Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import keyboard
- import time
- import random
- height = 10
- width = 8
- direction = "l"
- player = [(5, 5)]
- length = 5
- walls = [
- (1, 1), (4, 6), (3, 4)
- ]
- apple = (1, 5)
- alive = True
- shift = {
- "l": (-1, 0),
- "r": (1, 0),
- "u": (0, -1),
- "d": (0, 1)
- }
- def print_world():
- world = [[" "] * width for _ in range(height)]
- for wall in walls:
- world[wall[1]][wall[0]] = " XX "
- world[apple[1]][apple[0]] = " 0 "
- world[player[0][1]][player[0][0]] = " oo " if alive else " xx "
- for segment in player[1:]:
- world[segment[1]][segment[0]] = " () "
- print("-----" * width)
- for i in world:
- print("|" + " ".join(i) + "|")
- print("-----" * width)
- print()
- def is_in_world(coord):
- return coord[0] in range(width) and coord[1] in range(height)
- def get_action():
- # action = input()
- action = ""
- if keyboard.is_pressed("w"):
- action = "u"
- elif keyboard.is_pressed("s"):
- action = "d"
- elif keyboard.is_pressed("a"):
- action = "l"
- elif keyboard.is_pressed("d"):
- action = "r"
- return action
- def get_free_cells():
- return list(set({(i, j) for i in range(width)
- for j in range(height)})
- - set(player)
- - {apple}
- - set(walls))
- print_world()
- while alive:
- if apple == player[0]:
- length += 1
- apple = random.choice(get_free_cells())
- action = get_action()
- if action in set("lrud"):
- direction = action
- next_cell = (player[0][0] + shift[direction][0],
- player[0][1] + shift[direction][1])
- if (not is_in_world(next_cell)
- or next_cell in walls
- or next_cell in player[1:]):
- alive = False
- print_world()
- break
- player.insert(0, (player[0][0] + shift[direction][0],
- player[0][1] + shift[direction][1]))
- player = player[:length]
- print_world()
- time.sleep(0.5)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement