Advertisement
fkudinov

Гра Змійка / Робоча версія з keyboard

Jan 21st, 2024 (edited)
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.05 KB | Source Code | 0 0
  1. import keyboard
  2. import time
  3. import random
  4.  
  5. height = 10
  6. width = 8
  7.  
  8. direction = "l"
  9. player = [(5, 5)]
  10. length = 5
  11. walls = [
  12.     (1, 1), (4, 6), (3, 4)
  13. ]
  14. apple = (1, 5)
  15. alive = True
  16.  
  17. shift = {
  18.     "l": (-1, 0),
  19.     "r": (1, 0),
  20.     "u": (0, -1),
  21.     "d": (0, 1)
  22. }
  23.  
  24.  
  25. def print_world():
  26.     world = [["    "] * width for _ in range(height)]
  27.  
  28.     for wall in walls:
  29.         world[wall[1]][wall[0]] = " XX "
  30.  
  31.     world[apple[1]][apple[0]] = " 0  "
  32.  
  33.     world[player[0][1]][player[0][0]] = " oo " if alive else " xx "
  34.     for segment in player[1:]:
  35.         world[segment[1]][segment[0]] = " () "
  36.  
  37.     print("-----" * width)
  38.     for i in world:
  39.         print("|" + " ".join(i) + "|")
  40.     print("-----" * width)
  41.     print()
  42.  
  43.  
  44. def is_in_world(coord):
  45.     return coord[0] in range(width) and coord[1] in range(height)
  46.  
  47.  
  48. def get_action():
  49.     # action = input()
  50.  
  51.     action = ""
  52.     if keyboard.is_pressed("w"):
  53.         action = "u"
  54.     elif keyboard.is_pressed("s"):
  55.         action = "d"
  56.     elif keyboard.is_pressed("a"):
  57.         action = "l"
  58.     elif keyboard.is_pressed("d"):
  59.         action = "r"
  60.     return action
  61.  
  62.  
  63. def get_free_cells():
  64.     return list(set({(i, j) for i in range(width)
  65.                      for j in range(height)})
  66.                 - set(player)
  67.                 - {apple}
  68.                 - set(walls))
  69.  
  70.  
  71. print_world()
  72. while alive:
  73.  
  74.     if apple == player[0]:
  75.         length += 1
  76.         apple = random.choice(get_free_cells())
  77.  
  78.     action = get_action()
  79.  
  80.     if action in set("lrud"):
  81.         direction = action
  82.  
  83.     next_cell = (player[0][0] + shift[direction][0],
  84.                  player[0][1] + shift[direction][1])
  85.  
  86.     if (not is_in_world(next_cell)
  87.             or next_cell in walls
  88.             or next_cell in player[1:]):
  89.         alive = False
  90.         print_world()
  91.         break
  92.  
  93.     player.insert(0, (player[0][0] + shift[direction][0],
  94.                                     player[0][1] + shift[direction][1]))
  95.     player = player[:length]
  96.  
  97.     print_world()
  98.     time.sleep(0.5)
  99.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement