Форум программистов, компьютерный форум, киберфорум
Python: PyGame
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.92/13: Рейтинг темы: голосов - 13, средняя оценка - 4.92
0 / 0 / 0
Регистрация: 14.09.2020
Сообщений: 6

pygame.mouse.get_pressed()

07.04.2021, 14:59. Показов 2886. Ответов 3

Студворк — интернет-сервис помощи студентам
Создал не большую игру на питоне и после компилирования в exe файл игра не запускается, в чем может быть причина ? (возможно из-за строчки
Python
1
click = pygame.mouse.get_pressed()
) но при написании туда цифры игра не запускается без компилирования в exe
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
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
import pygame
import random
 
 
pygame.init()
 
displey_wight = 800
displey_height = 600
 
displey = pygame.display.set_mode((displey_wight, displey_height))
pygame.display.set_caption('dinorun')
 
 
class objeckt:
 
    global stone, cloud
 
    def __init__(self, x, y, wight, image, speed):
        self.x = x
        self.y = y
        self.wight = wight
        self.image = image
        self.speed = speed
 
    def move(self):
        if self.x >= -self.wight:
            displey.blit(self.image, (self.x, self.y))
            self.x -= self.speed
            return True
        else:
            return False
 
    def return_self(self, radius, y, wight, image):
        self.x = radius
        self.y = y
        self.wight = wight
        self.image = image
        displey.blit(self.image, (self.x, self.y))
 
 
class Button:
    def __init__(self, wight, height,):
        self.wight = wight
        self.height = height
        self.inactive_color = (23, 204, 58)
        self.active_color = (13, 162, 58)
        self.draw_effectes = False
        self.rect_h = 10
        self.rect_w = wight
        self.clear_effects = False
 
    def draw(self, x, y, message, action=None, font_size=30):
        mouse = pygame.mouse.get_pos()
        click = pygame.mouse.get_pressed()
 
        if x < mouse[0] < x + self.wight and y < mouse[1] < y + self.height:
 
            if click[0] == 1:    
                pygame.time.delay(300) 
                if action is not None:
                    if action == quit:
                        pygame.quit()
                        quit()
                    else:
                        action()
 
        self.draw_rect(mouse[0], mouse[1], x, y)
        print_text(message=message, x=x+10, y=y+10, font_size=font_size)
 
    def draw_rect(self, ms_x, ms_y, x, y):
        if x <= ms_x <= x + self.wight and y <= ms_y <= y + self.height:
            self.draw_effectes = True
 
        if self.draw_effectes:
            if self.rect_h < self.height:
                self.rect_h = self.height
            else:
                if ms_x < x or ms_x > x + self.wight or ms_y < y or ms_y> y + self.height:
                    self.clear_effects = True
                    self.draw_effectes = False
 
        if self.clear_effects:
            if self.rect_h > 10:
                self.rect_h = 10
            else:
                self.clear_effects = False
 
        draw_y = y + self.height - self.rect_h
        pygame.draw.rect(displey, self.active_color, (x, draw_y, self.rect_w, self.rect_h))
 
 
user_wight = 60
user_height = 100
user_x = displey_wight//3
user_y = displey_height-user_height-100
 
cactus_wight = 20
cactus_height = 70
cactus_x = displey_wight-50
cactus_y = displey_height-cactus_height-100
 
clock = pygame.time.Clock()
 
make_jump = False
 
jump_counter = 30
 
 
def show_menu():
    menu_backgr = pygame.image.load('menu.jpg')
    show = True
 
    start_button = Button(266, 70)
    quit_button = Button(114, 70)
 
    while show:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()
        displey.blit(menu_backgr, (0, 0))
        start_button.draw(20, 200, 'start Game', start_game, font_size=50)
        quit_button.draw(20, 300, 'quit', quit, font_size=50)
        pygame.display.update()
        clock.tick(60)
 
 
def start_game():
    global scores, make_jump, jump_counter, user_y, time_stead
    while game_cycle():
        scores = 0
        make_jump = False
        jump_counter = 30
        user_y = displey_height - user_height - 100
        time_stead = 80
 
 
def game_cycle():
 
    global make_jump
    game = True
    cactus_arr = []
    create_cactus_arr(cactus_arr)
    land = pygame.image.load('fon.jpg')
 
    stone, cloud = open_random_objects()
 
    button = Button(70, 50)
 
    while game:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()
 
        keys = pygame.key.get_pressed()
        if keys[pygame.K_SPACE]:
            make_jump = True
 
        if keys[pygame.K_ESCAPE]:
            pause()
 
        if make_jump:
            jump()
 
        count_scores(cactus_arr)
 
        displey.blit(land, (0, 0))
 
        print_text('skores:' + str(scores), 600, 10)
        print_text('spead:' + str(time_stead), 600, 30)
 
        draw_array(cactus_arr)
 
        move_objects(stone, cloud)
 
        draw_dino()
 
        spead()
 
        pygame.display.update()
        clock.tick(time_stead)
 
        if check_collision(cactus_arr):
            game = False
 
    return game_over()
 
 
def jump():
    global user_y, make_jump, jump_counter
    if jump_counter >= -30:
        "if jump_counter == 30:"
        user_y -= jump_counter / 2.5
        jump_counter -= 1
 
    else:
        jump_counter = 30
        make_jump = False
 
 
def create_cactus_arr(array):
    choice = random.randrange(0, 3)
    img = cactus_img[choice]
    wight = cactus_options[choice * 2]
    height = cactus_options[choice * 2 + 1]
    array.append(objeckt(displey_wight + 20, height, wight, img, 4))
    choice = random.randrange(0, 3)
    img = cactus_img[choice]
    wight = cactus_options[choice * 2]
    height = cactus_options[choice * 2 + 1]
    array.append(objeckt(displey_wight + 20, height, wight, img, 4))
    choice = random.randrange(0, 3)
    img = cactus_img[choice]
    wight = cactus_options[choice * 2]
    height = cactus_options[choice * 2 + 1]
    array.append(objeckt(displey_wight + 20, height, wight, img, 4))
 
 
def find_radius(array):
    maximum = max(array[0].x, array[1].x, array[2].x)
 
    if maximum < displey_wight:
        radius = displey_wight
        if radius - maximum < 50:
            radius += 250
    else:
        radius = maximum
    choice = random.randrange(0, 5)
    if choice == 0:
        radius += random.randrange(15, 20)
    else:
        radius += random.randrange(300, 350)
    return radius
 
 
def draw_array(array):
    for cactus in array:
        check = cactus.move()
        if not check:
            radius = find_radius(array)
 
            choice = random.randrange(0, 3)
            img = cactus_img[choice]
            wight = cactus_options[choice * 2]
            height = cactus_options[choice * 2 + 1]
 
            cactus.return_self(radius, height, wight, img)
 
 
def open_random_objects():
 
    choice = random.randrange(0, 2)
    img_of_stone = stone_img[choice]
 
    choice = random.randrange(0, 2)
    img_of_cloud = cloud_img[choice]
 
    stone = objeckt(displey_wight, displey_height - 80, 10, img_of_stone, 4)
    cloud = objeckt(displey_wight, 80, 70, img_of_cloud, 2)
    return stone, cloud
 
 
def move_objects(stone, cloud):
    check = stone.move()
    if not check:
        choice = random.randrange(0, 2)
        img_of_stone = stone_img[choice]
        stone.return_self(displey_wight, 500 + random.randrange(10, 80), stone.wight, img_of_stone)
 
    check = cloud.move()
    if not check:
        choice = random.randrange(0, 2)
        img_of_cloud = cloud_img[choice]
        cloud.return_self(displey_wight, random.randrange(10, 200), cloud.wight, img_of_cloud)
 
 
