Advertisement
fkudinov

Гра Sokoban / Робоча версія з keyboard

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