| 1 | 1 | | from typing import List, Tuple |
| 1 | 2 | | from minesweeper.mineitem import MineItem |
| 1 | 3 | | from random import sample |
| 1 | 4 | | from injector import inject |
| | 5 | |
|
| | 6 | |
|
| 1 | 7 | | class MineMap: |
| 1 | 8 | | def __getitem__(self, n): |
| 1 | 9 | | def getitem(xy): |
| 1 | 10 | | x, y = xy |
| 1 | 11 | | return ( |
| | 12 | | None |
| | 13 | | if x < 0 or y < 0 or x >= self._width or y >= self._height |
| | 14 | | else self._items[y * self._width + x] |
| | 15 | | ) |
| | 16 | |
|
| 1 | 17 | | def convert_index_int_to_tuple(n): |
| 1 | 18 | | return reversed(divmod(n, self._width)) |
| | 19 | |
|
| 1 | 20 | | if isinstance(n, tuple): |
| 1 | 21 | | return getitem(n) |
| | 22 | | else: |
| 1 | 23 | | return getitem(convert_index_int_to_tuple(n)) |
| | 24 | |
|
| 1 | 25 | | def __init__( |
| | 26 | | self, |
| | 27 | | width: int, |
| | 28 | | height: int, |
| | 29 | | pos_bombs: List[Tuple[int, int]] = [], |
| | 30 | | random_bombs=0, |
| | 31 | | ): |
| 1 | 32 | | self._width = width |
| 1 | 33 | | self._height = height |
| 1 | 34 | | self._items = [ |
| | 35 | | MineItem(self.near_items_generator((x, y))) |
| | 36 | | for y in range(height) |
| | 37 | | for x in range(width) |
| | 38 | | ] |
| | 39 | |
|
| 1 | 40 | | def select_bomb_items(): |
| 1 | 41 | | return ( |
| | 42 | | map(lambda xy: self[xy], pos_bombs) |
| | 43 | | if random_bombs == 0 |
| | 44 | | else (self[i] for i in sample(range(0, width * height), random_bombs)) |
| | 45 | | ) |
| | 46 | |
|
| 1 | 47 | | for item in select_bomb_items(): |
| 1 | 48 | | item.set_bomb() |
| | 49 | |
|
| 1 | 50 | | def near_items_generator(self, xy): |
| 1 | 51 | | x, y = xy |
| | 52 | |
|
| 1 | 53 | | def nears(): |
| 1 | 54 | | yield self[(x - 1, y - 1)] |
| 1 | 55 | | yield self[(x, y - 1)] |
| 1 | 56 | | yield self[(x + 1, y - 1)] |
| 1 | 57 | | yield self[(x - 1, y)] |
| 1 | 58 | | yield self[(x + 1, y)] |
| 1 | 59 | | yield self[(x - 1, y + 1)] |
| 1 | 60 | | yield self[(x, y + 1)] |
| 1 | 61 | | yield self[(x + 1, y + 1)] |
| | 62 | |
|
| 1 | 63 | | return (x for x in nears() if x is not None) |
| | 64 | |
|
| 1 | 65 | | def __str__(self): |
| 1 | 66 | | return "".join(str(x) for x in self._items) |
| | 67 | |
|
| 1 | 68 | | def click(self, x, y): |
| 1 | 69 | | self[(x, y)].click() |