-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfishTank.py
More file actions
392 lines (320 loc) · 12.9 KB
/
fishTank.py
File metadata and controls
392 lines (320 loc) · 12.9 KB
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
import random, sys, time
try:
import bext
except ImportError:
print('This program requires the bext module, which you')
print('can install by following the instruction at')
print('https://pypi.org/project/Bext/')
sys.exit()
# Set up constants:
WIDTH, HEIGHT = bext.size()
# Can't print to the last column on Windows without it adding a
# newline automatically, so reduce the width by one:
WIDTH -= 1
NUM_CRABS = 3 # NUMBER OF CRABS IN TANK
NUM_KELP = 2 # (!) TRY CHANGING THIS TO 10.
NUM_FISH = 10 # (!) TRY changing this to 2 or 100
NUM_BUBBLERS = 1 # (!) Try changing this to 0 or 10.
FRAMES_PER_SECOND = 4 # (!) try changing this number to 1 or 60.
# (!) try changing the constants to create a fish tank with only kelp.
# or only bubblers.
# NOTE: Every string in a fish dictionary should be the same length.
FISH_TYPES = [
{'right': ['><>'], 'left': ['<><']},
{'right': ['>||>'], 'left': ['<||<']},
{'right': ['))'], 'left': ['<[[<']},
{'right': ['>||o', '>||.'], 'left': ['o||<', '.||<']},
{'right': ['>))o', '>)).'], 'left': ['o[[<', '.[[<']},
{'right': ['>-==>'], 'left': ['<==-<']},
{'right': [r'>\\>'], 'left': ['<//<']},
{'right': ['><)))*>'], 'left': ['<*(((><']},
{'right': ['}-[[[*>'], 'left': ['<*]]]-{']},
{'right': [']-<)))b>'], 'left': ['<d(((<-[']},
{'right': ['><XXX*>'], 'left': ['<*XXX><']},
{'right': ['_.-._.-^=>', '.-._.-.^=>',
'-._.-._^=>', '._.-._.^=>'],
'left': ['<=^-._.-._', '<=^.-._.-.',
'<=^_.-._.-', '<=^._.-._.']},
] # (1) try adding fish to FISH_TYPES.
LONGEST_FISH_LENGTH = 10 # Longest single string in FISH_TYPES.
# NOTE crab dictionary
CRAB_TYPES = ['(v)', '<v>', '[v]', '{v}', '<(v)>', '[=v=]'] # You can get creative here!
# NOTE Castle dictionary
CASTLE_ART = [
" |>>> ",
" | ",
" /_\\ ",
" |___| ",
" |___| ",
" |___| ",
" |___| ",
" |___| ",
" |___| ",
]
LAST_CASTLE_POS = None # None or (x, y) of castle’s top-left
CASTLE_TIMER = 0 # Frames left before disappearing
CASTLE_DURATION = FRAMES_PER_SECOND * 5 # Visible for 5 seconds
# The x and y postions where a fish runs into the edge of the screen:
LEFT_EDGE = 0
RIGHT_EDGE = WIDTH - 1 - LONGEST_FISH_LENGTH
TOP_EDGE = 0
BOTTOM_EDGE = HEIGHT -2
def main():
global FISHES, BUBBLERS, BUBBLES, KELPS, STEP, CRABS
bext.bg('black')
bext.clear()
# Generate the global variables:
FISHES = []
for i in range(NUM_FISH):
FISHES.append(generateFish())
# NOTE: Bubbles are drawn, but not the bubblers themselves.
BUBBLERS = []
for i in range(NUM_BUBBLERS):
# Each bubbler starts at a random position.
BUBBLERS.append(random.randint(LEFT_EDGE, RIGHT_EDGE))
BUBBLES = []
KELPS = []
for i in range(NUM_KELP):
kelpx = random.randint(LEFT_EDGE, RIGHT_EDGE)
kelp = {'x': kelpx, 'segments' : []}
# Generate each segment of the kelp:
for i in range(random.randint(6, HEIGHT -1)):
kelp['segments'].append(random.choice(['(',')']))
KELPS.append(kelp)
# Initialize crabs
CRABS =[]
for _ in range(NUM_CRABS):
crab = {
'x': random.randint(LEFT_EDGE, WIDTH - 3),
'y': HEIGHT - 2,
'text': random.choice(CRAB_TYPES),
'color': getRandomColor(),
'direction': random.choice(['left', 'right']),
'speed' : random.randint(2, 6),
'timeToChange': random.randint(10, 40)
}
CRABS.append(crab)
# Run the simulation:
STEP = 1
while True:
simulateAquarium()
drawAquarium()
time.sleep(1 / FRAMES_PER_SECOND)
clearAquarium()
STEP += 1
def getRandomColor():
"""Return a string of a random color."""
return random.choice(('black', 'red', 'green', 'yellow', 'blue',
'purple', 'cyan', 'white'))
def generateFish():
"""Return a dictionary that represents a fish."""
fishType = random.choice(FISH_TYPES)
# Set up colors for each character in the fish text:
colorPattern = random.choice(('random', 'head-tail', 'single'))
fishLength = max(len(s) for s in fishType['right'] + fishType['left'])
if colorPattern == 'random': # All parts are randomly colored.
colors = []
for i in range(fishLength):
colors.append(getRandomColor())
if colorPattern == 'single' or colorPattern == 'head-tail':
colors = [getRandomColor()] * fishLength # All the same color.
if colorPattern == 'head-tail': # Head/tail different from body.
headTailColor = getRandomColor()
colors[0] = headTailColor # Set head color.
colors[-1] = headTailColor # set tail color.
# Set up the rest of fish data structure:
fish = {'right': fishType['right'],
'left': fishType['left'],
'colors': colors,
'hSpeed': random.randint(1, 6),
'vSpeed': random.randint(5, 15),
'timeToHDirChange': random.randint(10, 60),
'timeToVDirChange': random.randint(2, 20),
'goingRight': random.choice([True, False]),
'goingDown': random.choice([True, False])}
# 'x' is always the leftmost side of the fish body:
fish['x'] = random.randint(0, WIDTH - 1 - LONGEST_FISH_LENGTH)
fish['y'] = random.randint(0, HEIGHT - 2)
return fish
def simulateAquarium():
"""Simulate the movements in the aquarium for one step."""
global FISHES, BUBBLERS, BUBBLES, KELP, STEP, CASTLE_TIMER
if LAST_CASTLE_POS:
CASTLE_TIMER -= 1
# Simulate the fish for one step:
for fish in FISHES:
# Move the fish horizontally:
if STEP % fish['hSpeed'] == 0:
if fish['goingRight']:
if fish['x'] != RIGHT_EDGE:
fish['x'] += 1 #Move the fish right.
else:
fish['goingRight'] = False # Turn the fish around.
fish['colors'].reverse() # turn the colors around
else:
if fish['x'] != LEFT_EDGE:
fish['x'] -= 1 # Mover the fish left.
else:
fish['goingRight'] = True # Turn the fish around.
fish['colors'].reverse() # Turn the colors around.
# fish can randomly change their horizontal direction:
fish['timeToHDirChange'] -= 1
if fish['timeToHDirChange'] == 0:
fish['timeToHDirChange'] = random.randint(10, 60)
fish['goingRight'] = not fish['goingRight']
fish['hSpeed'] = random.randint(1, 6)
# Move the fish verically
if STEP % fish['vSpeed'] == 0:
if fish['goingDown']:
if fish['y'] != BOTTOM_EDGE:
fish['y'] += 1 # Move the fish down.
else:
fish['goingDown'] = False # Turn the fish around.
else:
if fish['y'] != TOP_EDGE:
fish['y'] -= 1 # Move the fish up.
else:
fish['goingDown'] = True # Turn the around.
# Fish can rndomly change their vertical direction and speed:
fish['timeToVDirChange'] -= 1
if fish['timeToVDirChange'] == 0:
# reset timer
fish['timeToVDirChange'] = random.randint(2, 20)
# flip vertical direction
fish['goingDown'] = not fish['goingDown']
# -- New line: pich a fresh vertical speed --
fish['vSpeed'] = random.randint(5, 15)
# 🦀 Simulate crab movement
for crab in CRABS:
if STEP % crab['speed'] == 0:
if crab['direction'] == 'right':
if crab['x'] < WIDTH - len(crab['text']):
crab['x'] += 1
else:
crab['direction'] = 'left'
else:
if crab['x'] > LEFT_EDGE:
crab['x'] -= 1
else:
crab['direction'] = 'right'
crab['timeToChange'] -= 1
if crab['timeToChange'] == 0:
crab['direction'] = random.choice(['left', 'right'])
crab['timeToChange'] = random.randint(10, 40)
# generate bubbles from bubblers:
for bubbler in BUBBLERS:
# There is a 1 in 5 chance of making a bubbble:
if random.randint(1, 5) ==1:
BUBBLES.append({'x': bubbler, 'y': HEIGHT -2})
# Move the bubbles:
for bubble in BUBBLES:
diceRoll = random.randint(1, 6)
if(diceRoll == 1) and (bubble['x'] != LEFT_EDGE):
bubble['x'] -= 1 # Bubble goes left.
elif (diceRoll == 2) and (bubble['x'] != RIGHT_EDGE):
bubble['x'] += 1 # Bubble goes right.
bubble['y'] -= 1 # the bubble always goes up.
# Iterate over BUBBLES in revers because I'm deleting from BUBBLES
# while iterating over it.
for i in range(len(BUBBLES) -1, -1, -1):
if BUBBLES[i]['y'] == TOP_EDGE: # Delete bubbles that reach the top.
del BUBBLES[i]
# Simulate the kelp waving for one step:
for kelp in KELPS:
for i, kelpSegment in enumerate(kelp['segments']):
# 1 in 20 chance to change waving:
if random.randint(1, 20) == 1:
if kelpSegment == '(':
kelp['segments'][i] = ')'
elif kelpSegment == ')':
kelp['segments'][i] = '('
def drawAquarium():
"""Draw the aquarium on the screen."""
global FISHES, BUBBLERS, BUBBLES, KELP, STEP, CRABS, LAST_CASTLE_POS, CASTLE_TIMER
# Draw quit message.
bext.fg('white')
bext.goto(0,0)
print('fish Tank, by AL Sweigart Ctrl-C to quit.', end='')
# Draw the bubbles:
bext.fg('white')
for bubble in BUBBLES:
bext.goto(bubble['x'], bubble['y'])
print(random.choice(('o', '0')), end='')
# Draw the fish:
for fish in FISHES:
bext.goto(fish['x'], fish['y'])
# Get the correct right- or left-facing fish txt.
if fish['goingRight']:
fishText = fish['right'][STEP % len(fish['right'])]
else:
fishText = fish['left'][STEP % len(fish['left'])]
# draw each character of the fish text in the right color.
for i, fishPart in enumerate(fishText):
bext.fg(fish['colors'][i])
print(fishPart, end='')
# Draw the kelp
bext.fg('green')
for kelp in KELPS:
for i, kelpSegment in enumerate(kelp['segments']):
if kelpSegment == '(':
bext.goto(kelp['x'], BOTTOM_EDGE - i)
elif kelpSegment == ')':
bext.goto(kelp['x'] + 1, BOTTOM_EDGE - i)
print(kelpSegment, end='')
# Draw the sand on the bottom:
bext.fg('yellow')
bext.goto(0, HEIGHT - 1)
print(chr(9617) * (WIDTH -1), end='') # Draws sand.
# 🦀 Draw the crabs
for crab in CRABS:
bext.fg(crab['color'])
bext.goto(crab['x'], crab['y'])
print(crab['text'], end='')
#if no castle active, randomly trigger one
if LAST_CASTLE_POS is None and random.randint(1, 20) == 1:
x = random.randint(0, WIDTH - len(CASTLE_ART[0]))
y = HEIGHT - 1 - len(CASTLE_ART)
LAST_CASTLE_POS = (x, y)
CASTLE_TIMER = CASTLE_DURATION
# Draw castle if active
if LAST_CASTLE_POS:
cx, cy = LAST_CASTLE_POS
for i, line in enumerate(CASTLE_ART):
bext.fg('white')
bext.goto(cx, cy + i)
print(line, end='')
sys.stdout.flush() # (Required for bext-using programs.)
def clearAquarium():
"""Draw empty spaces over everything on the screen."""
global FISHES, BUBBLERS, BUBBLES, KELP, CRABS, LAST_CASTLE_POS, CASTLE_TIMER
# Draw the bubbles:
for bubble in BUBBLES:
bext.goto(bubble['x'], bubble['y'])
print(' ', end='')
# Draw the fish:
for fish in FISHES:
bext.goto(fish['x'], fish['y'])
# Draw each character of the fish text in the right color.
print(' ' * len(fish['left'][0]), end='')
# Draw the kelp:
for kelp in KELPS:
for i, kelpSegment in enumerate(kelp['segments']):
bext.goto(kelp['x'], HEIGHT - 2 - i)
print(' ', end='')
# 🦀 Clear the crabs
for crab in CRABS:
bext.goto(crab['x'], crab['y'])
print(' ' * len(crab['text']), end='')
if LAST_CASTLE_POS and CASTLE_TIMER <= 0:
cx, cy = LAST_CASTLE_POS
for i, line in enumerate(CASTLE_ART):
bext.goto(cx, cy + i)
print(' ' * len(line), end='')
LAST_CASTLE_POS = None
sys.stdout.flush() # (Required for bext-using programs.)
# If this program was run(instead of imported), run the game:
if __name__ == '__main__':
try:
main()
except KeyboardInterrupt:
sys.exit() # When Ctrl-C is pressed, end the program.