-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtools.py
54 lines (42 loc) · 1.53 KB
/
tools.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
"""tools.py
A number of tools useful for making the board readable by a human.
Functions:
pic_to_board(string filename) returns Board()
save_as_pic(Board() board, string filename) void
board_to_string(Board() board) string output
"""
from PIL import Image
from cells import *
from Board import Board
def pic_to_board(filename):
"""Convert the file located at filename to a Board() object."""
image = Image.open(filename).convert("RGB")
rgb_data = list(image.getdata())
width, height = image.size
image.close()
# convert rgb_data from rgb tuples to cells
for ii, cell in enumerate(rgb_data):
rgb_data[ii] = from_rgb(cell)
data = []
for k in range(0,len(rgb_data),width):
data.append(rgb_data[k:width+k])
return Board(width, height, data)
def save_as_pic(board, filename):
"""Save the board as an image located at filename."""
image = Image.new("RGB",board.size())
rgb_data = []
for row in board.data():
for cell in row:
rgb_data.append(to_rgb(cell))
image.putdata(rgb_data)
image.save(filename,"PNG")
def board_to_string(board):
"""Return a string representing the board."""
data = board.data()
data_strings = [] # 1D list of strings; e.g. ["RBB","B B"]
for row in data:
row_as_strings = []
for cell in row:
row_as_strings.append(to_string(cell))
data_strings.append("".join(row_as_strings))
return "\n".join(data_strings)