Форум программистов, компьютерный форум, киберфорум
Python: Tkinter
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 5.00/7: Рейтинг темы: голосов - 7, средняя оценка - 5.00
1 / 1 / 0
Регистрация: 09.12.2023
Сообщений: 16

Игра. Добавление врагов

04.01.2025, 19:59. Показов 2473. Ответов 6
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Помогите сделать "Врагов" - черные кружки, двигающиеся в рандоме, на которые нельзя попадать управляемому шарику. Вот код:
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
import tkinter
import random
 
try:
 
    def move_wrap(obj, move):
        canvas.move(obj, move[0], move[1])
 
 
    def do_nothing(qwerty):
        return qwerty
 
 
    def check_move():
        if canvas.coords(player) == canvas.coords(leave):
            label.config(text="Победа!")
            master.bind("<KeyPress>", do_nothing)
        for f in fires:
            if canvas.coords(player) == canvas.coords(f):
                label.config(text="Ты проиграл!")
                master.bind("<KeyPress>", do_nothing)
 
 
    def always_right():
        return step, 0
 
 
    def random_move():
        return random.choice([(step, 0), (-step, 0), (0, step), (0, -step)])
 
 
    def prepare_and_start():
        global player, leave, fires
        canvas.delete("all")
        player_pos = (random.randint(1, N_X - 1) * step,
                      random.randint(1, N_Y - 1) * step)
        exit_pos = (random.randint(1, N_X - 1) * step,
                    random.randint(1, N_Y) * step)
        player = canvas.create_oval(
            (player_pos[0], player_pos[1]),
            (player_pos[0] + step, player_pos[1] + step),
            fill='green')
        leave = canvas.create_oval(
            (exit_pos[0], exit_pos[1]),
            (exit_pos[0] + step, exit_pos[1] + step),
            fill='yellow')
        n_fires = 6
        fires = []
        for i in range(n_fires):
            fire_pos = (random.randint(1, N_X - 1) * step,
                        random.randint(1, N_Y - 1) * step)
            fire = canvas.create_oval(
                (fire_pos[0], fire_pos[1]),
                (fire_pos[0] + step, fire_pos[1] + step),
                fill='red')
            fires.append(fire)
        label.config(text="Найди выход!")
        master.bind("<KeyPress>", key_pressed)
 
 
    def key_pressed(event):
        if event.keysym == 'Up':
            move_wrap(player, (0, -step))
        elif event.keysym == 'Down':
            move_wrap(player, (0, step))
        elif event.keysym == 'Left':
            move_wrap(player, (-step, 0))
        elif event.keysym == 'Right':
            move_wrap(player, (step, 0))
        elif event.keysym == 'Control_L':
            label.config(text="Ты проиграл!")
            master.bind("<KeyPress>", do_nothing)
        elif event.keysym == 'Control_R':
            label.config(text="Победа!")
            master.bind("<KeyPress>", do_nothing)
        check_move()
 
 
    master = tkinter.Tk()
    step = 60
    N_X = 10
    N_Y = 10
    label = tkinter.Label(master, text="Найди выход")
    label.pack()
    canvas = tkinter.Canvas(master, bg='blue',
                            height=N_X * step, width=N_Y * step)
    canvas.pack()
    restart = tkinter.Button(master, text="Начать заново",
                             command=prepare_and_start)
    restart.pack()
    prepare_and_start()
    master.mainloop()
 
    player_pos = (random.randint(0, N_X - 1) * step,
                  random.randint(0, N_Y - 1) * step)
    exit_pos = (random.randint(0, N_X - 1) * step,
                random.randint(0, N_Y - 1) * step)
 
    player = canvas.create_oval((player_pos[0], player_pos[1]), (player_pos[0] + step, player_pos[1] + step),
                                fill='green')
    leave = canvas.create_oval((exit_pos[0], exit_pos[1]),
                               (exit_pos[0] + step, exit_pos[1] + step),
                               fill='yellow')
 
    label = tkinter.Label(master, text="Найди выход")
    label.pack()
    canvas.pack()
    master.bind("<KeyPress>", key_pressed)
    master.mainloop()
 
except tkinter.TclError:
    qwerty = 0
Заранее спасибо!)
0
Лучшие ответы (1)
IT_Exp
Эксперт
34794 / 4073 / 2104
Регистрация: 17.06.2006
Сообщений: 32,602
Блог
04.01.2025, 19:59
Ответы с готовыми решениями:

Игра с перемещением персонажа и врагов
Нужно написать программу, с полем 80x80. Программа должна выбивать на экран информацию о местоположении Главного героя и трех врагов. Также...

Игра танки тормозит при появлении 6 и более врагов
как то писал курсач -&quot;танки&quot;. c# знал плохо, ооп вообще не понимал. сейчас стал кое что понимать решил повторить попытку. столкнулся с тем,...

Проблема стрельбы врагов через стены по игроку в TDS Unity2D (игра с видом сверху)
Здравствуйте уважаемые знатоки). У меня враги стреляют в меня через стены, а мне этого не надо. Я не знаю как реализовать это, так чтобы...

6
228 / 169 / 71
Регистрация: 14.06.2024
Сообщений: 458
05.01.2025, 07:25
Цитата Сообщение от Twitty_BIRD Посмотреть сообщение
"Врагов" - черные кружки, двигающиеся в рандоме
самостоятельно должны двигаться, или только после хода игрока?
0
1 / 1 / 0
Регистрация: 09.12.2023
Сообщений: 16
05.01.2025, 21:53  [ТС]
Самостаятельно
0
228 / 169 / 71
Регистрация: 14.06.2024
Сообщений: 458
08.01.2025, 15:22
а чего проверки нет на совпадение координат?
0
1 / 1 / 0
Регистрация: 09.12.2023
Сообщений: 16
10.01.2025, 20:59  [ТС]
14 строка - совпадение кружка игрока и кружка-выхода
Python
1
def check_move():
0
 Аватар для Aviz__
2736 / 2046 / 506
Регистрация: 17.02.2014
Сообщений: 9,462
14.01.2025, 11:03
Лучший ответ Сообщение было отмечено Twitty_BIRD как решение

Решение

Twitty_BIRD, держи. Как-то тоже было интересно сделать такое. Двигаешь красным, опасные синии, выходы зеленые. Можно усложнять до бесконечности этот код. Например, придумать систему взаимной расстановки, чтобы добраться до выходов было сложно (сейчас, как повезет), или перемещение опасностей.
Кликните здесь для просмотра всего текста
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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
import math
import random as rnd
import tkinter as tk
 
 
class Point:
    """Represents a point on a 2D plane.
 
    Attributes:
        x (int): The x-coordinate of the point.
        y (int): The y-coordinate of the point.
    """
    def __init__(self, x, y):
        self.x = x
        self.y = y
 
    def get_tuple_cords(self):
        """Returns the coordinates of the point as a tuple.
 
        Returns:
            tuple[int, int]: The x and y coordinates of the point.
        """
        return self.x, self.y
 
 
class CircleGame:
    """Represents a circle game object.
 
    Attributes:
        center (Point): The center point of the circle.
        radius (int): The radius of the circle.
        fill_color (str): The color of the circle.
    """
    def __init__(self, center: Point, radius: int, fill_color: str):
        self.center = center
        self.radius = radius
        self.fill_color = fill_color
 
    def get_central_point(self):
        """Returns the center point of the circle.
 
        Returns:
            Point: The center point of the circle.
        """
        return self.center
 
    def _get_graph_space(self) -> tuple[int, ...]:
        """Returns the coordinates of the bounding box for the circle.
 
        Returns:
            tuple[int, ...]: The coordinates of the top-left and bottom-right points of the bounding box.
        """
        p_top_l = Point(self.center.x - self.radius, self.center.y - self.radius)
        p_bottom_r = Point(self.center.x + self.radius, self.center.y + self.radius)
 
        return *p_top_l.get_tuple_cords(), *p_bottom_r.get_tuple_cords()
 
    def __eq__(self, other: 'CircleGame') -> bool:
        """Compares two CircleGame objects for equality.
 
        Args:
            other (CircleGame): The other CircleGame object to compare.
 
        Returns:
            bool: True if the circles are overlapping, False otherwise.
        """
        if not isinstance(other, CircleGame):
            return NotImplemented
 
        return math.dist(self.center.get_tuple_cords(), other.center.get_tuple_cords()) < (self.radius + other.radius)
 
    def draw(self, canvas):
        """Draws the circle on the given canvas.
 
        Args:
            canvas (tk.Canvas): The canvas to draw the circle on.
        """
        canvas.create_oval(self._get_graph_space(), fill=self.fill_color)
 
    def move_up(self, distance):
        """Moves the circle up by the given distance.
 
        Args:
            distance (int): The distance to move the circle up.
        """
        self.center.y -= distance
 
    def move_down(self, distance):
        """Moves the circle down by the given distance.
 
        Args:
            distance (int): The distance to move the circle down.
        """
        self.center.y += distance
 
    def move_left(self, distance):
        """Moves the circle left by the given distance.
 
        Args:
            distance (int): The distance to move the circle left.
        """
        self.center.x -= distance
 
    def move_right(self, distance):
        """Moves the circle right by the given distance.
 
        Args:
            distance (int): The distance to move the circle right.
        """
        self.center.x += distance
 
    @classmethod
    def get_color_circles_list(cls, circle_counts: dict, canvas_size: int) -> list['CircleGame']:
        """Generates a list of CircleGame objects with the specified colors and counts.
 
        Args:
            circle_counts (dict): A dictionary mapping color strings to the number of circles of that color.
            canvas_size (int): The size of the canvas (width or height).
 
        Returns:
            list[CircleGame]: A list of CircleGame objects.
        """
        radius = canvas_size // 30
        low_brd = radius
        hi_brd = canvas_size - radius
        ret_list = []
        all_counts = 0
 
        for color, count in circle_counts.items():
            all_counts += count
            while len(ret_list) < all_counts:
                tmp_cg = CircleGame(Point(rnd.randint(low_brd, hi_brd), rnd.randint(low_brd, hi_brd)), radius, color)
                if tmp_cg not in ret_list:
                    ret_list.append(tmp_cg)
 
        return ret_list
 
    @classmethod
    def get_colliding_circles_list(cls, circle_moveable: 'CircleGame', circles: list['CircleGame']) -> list['CircleGame']:
        """Returns a list of circles that are colliding with the given moveable circle.
 
        Args:
            circle_moveable (CircleGame): The moveable circle.
            circles (list[CircleGame]): The list of circles to check for collisions.
 
        Returns:
            list[CircleGame]: A list of circles that are colliding with the moveable circle.
        """
        return [c for c in circles if c.fill_color != circle_moveable.fill_color and c == circle_moveable]
 
 
