1 / 1 / 0
Регистрация: 27.11.2020
Сообщений: 6
1

Папа сапёра

08.12.2021, 13:46. Показов 3937. Ответов 1
Метки нет (Все метки)

Author24 — интернет-сервис помощи студентам
Добавьте в класс Dedushka из классной задачи автоматическое открывание пустых областей (измените функцию open_cell(self)) при щелчке на пустую клетку.

Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
import pygame
import random
 
class Board:
    def __init__(self, width, height):
        self.width = width
        self.height = height
        self.board = [[0] * width for _ in range(height)]
        self.left = 10
        self.top = 10
        self.cell_size = 30
 
    def set_view(self, left, top, cell_size):
        self.left = left
        self.top = top
        self.cell_size = cell_size
 
    def render(self, screen):
        color = pygame.Color('white')
        for y in range(self.height):
            for x in range(self.width):
                coor = (x * self.cell_size + self.left, y * self.cell_size + self.top, self.cell_size, self.cell_size)
                pygame.draw.rect(screen, color, coor, 1)
 
 
    def get_cell(self, mouse_pos):
        cell_x = (mouse_pos[0] - self.left) // self.cell_size
        cell_y = (mouse_pos[1] - self.top) // self.cell_size
        if cell_x < 0 or cell_x >= self.width or cell_y < 0 or cell_y >= self.height:
            return None
        return cell_x, cell_y
 
    def on_click(self, cell):
        pass
 
    def get_click(self, mouse_pos):
        cell = self.get_cell(mouse_pos)
        if cell:
            self.on_click(cell)
 
class Dedushka(Board):
    def __init__(self, width, height, need):
        super().__init__(width, height)
        self.board = [[-1] * width for inet in range(height)]
        ter = 0
        while ter < need:
            x = random.randint(0, self.width - 1)
            y = random.randint(0, self.height - 1)
            if self.board[y][x] == -1:
                self.board[y][x] = 10
                ter += 1
 
    def open_click(self, cell):
        x, y = cell
        if self.board == 10:
            return
        s = 0
        for dy in range(-1, 2):
            for dx in range(-1, 2):
                if x + dx < 0 or x + dx >= self.width or y + dy < 0 or y + dy >= self.height:
                    continue
                if self.board[y + dy][x + dx] == 10:
                    s += 1
        self.board[y][x] = s
 
    def on_click(self, cell):
        self.open_click(cell)
 
    def render(self, screen):
        color = pygame.Color('red')
        for y in range(self.height):
            for x in range(self.width):
                coor = (x * self.cell_size + self.left, y * self.cell_size + self.top,
                        self.cell_size, self.cell_size)
                coor1 = (x * self.cell_size + self.left + 2, y * self.cell_size + self.top + 2,
                        self.cell_size, self.cell_size)
                if self.board[y][x] == 10:
                    pygame.draw.rect(screen, color, coor)
                pygame.draw.rect(screen, pygame.Color('white'), coor, 1)
                if self.board[y][x] >= 0 and self.board[y][x] != 10:
                    font = pygame.font.Font(None, self.cell_size - 7)
                    text = font.render(str(self.board[y][x]), 1, (100, 255, 100))
                    screen.blit(text, coor1)
 
 
def main():
    pygame.init()
    size = 500, 500
    screen = pygame.display.set_mode(size)
    pygame.display.set_caption('Дедушка сапёра')
    clock = pygame.time.Clock()
    board = Dedushka(10, 15, 10)
    ticks = 0
    running = True
    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            if event.type == pygame.MOUSEBUTTONDOWN:
                board.get_click(event.pos)
        screen.fill((0, 0, 0))
        board.render(screen)
        pygame.display.flip()
        clock.tick(50)
        ticks += 1
    pygame.quit()
 
 
if __name__ == '__main__':
    main()
0
Лучшие ответы (1)
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
08.12.2021, 13:46
Ответы с готовыми решениями:

Алгоритм для сапера
Доброго времени суток! Я решил реализовать работу сапера на PyQt5, но не могу придумать алгоритм...

Генератор поля для сапера
Нужен генератор текстового поля для сапера (в качестве шаблона, далее переделаю в графическую...

Оцените программу на pygame (копия сапёра)
Привет! Закончил писать копию сапёра. Выкладываю файлы. Потестите на ошибки. Буду рад послушать...

Папа Сапёра
Добавьте в класс Minesweeper из классной задачи автоматическое открывание пустых областей (измените...

Богатый папа, бедный папа - Кийосаки Роберт - комментарии
Хотелось бы слышать ваше мнение . Сам, согласен отчасти, но не совсем .Лично мое мнение - Книга...

1
3 / 2 / 1
Регистрация: 22.09.2021
Сообщений: 3
13.12.2021, 22:59 2
Лучший ответ Сообщение было отмечено GerJer23 как решение

Решение

Привет! Спасибо за базу для кода! Немного лагает, но думаю ничего)
UPD: В твоей версии кода кстати был баг - при нажатие на мину она исчезала, я это пофиксил <3
Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
import pygame
import random
 
class Board:
    def __init__(self, width, height):
        self.width = width
        self.height = height
        self.board = [[0] * width for _ in range(height)]
        self.left = 10
        self.top = 10
        self.cell_size = 30
 
    def set_view(self, left, top, cell_size):
        self.left = left
        self.top = top
        self.cell_size = cell_size
 
    def render(self, screen):
        color = pygame.Color('white')
        for y in range(self.height):
            for x in range(self.width):
                coor = (x * self.cell_size + self.left, y * self.cell_size + self.top, self.cell_size, self.cell_size)
                pygame.draw.rect(screen, color, coor, 1)
 
 
    def get_cell(self, mouse_pos):
        cell_x = (mouse_pos[0] - self.left) // self.cell_size
        cell_y = (mouse_pos[1] - self.top) // self.cell_size
        if cell_x < 0 or cell_x >= self.width or cell_y < 0 or cell_y >= self.height:
            return None
        return cell_x, cell_y
 
    def on_click(self, cell):
        pass
 
    def get_click(self, mouse_pos):
        cell = self.get_cell(mouse_pos)
        if cell:
            self.on_click(cell)
 
class Minesweeper(Board):
    def __init__(self, width, height, need):
        super().__init__(width, height)
        self.board = [[-1] * width for inet in range(height)]
        ter = 0
        while ter < need:
            x = random.randint(0, self.width - 1)
            y = random.randint(0, self.height - 1)
            if self.board[y][x] == -1:
                self.board[y][x] = 10
                ter += 1
 
    def open_click(self, cell):
        x, y = cell
        if self.board[y][x] == 10:
            return
        s = 0
        for dy in range(-1, 2):
            for dx in range(-1, 2):
                if x + dx < 0 or x + dx >= self.width or y + dy < 0 or y + dy >= self.height:
                    continue
                if self.board[y + dy][x + dx] == 10:
                    s += 1
        if s == 0: 
            s1 = 0
            for x1 in range(self.width):
                for y1 in range(self.height):
                    s1 = 0
                    if self.board[y1][x1] == -1:
                        for dy1 in range(-1, 2):
                            for dx1 in range(-1, 2):
                                if x1 + dx1 < 0 or x1 + dx1 >= self.width or y1 + dy1 < 0 or y1 + dy1 >= self.height:
                                    continue
                                if self.board[y1 + dy1][x1 + dx1] == 10:
                                    s1 += 1
                        if s1 == 0:
                            self.board[y1][x1] = s1
        self.board[y][x] = s
 
    def on_click(self, cell):
        self.open_click(cell)
 
    def render(self, screen):
        color = pygame.Color('red')
        for y in range(self.height):
            for x in range(self.width):
                coor = (x * self.cell_size + self.left, y * self.cell_size + self.top,
                        self.cell_size, self.cell_size)
                coor1 = (x * self.cell_size + self.left + 2, y * self.cell_size + self.top + 2,
                        self.cell_size, self.cell_size)
                if self.board[y][x] == 10:
                    pygame.draw.rect(screen, color, coor)
                pygame.draw.rect(screen, pygame.Color('white'), coor, 1)
                if self.board[y][x] >= 0 and self.board[y][x] != 10:
                    font = pygame.font.Font(None, self.cell_size - 7)
                    text = font.render(str(self.board[y][x]), 1, (100, 255, 100))
                    screen.blit(text, coor1)
 
 
def main():
    pygame.init()
    size = 500, 500
    screen = pygame.display.set_mode(size)
    pygame.display.set_caption('Папа сапёра')
    clock = pygame.time.Clock()
    board = Minesweeper(10, 15, 10)
    ticks = 0
    running = True
    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            if event.type == pygame.MOUSEBUTTONDOWN:
                board.get_click(event.pos)
        screen.fill((0, 0, 0))
        board.render(screen)
        pygame.display.flip()
        clock.tick(50)
        ticks += 1
    pygame.quit()
 
 
if __name__ == '__main__':
    main()
1
13.12.2021, 22:59
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
13.12.2021, 22:59
Помогаю со студенческими работами здесь

Minijack 3.5 (папа-папа)
Здравствуйте. Подскажите, где приобрести 3,5 мм разъем Hands free типа папа-папа, но без провода,...

Где папа?
Мама старше своего сына на 21 год. Через шесть лет она будет старше его в пять раз. Вопрос: Где...

Старенький папа и вирусы
Здравствуйте. Вынудило меня обратиться к вам доверчивость моего старенького папы. Не успела ему...

Самодельные провода папа-мама
Провод мама-мама сделать можно коннектор обжав соответствующий на концах провода. А как можно...

какой взять разъём (мама - папа)
Делаю часы-термометр-вольтметр. Два датчика температуры DS18b20 - выносные, но идут в разные места...

Реализовать отношение мама-папа-дочь(ООП)
У них должно быть имя (например, Мария, Александр, Анна); возраст, пол. У мамы, папы и дочери...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
2
Ответ Создать тему
Опции темы

КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2024, CyberForum.ru