def draw_dino():
    global img_counter
    if img_counter == 20:
        img_counter = 0
 
    displey.blit(dino_img[img_counter // 5], (user_x, user_y))
    img_counter += 1
 
 
def print_text(message, x, y, front_color=(0, 0, 0), front_type='Samson.ttf', font_size=30):
    front_type = pygame.font.Font(front_type, font_size)
    text = front_type.render(message, True, front_color)
    displey.blit(text, (x, y))
 
 
def pause():
    paused = True
 
 
    while paused:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()
 
        print_text('paused press enter to continue', 160, 300)
 
        keys = pygame.key.get_pressed()
        if keys[pygame.K_RETURN]:
            paused = False
        pygame.display.update()
        clock.tick(15)
 
 
def check_collision(barriers):
    for barrier in barriers:
        if barrier.y == 450:
            if not make_jump:
                if barrier.x <= user_x + user_wight - 18 <= barrier.x + barrier.wight:
                    return True
            elif jump_counter >= 0:
                if user_y + user_height - 5 >= barrier.y:
                    if barrier.x <= user_x + user_wight - 18 <= barrier.x + barrier.wight:
                        return True
            else:
                if user_y + user_height - 30 >= barrier.y:
                    if barrier.x <= user_x <= barrier.x + barrier.wight:
                        return True
        else:
            if not make_jump:
                if barrier.x <= user_x + user_wight - 5 <= barrier.x + barrier.wight:
                    return True
            elif jump_counter == 10:
                if user_y + user_height - 5 >= barrier.y:
                    if barrier.x <= user_x + user_wight - 8 <= barrier.x + barrier.wight:
                        return True
            elif jump_counter == -1:
                if user_y + user_height - 5 >= barrier.y:
                    if barrier.x <= user_x + user_wight - 18 <= barrier.x + barrier.wight:
                        return True
            else:
                if user_y + user_height - 25 >= barrier.y:
                    if barrier.x <= user_x + 5 <= barrier.x + barrier.wight:
                        return True
 
    return False
 
 
def count_scores(barriers):
    global scores, max_above
    above_cactus = 0
 
    if -20 <= jump_counter <= 25:
        for barrier in barriers:
            if user_y + user_height - 5 <= barrier.y:
                if barrier.x <= user_x <= barrier.x + barrier.wight:
                    above_cactus += 1
                elif barrier.x <= user_x + user_wight / 2 <= barrier.x + barrier.wight:
                    above_cactus += 1
        max_above = max(max_above, above_cactus)
    else:
        if jump_counter == -30:
            scores += max_above
            max_above = 0
 
 
def game_over():
    global max_scores, scores
    if scores > max_scores:
        max_scores = scores
 
    stopped = True
    while stopped:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()
 
        print_text('game over. Press Enter to play again, Esc to Exit', 40, 300)
        print_text('max scores:' + str(max_scores), 300, 350)
 
        keys = pygame.key.get_pressed()
        if keys[pygame.K_RETURN]:
            return True
 
        if keys[pygame.K_ESCAPE]:
            return False
 
        pygame.display.update()
        clock.tick(15)
 
 
def spead():
    global vremia, time_stead
    if scores == vremia:
        vremia += 5
        time_stead += 2
 
 
show_menu()
 
pygame.quit()
quit()
0
cpp_developer
Эксперт
20123 / 5690 / 1417
Регистрация: 09.04.2010
Сообщений: 22,546
Блог
07.04.2021, 14:59
Ответы с готовыми решениями:

Проблемы с pygame.key.get_pressed
key = pygame.key.get_pressed() if key: x -=speed elif key: x +=speed elif key: y...

При импорте pygame пишет что нет модуля pygame.base
Устанавливаю для kivy.Всё есть (sython,gsstreamer,kivy,pyscripter,python) , а вот фраем. pygame не работает.Почему?Что ещё надо для работы...

Ошибка в pygame AttributeError: 'pygame.Rect' object has no attribute 'blit'
Создаю игру, крестики нолики Почему возникает ошибка и как ее исправить? AttributeError: 'pygame.Rect' object has no attribute 'blit' ...

3
Модератор
Эксперт Python
 Аватар для Fudthhh
2695 / 1601 / 513
Регистрация: 21.02.2017
Сообщений: 4,210
Записей в блоге: 1
07.04.2021, 16:24
Цитата Сообщение от multirum Посмотреть сообщение
компилирования в exe
после упаковки.

Код не читабельный, запускай exe через консоль показывай ошибку.
0
0 / 0 / 0
Регистрация: 14.09.2020
Сообщений: 6
07.04.2021, 16:38  [ТС]
Traceback (most recent call last):
File "main.py", line 1, in <module>
ModuleNotFoundError: No module named 'pygame'
[10552] Failed to execute script main
0
Модератор
Эксперт Python
 Аватар для Fudthhh
2695 / 1601 / 513
Регистрация: 21.02.2017
Сообщений: 4,210
Записей в блоге: 1
08.04.2021, 07:39
multirum, ну вот тебе и ответ, не упаковался модуль pygame в твой exe. Используй самую свежую версию pyinstaller если не поможет, читай в доках как подцепить доп. модули при упаковке.
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
raxper
Эксперт
30234 / 6612 / 1498
Регистрация: 28.12.2010
Сообщений: 21,154
Блог
08.04.2021, 07:39
Помогаю со студенческими работами здесь

Pygame ошибка module ‘pygame’ has no ‘init’ member
Всем здравствуйте. Недавно начал работать с VS code и выдает такая ошибка. Прикрепляю полностью скрин. Нашел решение перед каждой...

pygame.error: cannot convert without pygame.display initialized
Только начал изучать спрайты Выдаёт ошибку: Traceback (most recent call last): File &quot;D:/project1/OCode.py&quot;, line 18, in...

Pygame.mixer.music.set_pose() не меняет pygame.mixer.music.get_pose()
Доброго времени суток, друзья! Пишу что-то среднее между часами и музыкальным плеером. Решил, что музыку буду воспроизводить с помощью...

PyGame
Для курсовой необходимо хоть какое то описание PyGame. Поиски в интернете не дали результата. Кто нибудь может дать ей внятное определение...

Pygame
всем привет, начал изучать pygame и столкнулся с проблемой. import sys import pygame def run_game(): pygame.init() ...


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

Или воспользуйтесь поиском по форуму:
4
Ответ Создать тему
Новые блоги и статьи
Символические и жёсткие ссылки в Linux.
algri14 15.03.2026
Существует два типа ссылок — символические и жёсткие. Ссылка в Linux — это дополнительная запись в каталоге, которая может указывать либо на inode «файла-ИСТОЧНИКА», тогда это будет «жёсткая. . .
[Owen Logic] Поддержание уровня воды в резервуаре количеством включённых насосов: моделирование и выбор регулятора
ФедосеевПавел 14.03.2026
Поддержание уровня воды в резервуаре количеством включённых насосов: моделирование и выбор регулятора ВВЕДЕНИЕ Выполняя задание на управление насосной группой заполнения резервуара,. . .
делаю науч статью по влиянию грибов на сукцессию
anaschu 13.03.2026
прикрепляю статью
SDL3 для Desktop (MinGW): Создаём пустое окно с нуля для 2D-графики на SDL3, Си и C++
8Observer8 10.03.2026
Содержание блога Финальные проекты на Си и на C++: hello-sdl3-c. zip hello-sdl3-cpp. zip Результат:
Установка CMake и MinGW 13.1 для сборки С и C++ приложений из консоли и из Qt Creator в EXE
8Observer8 10.03.2026
Содержание блога MinGW - это коллекция инструментов для сборки приложений в EXE. CMake - это система сборки приложений. Здесь описаны базовые шаги для старта программирования с помощью CMake и. . .
Как дизайн сайта влияет на конверсию: 7 решений, которые реально повышают заявки
Neotwalker 08.03.2026
Многие до сих пор воспринимают дизайн сайта как “красивую оболочку”. На практике всё иначе: дизайн напрямую влияет на то, оставит человек заявку или уйдёт через несколько секунд. Даже если у вас. . .
Модульная разработка через nuget packages
DevAlt 07.03.2026
Сложившийся в . Net-среде способ разработки чаще всего предполагает монорепозиторий в котором находятся все исходники. При создании нового решения, мы просто добавляем нужные проекты и имеем. . .
Модульный подход на примере F#
DevAlt 06.03.2026
В блоге дяди Боба наткнулся на такое определение: В этой книге («Подход, основанный на вариантах использования») Ивар утверждает, что архитектура программного обеспечения — это структуры,. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru