Advertisement
fkudinov

Гра Сапер на Пайтоні

Aug 18th, 2024
51
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.70 KB | Source Code | 0 0
  1. # Гра Сапер
  2.  
  3. import random
  4.  
  5. DELTAS = [(0, 1), (0, -1), (1, 0),
  6.           (1, -1), (-1, 1), (-1, 0),
  7.           (1, 1), (-1, -1)]
  8. width = 5
  9. height = 10
  10. mines_count = 2
  11. mines = []
  12.  
  13. field = [[" -- "] * width for _ in range(height)]
  14. for i in range(mines_count):
  15.     empty = [(x, y) for x in range(width)
  16.                     for y in range(height)
  17.                     if (x, y) not in mines]
  18.     x, y = random.choice(empty)
  19.     mines.append((x, y))
  20.  
  21.  
  22. def mines_around(coord):
  23.     x, y = coord
  24.     return sum((dx + x, dy + y) in mines
  25.                for dx, dy in DELTAS)
  26.  
  27.  
  28. while True:
  29.     print(*field, sep="\n")
  30.  
  31.     coords = input("x, y")
  32.     try:
  33.         x, y = map(int, coords.split(","))
  34.         _ = field[y][x]
  35.     except Exception:
  36.         print(f"Incorrect: '{coords}', try again")
  37.         continue
  38.  
  39.     if (x, y) in mines:
  40.         print("You lost")
  41.         for m in mines:
  42.             field[m[1]][m[0]] = " ** "
  43.         field[y][x] = " XX "
  44.         break
  45.    
  46.     to_visit = [(x, y)]
  47.     while to_visit:
  48.         x, y = to_visit.pop()
  49.         field[y][x] = f" {mines_around((x, y)):02} "
  50.         if field[y][x] == " 00 ":
  51.             neighbours = [(dx + x, dy + y) for dx, dy in DELTAS
  52.                           if x + dx in range(width)
  53.                           and y + dy in range(height)
  54.                           and field[dy + y][dx + x] == " -- "]
  55.             to_visit.extend(neighbours)
  56.  
  57.     empty_cells = [(x, y) for x in range(width)
  58.                    for y in range(height)
  59.                    if field[y][x] == " -- "
  60.                    and (x, y) not in mines]
  61.     if not empty_cells:
  62.         print("You win")
  63.         break
  64.  
  65. print(*field, sep="\n")
  66.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement