-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgol.py
executable file
·435 lines (327 loc) · 12.4 KB
/
gol.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
#!/usr/bin/python2.6
import os
import sys
import string
import curses
import itertools
import random
from optparse import OptionParser
"""
This is a python, curses implimentation of Conway's game of life
v1.0 (2010-05-15)
by Daniel Thau, Morgan Goose
Licensed under the GPLv2
"""
def load_board(filename, board):
"""
loads the file argument into the board
"""
global options
if filename.endswith(".gol") or options.file_format == "gol":
return _explicit_board(filename, board)
elif filename.endswith(".rle") or options.file_format == "rle":
return _rle_board(filename, board)
else:
raise Exception("Do not know board format.")
def _decode(line):
"""
Take encoded string and return expanded form
"""
decoded, counting = "", ""
for c in list(line):
if c in ["b", "o"] and not counting:
decoded += c
elif c in ["b", "o"] and counting:
decoded += c*int(counting)
counting = ""
elif c in string.digits:
counting += c
return decoded
def _rle_board(filename, board):
"""
Lets us use the rle format as explained here:
http://conwaylife.com/wiki/index.php?title=RLE
"""
with open(filename) as rle_file:
loaded_rle = rle_file.readlines()
pattern = []
for line in loaded_rle:
if not line.startswith("#"):
if line.startswith("x"):
if "rule" in line:
x, y, rule = line.split(',')
else:
x, y = line.split(',')
else:
pattern.extend(line.split("$"))
cols = int(x.split("=")[-1])
rows = int(y.split("=")[-1])
if cols > len(board[0]) or rows > len(board):
raise Exception("\nPattern too large:\n\trows: %s\n\tcols: %s\
\nwhere:\n\tx: %s\n\ty: %s" % (
rows, cols, len(board), len(board[0])))
row_offset = col_offset = 0
if cols/2 < len(board[0]) and rows/2 < len(board):
row_offset = (len(board) - rows)/2
col_offset = (len(board[0]) - cols)/2
trans = {'b':0, 'o':1}
row = 0
for line in pattern:
col = 0
decoded = _decode(line)
for char in decoded:
if char in ['b', 'o']:
board[row+row_offset][col+col_offset] = trans[char]
col += 1
row += 1
return board
def _explicit_board(filename, board):
with open(filename,'r') as f:
loaded_file = f.readlines()
# finding row/col offset to center file on board
rows = cols = 0
for line in loaded_file:
rows+=1
if len(line)>cols:
cols=len(line)
row_offset=(len(board)-rows)/2
col_offset=(len(board[0])-cols)/2
row = 0
for line in loaded_file:
col = 0
for char in line:
if char in ['0', '1']:
board[row+row_offset][col+col_offset] = int(char)
col += 1
row += 1
return board
def new_board(screen_width, screen_height):
"""
create empty board
"""
return [[0 for i in range(screen_width)] for j in range(screen_height)]
def random_board(screen_width, screen_height):
"""
create random board
"""
return [[random.randint(0,1) for i in range(screen_width)] for j in range(screen_height)]
def draw_board(screen, board):
"""
draw board onto screen
"""
global options
chars = {
0:' ', 1:'#', 2:'*', 3:'o',
4:'`', 5:'"', 6:"'", 7:'-',
8:'.', 9:'x',
}
if options.foreground:
for key in chars.keys():
if key:
chars[key] = options.foreground
if options.background:
chars[0] = options.background
color = 0
if options.color:
colors ={
0:curses.color_pair(5),
1:curses.color_pair(1),
2:curses.color_pair(2),
3:curses.color_pair(3),
4:curses.color_pair(4),
5:curses.color_pair(1),
6:curses.color_pair(2),
7:curses.color_pair(3),
8:curses.color_pair(4),
9:curses.color_pair(6),
}
for row in range(len(board)):
for col in range(len(board[0])):
spot = board[row][col]
# ensures lifetime variable doesn't excede available rendering range
spot = 9 if spot>9 else spot
char = chars[spot]
if options.color:
color = colors[spot]
screen.addstr(row, col*2, char, color)
def check_life_simple(screen, board):
"""
follows Conway's Game of Life rules to determine which cells
are alive in the next frame. Does not keep track of anything
more than life/death.
"""
nextboard=new_board(len(board[0]),len(board))
for row in range(len(board)):
for col in range(len(board[0])):
live_neighbors = 0
# checking neighbors
for row_offset in [-1,0,1]:
for col_offset in [-1,0,1]:
check_row = row+row_offset
if check_row < 0:
check_row = len(board)-1
if check_row == len(board):
check_row = 0
check_col = col+col_offset
if check_col < 0:
check_col = len(board[0])-1
if check_col == len(board[0]):
check_col = 0
#if board[check_row][check_col] == 1:
if board[check_row][check_col] >= 1:
live_neighbors += 1
if board[row][col] == 0 and live_neighbors == 3:
nextboard[row][col] = 1
elif board[row][col] > 0:
# checking for 3 or 4 since actual cell was counted as a neighbor
if live_neighbors in [3,4]:
nextboard[row][col] = 1
return nextboard
def check_life_neighbor(screen, board):
"""
follows Conway's Game of Life rules to determine which cells
are alive in the next frame. Keeps track of the number of
living neighbors.
"""
nextboard=new_board(len(board[0]),len(board))
for row in range(len(board)):
for col in range(len(board[0])):
live_neighbors = 0
# checking neighbors
for row_offset in [-1,0,1]:
for col_offset in [-1,0,1]:
check_row = row+row_offset
if check_row < 0:
check_row = len(board)-1
if check_row == len(board):
check_row = 0
check_col = col+col_offset
if check_col < 0:
check_col = len(board[0])-1
if check_col == len(board[0]):
check_col = 0
#if board[check_row][check_col] == 1:
if board[check_row][check_col] >= 1:
live_neighbors += 1
if board[row][col] == 0 and live_neighbors == 3:
nextboard[row][col] = 1
elif board[row][col] > 0:
# checking for 3 or 4 since actual cell was counted as a neighbor
if live_neighbors in [3,4]:
nextboard[row][col] += live_neighbors
return nextboard
def check_life_lifetime(screen, board):
"""
follows Conway's Game of Life rules to determine which cells
are alive in the next frame. Keeps track of the number of
frames a cell has been alive
"""
nextboard=new_board(len(board[0]),len(board))
for row in range(len(board)):
for col in range(len(board[0])):
live_neighbors = 0
# checking neighbors
for row_offset in [-1,0,1]:
for col_offset in [-1,0,1]:
check_row = row+row_offset
if check_row < 0:
check_row = len(board)-1
if check_row == len(board):
check_row = 0
check_col = col+col_offset
if check_col < 0:
check_col = len(board[0])-1
if check_col == len(board[0]):
check_col = 0
#if board[check_row][check_col] == 1:
if board[check_row][check_col] >= 1:
live_neighbors += 1
if board[row][col] == 0 and live_neighbors == 3:
nextboard[row][col] = 1
elif board[row][col] > 0:
# checking for 3 or 4 since actual cell was counted as a neighbor
if live_neighbors in [3,4]:
nextboard[row][col] = board[row][col]+1
return nextboard
def main(screen, pause_between_frames, filename):
"""
main loop
"""
screen_height=screen.getmaxyx()[0]
screen_width=screen.getmaxyx()[1]/2-1
curses.curs_set(0) # makes cursor invisible
if options.color:
#Get some color settings in the works
curses.start_color()
colors = [curses.COLOR_GREEN, curses.COLOR_YELLOW, curses.COLOR_BLUE,
curses.COLOR_CYAN, curses.COLOR_WHITE, curses.COLOR_RED]
black = curses.COLOR_BLACK
for i, (color, bg) in enumerate([(c, black) for c in colors], start=1):
curses.init_pair(i, color, bg)
if options.random:
board = random_board(screen_width,screen_height)
else:
board = load_board(filename,new_board(screen_width,screen_height))
check_func = {
'0': check_life_simple,
'1': check_life_neighbor,
'2': check_life_lifetime,
'simple': check_life_simple,
'neighbor': check_life_neighbor,
'lifetime': check_life_lifetime,
}.get(options.track, check_life_simple)
while True:
draw_board(screen, board)
board = check_func(screen, board)
screen.refresh()
if pause_between_frames:
screen.getch()
if __name__ == '__main__':
global options
parser = OptionParser()
def _check_len(option, opt_str, value, parser):
print option, opt_str, value, parser
if len(value) != 1:
parser.error("%s value invalid for this option. Need single char" % value)
setattr(parser.values, option.dest, value)
parser.add_option("-p", "--pause", dest="pause_between_frames",
default=False, action="store_true",
help="pause for input between frames.")
parser.add_option("-c", "--color", dest="color",
default=False, action="store_true",
help="sets whether to enable color or not.")
parser.add_option("-t", "--track", dest="track",
default="", action="store", metavar="#",
help="sets what to track (0=simple, 1=neighbors, 2=lifetime).")
parser.add_option("-o", "--format", dest="file_format",
default="", action="store", metavar="FMT",
help="will take either gol or rle as options.")
parser.add_option("-b", "--background", dest="background",
#default="", action="store", metavar="CHAR",
#help="sets the background character")
default="", action="callback", callback=_check_len,
metavar="CHAR", nargs=1, type='string',
help="sets the background character")
parser.add_option("-f", "--foreground", dest="foreground",
#default="", action="store", metavar="CHAR",
#help="sets the foreground character")
default="", action="callback", callback=_check_len,
metavar="CHAR", nargs=1, type='string',
help="sets the foreground character")
parser.add_option("-d", "--random", dest="random",
default=False, action="store_true",
help="creats a random board")
(options, args) = parser.parse_args()
files = []
for arg in args:
if not os.path.exists(arg):
print "File not found, quitting"
sys.exit()
else:
files.append(arg)
if options.random and not files:
files.append('random') # just to ensure we don't trip the no-file warning
if not files:
print "No files given, quitting."
sys.exit()
curses.wrapper(main, options.pause_between_frames, files[0])