class Game:
    """Represents the game controller.
 
    Attributes:
        window_width (int): The width of the game window.
        window_height (int): The height of the game window.
        root (tk.Tk): The main Tkinter window.
        canvas (tk.Canvas): The canvas for drawing the game elements.
        circles (list[CircleGame]): The list of CircleGame objects in the game.
        moveable_circle (CircleGame): The moveable circle in the game.
    """
    def __init__(self, window_width: int, window_height: int):
        self.window_width = window_width
        self.window_height = window_height
        self.root = tk.Tk()
        self.root.title(">>>Опасное путешествие красного Колобка<<<")
        self.canvas = tk.Canvas(self.root, width=self.window_width, height=self.window_height)
        self.canvas.pack()
        self.circles = CircleGame.get_color_circles_list({'red': 1, 'green': 2, 'blue': 21}, self.window_width)
        self.moveable_circle = [c for c in self.circles if c.fill_color == 'red'][0]
 
    def redraw(self, message=None):
        """Redraws the game elements on the canvas.
 
        Args:
            message (str, optional): A message to display on the canvas.
        """
        self.canvas.delete("all")
        if message:
            x, y = self.window_width // 2, self.window_height // 2
            self.canvas.create_text(x, y, text=message, fill="red", font=("Arial", 16))
        else:
            for circle in self.circles:
                circle.draw(self.canvas)
 
    def _can_move(self, direction: str, distance: int) -> bool:
        """Checks if the moveable circle can be moved in the given direction by the given distance.
 
        Args:
            direction (str): The direction to move the circle ("up", "down", "left", "right").
            distance (int): The distance to move the circle.
 
        Returns:
            bool: True if the circle can be moved, False otherwise.
        """
        if direction == "up":
            new_y = self.moveable_circle.center.y - distance
            return new_y >= self.moveable_circle.radius
        elif direction == "down":
            new_y = self.moveable_circle.center.y + distance
            return new_y <= self.window_height - self.moveable_circle.radius
        elif direction == "left":
            new_x = self.moveable_circle.center.x - distance
            return new_x >= self.moveable_circle.radius
        elif direction == "right":
            new_x = self.moveable_circle.center.x + distance
            return new_x <= self.window_width - self.moveable_circle.radius
        return False
 
    def move_circle(self, direction: str, distance=10):
        """Moves the moveable circle in the given direction, if possible.
 
        Args:
            direction (str): The direction to move the circle ("up", "down", "left", "right").
            distance (int, optional): The distance to move the circle. Defaults to 10.
        """
        if self._can_move(direction, distance):
            if direction == "up":
                self.moveable_circle.move_up(distance)
            elif direction == "down":
                self.moveable_circle.move_down(distance)
            elif direction == "left":
                self.moveable_circle.move_left(distance)
            elif direction == "right":
                self.moveable_circle.move_right(distance)
 
        colliding_list = CircleGame.get_colliding_circles_list(self.moveable_circle, self.circles)
        if len(colliding_list) > 0:
            if colliding_list[0].fill_color == "blue":
                self.game_over()
            elif colliding_list[0].fill_color == "green":
                self.win()
        else:
            self.redraw()
 
    def game_over(self):
        """Displays the "game over" message and binds the space key to the reset method."""
        self.redraw("Колобок доигрался, конец!\nНачать снова, жми пробел, выход из игры - Escape.")
        self.root.bind("<space>", lambda event: self.reset())
 
    def win(self):
        """Displays the "win" message and binds the space key to the reset method."""
        self.redraw("Колобок нашел свое счастье!\nНачать снова, жми пробел, выход из игры - Escape.")
        self.root.bind("<space>", lambda event: self.reset())
 
    def reset(self):
        """Resets the game by generating a new set of circles."""
        self.circles = CircleGame.get_color_circles_list({'red': 1, 'green': 2, 'blue': 21}, self.window_width)
        self.moveable_circle = [c for c in self.circles if c.fill_color == 'red'][0]
        self.redraw()
 
    def exit(self):
        """Exits the game by destroying the Tkinter window."""
        self.root.destroy()
 
    def run(self):
        """Runs the game by displaying the initial state and binding the keyboard events."""
        self.redraw()
 
        self.root.bind("<Up>", lambda event: self.move_circle("up"))
        self.root.bind("<Down>", lambda event: self.move_circle("down"))
        self.root.bind("<Left>", lambda event: self.move_circle("left"))
        self.root.bind("<Right>", lambda event: self.move_circle("right"))
        self.root.bind("<Escape>", lambda event: self.exit())
 
        self.root.mainloop()
 
if __name__ == "__main__":
    game = Game(600, 600)
    game.run()
1
1 / 1 / 0
Регистрация: 09.12.2023
Сообщений: 16
24.01.2025, 11:06  [ТС]
Спасибо
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
BasicMan
Эксперт
29316 / 5623 / 2384
Регистрация: 17.02.2009
Сообщений: 30,364
Блог
24.01.2025, 11:06
Помогаю со студенческими работами здесь

