-
Notifications
You must be signed in to change notification settings - Fork 0
/
game.py
488 lines (387 loc) · 17 KB
/
game.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
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
from __future__ import print_function, division
import math
from CYLGame import GameLanguage
from CYLGame import GridGame
from CYLGame import MessagePanel
from CYLGame import MapPanel
from CYLGame import StatusPanel
from CYLGame import PanelBorder
from CYLGame.Player import DefaultGridPlayer
class AppleFinder(GridGame):
MAP_WIDTH = 60
MAP_HEIGHT = 25
SCREEN_WIDTH = 60
SCREEN_HEIGHT = MAP_HEIGHT + 6
MSG_START = 20
MAX_MSG_LEN = SCREEN_WIDTH - MSG_START - 1
CHAR_WIDTH = 16
CHAR_HEIGHT = 16
GAME_TITLE = "FarmBot 5000"
CHAR_SET = "resources/farmbot-terminal16x16_gs_ro.png"
NUM_OF_APPLES = 4
NUM_OF_HOLES_START = 10
NUM_OF_HOLES_PER_LEVEL = 10
MAX_TURNS = 1000
MAX_PONDS = 3
MAX_POND_SIZE = 8
# will start from the base tile set
PLAYER = chr(255)
WATER = chr(247)
MOUNTAIN = chr(30)
GROUND = chr(176)
HOLE = ' '
BASE = '#'
# will start by using numbers for plant growth stages
ROCK = chr(239)
BEAST = chr(2)
TREE1 = chr(5)
TREE2 = chr(6)
EMPTY = GROUND
APPLE = chr(15)
APPLE = 'O'
BASE = chr(233)
def __init__(self, random):
self.random = random
self.running = True
self.player_start_x = 0
self.player_start_y = 0
self.max_energy = 200
self.base_energy = 160
self.energy = self.base_energy
self.apples_eaten = 0
self.apples_left = 0
self.apple_pos = []
self.objects = []
self.turns = 0
self.level = 0
self.msg_panel = MessagePanel(self.MSG_START, self.MAP_HEIGHT+1, self.SCREEN_WIDTH - self.MSG_START, 5)
self.status_panel = StatusPanel(0, self.MAP_HEIGHT+1, self.MSG_START, 5)
self.panels = [self.msg_panel, self.status_panel]
self.msg_panel.add("Welcome to " + self.GAME_TITLE + "!!!")
self.msg_panel.add("Try to grow plants and collect seeds!")
def init_board(self):
self.map = MapPanel(0, 0, self.MAP_WIDTH, self.MAP_HEIGHT, self.EMPTY,
border=PanelBorder.create(bottom="-"))
self.panels += [self.map]
self.place_rocks(10)
self.place_holes(self.NUM_OF_HOLES_START)
# check all holes for water adjacency
for x in range(self.MAP_WIDTH - 1):
for y in range(self.MAP_HEIGHT - 1):
if self.map[(x, y)] == self.HOLE:
self.water_check((x,y))
self.place_apples(self.NUM_OF_APPLES)
self.place_ponds(self.MAX_POND_SIZE, self.MAX_PONDS)
self.carve_river()
# place robot and base randomly
# robot and base cannot start in water
has_safe_loc = False
while not has_safe_loc:
# pick a starting x y location that isn't water
self.player_start_x = self.random.randint(0, self.MAP_WIDTH - 1)
self.player_start_y = self.random.randint(0, self.MAP_HEIGHT - 1)
if self.map[(self.player_start_x, self.player_start_y)] != self.WATER:
has_safe_loc = True # found a safe spot
self.player_pos = [self.player_start_x, self.player_start_y]
self.underneath_robot = self.BASE # thing underneath the player
def add_check_energy(self, amount):
self.energy += amount
if self.energy > 200:
self.energy == 200
def create_new_player(self, prog):
self.player = DefaultGridPlayer(prog, self.get_move_consts())
self.map[(self.player_pos[0], self.player_pos[1])] = self.PLAYER
self.update_vars_for_player()
return self.player
def start_game(self):
pass
def place_apples(self, count):
self.place_objects(self.APPLE, count)
self.apples_left = self.apples_left + count
def place_rocks(self, count):
self.place_objects(self.ROCK, count)
def place_holes(self, count):
self.place_objects(self.HOLE, count)
def carve_river(self):
# run a river across the map
# the river starts on the left or top side of the screen
# does a random-ish walk until it hits another map boundary
# if on left, cannot move "west" and prefers "east"
# if no top, cannot move "north" and prefers "south"
starts = ["north", "east"]
start = starts[self.random.randint(0,1)]
direction = None
river_x = 0
river_y = 0
if start == "north":
river_x = self.random.randint(0, self.MAP_WIDTH - 1)
direction = "south"
else:
river_y = self.random.randint(0, self.MAP_HEIGHT - 1)
direction = "west"
print("River will go %s, starting from (%d, %d)." % (direction, river_x, river_y))
self.map[(river_x, river_y)] = self.WATER
hit_edge = False
while not hit_edge:
if direction == "south":
deck = [(0, 1), (0,1), (-1, 0), (1, 0)]
else:
deck = [(1, 0), (1,0), (0, -1), (0, 1)]
self.random.shuffle(deck)
river_x += deck[0][0]
river_y += deck[0][1]
if river_x >= self.MAP_WIDTH or river_x < 0:
hit_edge = True
elif river_y >= self.MAP_HEIGHT or river_y < 0:
hit_edge = True
else:
self.map[(river_x, river_y)] = self.WATER
def carve_river(self):
# run a river across the map
# the river starts on the left or top side of the screen
# does a random-ish walk until it hits another map boundary
# if on left, cannot move "west" and prefers "east"
# if no top, cannot move "north" and prefers "south"
starts = ["north", "east"]
start = starts[self.random.randint(0,1)]
direction = None
river_x = 0
river_y = 0
if start == "north":
river_x = self.random.randint(0, self.MAP_WIDTH)
direction = "south"
else:
river_y = self.random.randint(0, self.MAP_HEIGHT)
direction = "west"
print("River will go %s, starting from (%d, %d)." % (direction, river_x, river_y))
self.map[(river_x, river_y)] = self.WATER
hit_edge = False
while not hit_edge:
if direction == "south":
deck = [(0, 1), (0,1), (-1, 0), (1, 0)]
else:
deck = [(1, 0), (1,0), (0, -1), (0, 1)]
self.random.shuffle(deck)
river_x += deck[0][0]
river_y += deck[0][1]
if river_x == self.MAP_WIDTH or river_x < 0:
hit_edge = True
elif river_y == self.MAP_HEIGHT or river_y < 0:
hit_edge = True
else:
self.map[(river_x, river_y)] = self.WATER
def place_ponds(self, max_size, max_count):
# pick a random location that is at least max_size from
# right side of screen
for i in range(self.MAX_PONDS):
pond_width = self.random.randint(0, max_size) # this pond's width
if pond_width:
print("making a pond of width %d..." % (pond_width))
pond_x = self.random.randint(0, self.MAP_WIDTH - pond_width) # pond x loc
pond_y = self.random.randint(pond_width, self.MAP_HEIGHT - pond_width) # pond y loc
# draw pond's initial line
for j in range(pond_width):
self.map[(pond_x + j, pond_y)] = self.WATER
# draw pond's upper and lower lines
y_offset = 1 # above and below
x_offset = 1
linelen = pond_width - 2
while linelen > 0:
for j in range(linelen):
self.map[(pond_x + x_offset + j, pond_y + y_offset)] = self.WATER
self.map[(pond_x + x_offset + j, pond_y - y_offset)] = self.WATER
linelen -= 2
y_offset += 1
x_offset += 1
def place_objects(self, char, count):
placed_objects = 0
while placed_objects < count:
x = self.random.randint(0, self.MAP_WIDTH - 1)
y = self.random.randint(0, self.MAP_HEIGHT - 1)
if self.map[(x, y)] == self.EMPTY:
self.map[(x, y)] = char
placed_objects += 1
def do_turn(self):
self.handle_key(self.player.move)
self.update_vars_for_player()
def water_check(self, location):
# if this hole is touching water, change it to water
# then, recursively check all non-water neighbors
neighbors = [(1,0), (-1,0), (0,1), (0,-1)]
print("Hole at (%d,%d) -- does it have a water neighbor?" % (location[0], location[1]))
for neighbor in neighbors:
test_x = location[0] + neighbor[0]
test_y = location[1] + neighbor[1]
if (test_x > self.MAP_WIDTH - 1 or test_y > self.MAP_HEIGHT - 1
or test_x < 0 or test_y < 0):
continue
if self.map[(test_x, test_y)] == self.WATER:
print("We found water at neighbor %d,%d! Filling (%d,%d)" %
(test_x, test_y, location[0], location[1]))
# if a neighbor is water, then I'm water
self.map[(location[0], location[1])] = self.WATER
if location == self.player_pos:
self.underneath_robot = self.WATER
# if I'm water, then recurse for any of my neighbors
# if those neighbors are HOLES
for neighbor in neighbors:
recurse_x = location[0] + neighbor[0]
recurse_y = location[1] + neighbor[1]
if self.map[(recurse_x, recurse_y)] == self.HOLE:
print("Recursing to check HOLE neighbor at (%d,%d)..." %
(recurse_x, recurse_y))
self.water_check((recurse_x, recurse_y))
def handle_key(self, key):
self.turns += 1
# when robot moves, we restore what was underneath robot
self.map[(self.player_pos[0], self.player_pos[1])] = self.underneath_robot
if key == "w":
self.player_pos[1] -= 1
if key == "s":
self.player_pos[1] += 1
if key == "a":
self.player_pos[0] -= 1
if key == "d":
self.player_pos[0] += 1
if key == "Q":
self.running = False
return
# check for collisions and reverse the movement if necessary
if self.map[(self.player_pos[0], self.player_pos[1])] == self.ROCK:
self.msg_panel.add("You bumped into a rock!")
# if the new position is a rock, move robot back
# but lose your turn
if key == "w":
self.player_pos[1] += 1
elif key == "s":
self.player_pos[1] -= 1
elif key == "a":
self.player_pos[0] += 1
elif key == "d":
self.player_pos[0] -= 1
# robot can "warp" around the edges of the map
# this may not be what we want...
self.player_pos[0] %= self.MAP_WIDTH
self.player_pos[1] %= self.MAP_HEIGHT
# robot eats an apple
if self.map[(self.player_pos[0], self.player_pos[1])] == self.APPLE:
self.apples_eaten += 1
self.apples_left -= 1
self.msg_panel.add("You ate an apple and got 20 energy!")
self.map[(self.player_pos[0], self.player_pos[1])] = self.EMPTY # apple eaten
self.add_check_energy(20) # eating an apple gives some energy
# check for collisions and reverse the movement if necessary
if self.map[(self.player_pos[0], self.player_pos[1])] == self.BASE:
self.msg_panel.add("You returned to base!")
if self.energy < self.base_energy:
self.msg_panel.add("Charging you up to 160!")
self.energy = self.base_energy
else:
self.msg_panel.add("Already above 160.")
# update new player position
# save what robot is going to step on
self.underneath_robot = self.map[(self.player_pos[0], self.player_pos[1])]
# move robot onto that item
self.map[(self.player_pos[0], self.player_pos[1])] = self.PLAYER
# player digs a hole
# fill hole with water if adjacent to water
if key == "x":
self.map[(self.player_pos[0], self.player_pos[1])] = self.HOLE
self.underneath_robot = self.HOLE
# check hole -- and any adjacent holes -- for water
self.water_check(self.player_pos)
# fix up map in case hole was filled with water
self.map[(self.player_pos[0], self.player_pos[1])] = self.PLAYER
# calculate move costs
pmoved = False # did the player initiate this move?
if key in "wasd":
# these things cost 1 E
self.energy -= 1
pmoved = True # this player moved THEMSELVES
elif key in "x":
# these things cost 5 E
self.energy -= 5
if pmoved and self.underneath_robot == self.WATER:
self.energy -= 1 # swimming costs 2 total
self.msg_panel.add("Swimming is hard!")
# End of the game
if self.turns >= self.MAX_TURNS:
self.running = False
self.msg_panel.add("You are out of moves.")
elif self.energy <= 0:
self.running = False
self.msg_panel.add("You ran out of energy.")
elif self.underneath_robot == self.HOLE and pmoved:
# game over if stepped into a hole
# but not if they dug themselves into a hole
self.running = False
self.msg_panel.add("You fell into a hole :(")
print("You fell into a hole!")
def is_running(self):
return self.running
def find_closest_apple(self, x, y):
apple_pos_dist = []
for pos in self.map.get_all_pos(self.APPLE):
for i in range(-1, 2):
for j in range(-1, 2):
a_x, a_y = pos[0]+(self.MAP_WIDTH*i), pos[1]+(self.MAP_HEIGHT*j)
dist = math.sqrt((a_x-x)**2 + (a_y-y)**2)
direction = [a_x-x, a_y-y]
if direction[0] > 0:
direction[0] = 1
elif direction[0] < 0:
direction[0] = -1
if direction[1] > 0:
direction[1] = 1
elif direction[1] < 0:
direction[1] = -1
apple_pos_dist += [(dist, direction)]
apple_pos_dist.sort()
if len(apple_pos_dist) > 0:
return apple_pos_dist[0][1]
else:
raise Exception("We didn't find an apple")
def update_vars_for_player(self):
bot_vars = {}
# look for closest apple -- disabled for now
# x_dir, y_dir = self.find_closest_apple(*self.player_pos)
#
# x_dir_to_char = {-1: ord("a"), 1: ord("d"), 0: 0}
# y_dir_to_char = {-1: ord("w"), 1: ord("s"), 0: 0}
# bot_vars = {"x_dir": x_dir_to_char[x_dir], "y_dir": y_dir_to_char[y_dir],
# "pit_to_east": 0, "pit_to_west": 0, "pit_to_north": 0, "pit_to_south": 0}
# bot_vars = {"x_dir": x_dir_to_char[x_dir], "y_dir": y_dir_to_char[y_dir],
# "pit_to_east": 0, "pit_to_west": 0, "pit_to_north": 0, "pit_to_south": 0}
# if self.map[((self.player_pos[0]+1)%self.MAP_WIDTH, self.player_pos[1])] == self.PIT:
# bot_vars["pit_to_east"] = 1
# if self.map[((self.player_pos[0]-1)%self.MAP_WIDTH, self.player_pos[1])] == self.PIT:
# bot_vars["pit_to_west"] = 1
# if self.map[(self.player_pos[0], (self.player_pos[1]-1)%self.MAP_HEIGHT)] == self.PIT:
# bot_vars["pit_to_north"] = 1
# if self.map[(self.player_pos[0], (self.player_pos[1]+1)%self.MAP_HEIGHT)] == self.PIT:
# bot_vars["pit_to_south"] = 1
self.player.bot_vars = bot_vars
@staticmethod
def default_prog_for_bot(language):
if language == GameLanguage.LITTLEPY:
return open("resources/apple_bot.lp", "r").read()
@staticmethod
def get_intro():
return open("resources/intro.md", "r").read()
def get_score(self):
return self.apples_eaten
def draw_screen(self, frame_buffer):
if not self.running:
if self.apples_eaten == 0:
self.msg_panel.add("You ate " + str(self.apples_eaten) + " apples. Better luck next time :(")
else:
self.msg_panel.add("You ate " + str(self.apples_eaten) + " apples. Good job!")
# Update Status
self.status_panel["Energy"] = self.energy
self.status_panel["Apples"] = self.apples_eaten
self.status_panel["Move"] = str(self.turns) + " of " + str(self.MAX_TURNS)
for panel in self.panels:
panel.redraw(frame_buffer)
if __name__ == '__main__':
from CYLGame import run
run(AppleFinder)