Добавление меню в приложение Java на ПК. Игра Крестики Нолики
Только начинаю изучать java нашёл вот такой код, хочу усовершенствовать эту игру, например добавить меню по типу(Файл, О создателе,...

Карточная игра в дурака. Раздача и добавление карт после отбоя.
Ребята помогите с написанием игры в дурака на двоих. Я делаю на визуалке в среде с++ билдер; Немогу понять куда девать карты когда...

ИИ врагов
Я хочу чтобы враг ходил по определенной траектории и когда игрок пересекал эту траекторию, враг начинал в него стрелять. Еще было бы...

Врагов в друзей
Помогите Чиполлино превратить врагов в друзей. Враги – это обычно графы, герцоги, принцы и свита, их имена состоят из нескольких слов....

Создание врагов
Привет есть вот такой класс, работаю в андроид студио, пытаюсь создать большое количество врагов. Но отрисовывает только одного в методе...


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

Или воспользуйтесь поиском по форуму:
7
Ответ Создать тему
Новые блоги и статьи
PhpStorm 2025.3: WSL Terminal всегда стартует в ~
and_y87 14.12.2025
PhpStorm 2025. 3: WSL Terminal всегда стартует в ~ (home), игнорируя директорию проекта Симптом: После обновления до PhpStorm 2025. 3 встроенный терминал WSL открывается в домашней директории. . .
Как объединить две одинаковые БД Access с разными данными
VikBal 11.12.2025
Помогите пожалуйста !! Как объединить 2 одинаковые БД Access с разными данными.
Новый ноутбук
volvo 07.12.2025
Всем привет. По скидке в "черную пятницу" взял себе новый ноутбук Lenovo ThinkBook 16 G7 на Амазоне: Ryzen 5 7533HS 64 Gb DDR5 1Tb NVMe 16" Full HD Display Win11 Pro
Музыка, написанная Искусственным Интеллектом
volvo 04.12.2025
Всем привет. Некоторое время назад меня заинтересовало, что уже умеет ИИ в плане написания музыки для песен, и, собственно, исполнения этих самых песен. Стихов у нас много, уже вышли 4 книги, еще 3. . .
От async/await к виртуальным потокам в Python
IndentationError 23.11.2025
Армин Ронахер поставил под сомнение async/ await. Создатель Flask заявляет: цветные функции - провал, виртуальные потоки - решение. Не threading-динозавры, а новое поколение лёгких потоков. Откат?. . .
Поиск "дружественных имён" СОМ портов
Argus19 22.11.2025
Поиск "дружественных имён" СОМ портов На странице: https:/ / norseev. ru/ 2018/ 01/ 04/ comportlist_windows/ нашёл схожую тему. Там приведён код на С++, который показывает только имена СОМ портов, типа,. . .
Сколько Государство потратило денег на меня, обеспечивая инсулином.
Programma_Boinc 20.11.2025
Сколько Государство потратило денег на меня, обеспечивая инсулином. Вот решила сделать интересный приблизительный подсчет, сколько государство потратило на меня денег на покупку инсулинов. . . .
Ломающие изменения в C#.NStar Alpha
Etyuhibosecyu 20.11.2025
Уже можно не только тестировать, но и пользоваться C#. NStar - писать оконные приложения, содержащие надписи, кнопки, текстовые поля и даже изображения, например, моя игра "Три в ряд" написана на этом. . .
Мысли в слух
kumehtar 18.11.2025
Кстати, совсем недавно имел разговор на тему медитаций с людьми. И обнаружил, что они вообще не понимают что такое медитация и зачем она нужна. Самые базовые вещи. Для них это - когда просто люди. . .
Создание Single Page Application на фреймах
krapotkin 16.11.2025
Статья исключительно для начинающих. Подходы оригинальностью не блещут. В век Веб все очень привыкли к дизайну Single-Page-Application . Быстренько разберем подход "на фреймах". Мы делаем одну. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2025, CyberForum.ru