如何解决Pygame 暂停功能
我一直在尝试为我的乒乓球游戏添加暂停功能,但它不起作用。我可以暂停一次游戏然后它停止,但是之后如果我按下暂停游戏的键,游戏将移动几帧然后停止。之后,我必须按住暂停按钮才能让游戏移动。我将链接下面的课程代码:
class Game:
def __init__(self,start):
self.start = start
self.score1 = 0
self.score2 = 0
self.pause = False
self.over = False
def play(self,ai):
player2.AI = ai
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Pong")
self.over = False
while self.start:
# quits if x is pressed
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
pressed_keys = pygame.key.get_pressed()
if pressed_keys[pygame.K_p]:
self.pauseMenu()
if self.pause == False:
# creates list of pressed keys and using that to determine movement
pressed_keys = pygame.key.get_pressed()
if pressed_keys[pygame.K_w]:
player1.moveUp(5)
if pressed_keys[pygame.K_s]:
player1.moveDown(5)
if player2.AI == True:
player2.AI_move(ball)
if pressed_keys[pygame.K_SPACE]:
pygame.quit()
else:
if pressed_keys[pygame.K_UP]:
player2.moveUp(5)
if pressed_keys[pygame.K_DOWN]:
player2.moveDown(5)
if pressed_keys[pygame.K_p]:
self.pauseMenu()
# scoring system if ball touches variable,increments score and resets ball to middle
if ball.rect.x >= 790:
self.score1 += 1
ball.rect.x = 400
ball.rect.y = 240
ball.x_velo = choice([-2,2])
ball.y_velo = choice([-1,-2,1,2])
if ball.rect.x <= 0:
self.score2 += 1
ball.rect.x = 400
ball.rect.y = 240
ball.x_velo = choice([-2,2])
# bounces ball of top or bottom wall
if ball.rect.y > 470 or ball.rect.y < 0:
ball.y_velo = -ball.y_velo
# detects collision and reflects ball off board
if pygame.sprite.collide_mask(ball,player1) or pygame.sprite.collide_mask(ball,player2):
ball.bounce()
# refresh method to move ball
ball.refresh()
# draws background and sprites onto screen each tick
screen.fill(BLACK)
pygame.draw.line(screen,WHITE,[400,0],580],1)
all_sprites_list.update()
all_sprites_list.draw(screen)
# draws score at top
font = pygame.font.Font('ARCADECLASSIC.TTF',74)
text = font.render(str(self.score1),BLUE)
screen.blit(text,(300,10))
text = font.render(str(self.score2),(470,10))
if self.score1 >= 5:
self.victory("Player 1")
elif self.score2 >= 5:
self.victory("Player 2")
# refreshes display each tick
pygame.display.flip()
# sets number of ticks per second
clock.tick(60)
def victory(self,winner):
pass
def pauseMenu(self):
if self.pause == True:
self.pause = False
elif self.pause == False:
self.pause = True
解决方法
你可以试试这个:
pause=False
#your game code
for event in pygame.event.get():
if event.type==KEYUP:
if event.key==K_p:
pause = True
while pause == True:
for event in pygame.event.get():
if event.type==KEYUP:
if event.key==K_p:
pause = False
#your remaining code
您首先将暂停设为 false,然后添加一个暂停屏幕的键。
,问题是代码运行速度非常快,当您按下按钮 P
时,它会多次循环运行并多次检查 pressed_keys()
- 因此它多次执行 pauseMenu()
并且它会发生变化pause
多次,您不知道最后一个值是 True
还是 False
。但是您只需执行一次 pauseMenu()
。
您可以为此使用 event
,因为当您按下按钮时,系统只会发送一个事件,并且它会运行 pauseMenu()
只运行。
# quits if x is pressed
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_p:
# toggle value
self.pause = not self.pause
使用 pressed_keys[pygame.K_p]
您必须记住以前的值 pressed_keys[pygame.K_p]
并将其与当前值 pressed_keys[pygame.K_p]
进行比较 - 如果它从 False
变为 True
然后您必须更改 pause
。所以你必须做你已经拥有的事件。
# before loop
previus_key_p = False
# inside loop
pressed_keys = pygame.key.get_pressed()
if pressed_keys[pygame.K_p] and previus_key_p = False:
self.pauseMenu()
previus_key_p = pressed_keys[pygame.K_p]
如果您在 P
之前选中按钮 if self.pause == False:
,那么您不必在 if self.pause == False:
内再次执行此操作
编辑:添加丢失的代码后,我运行代码,主要问题是第二个 if self.pause == False:
顺便说一句:
要切换值 True/False
,您可以使用 not
def pauseMenu(self):
self.pause = not self.pause
顺便说一句:
当我使用 pygame.mouse.get_button()
按下屏幕上的按钮,然后在同一位置显示新按钮时,我很少看到类似的问题 - 它立即按下了新按钮。
编辑:
最少的工作代码。
它需要移动球员的功能,但球在移动,你可以暂停它。它还在暂停时显示文本 - 我在 if not self.pause:
之外绘制所有内容并绘制文本 Pause
,但我什至可以在暂停时绘制一些动画。
我还将 ball.refresh()
重命名为 ball.update()
并将 ball
添加到 group,现在 group 为所有对象运行 update()
。
我添加了前缀为 # <---
的评论
import pygame
from random import choice
# --- constants --- (PEP8: UPPER_CASE_NAMES)
BLACK = (0,0)
WHITE = (255,255,255)
RED = (255,0)
GREEN = (0,0)
BLUE = (0,255)
# --- classes --- (PEP8: CamelCaseNames)
class Game:
def __init__(self,start):
self.start = start
self.score1 = 0
self.score2 = 0
self.pause = False
self.over = False
def play(self,ai):
player2.AI = ai
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Pong")
self.over = False
# <--- you can create it once
#font = pygame.font.Font('ARCADECLASSIC.TTF',74)
font = pygame.font.SysFont(None,74)
# <--- value at start
previous_key_p = False
while self.start:
# quits if x is pressed
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
pressed_keys = pygame.key.get_pressed()
# <--- check also previous value
if pressed_keys[pygame.K_p] and previous_key_p == False:
self.pauseMenu()
# <--- keep current value to check it in next loop
previous_key_p = pressed_keys[pygame.K_p]
if not self.pause:
# creates list of pressed keys and using that to determine movement
pressed_keys = pygame.key.get_pressed()
if pressed_keys[pygame.K_w]:
player1.moveUp(5)
if pressed_keys[pygame.K_s]:
player1.moveDown(5)
if player2.AI == True:
player2.AI_move(ball)
if pressed_keys[pygame.K_SPACE]:
pygame.quit()
else:
if pressed_keys[pygame.K_UP]:
player2.moveUp(5)
if pressed_keys[pygame.K_DOWN]:
player2.moveDown(5)
# <--- you don't need it
#if pressed_keys[pygame.K_p]:
# self.pauseMenu()
# scoring system if ball touches variable,increments score and resets ball to middle
if ball.rect.x >= 790:
self.score1 += 1
ball.rect.x = 400
ball.rect.y = 240
ball.x_velo = choice([-2,2])
ball.y_velo = choice([-1,-2,1,2])
if ball.rect.x <= 0:
self.score2 += 1
ball.rect.x = 400
ball.rect.y = 240
ball.x_velo = choice([-2,2])
# bounces ball of top or bottom wall
if ball.rect.y > 470 or ball.rect.y < 0:
ball.y_velo = -ball.y_velo
# detects collision and reflects ball off board
if pygame.sprite.collide_mask(ball,player1) or pygame.sprite.collide_mask(ball,player2):
ball.bounce()
# <--- I renamed it to `update()` and add to group so I don't have to run it manually
# refresh method to move ball
#ball.update()
all_sprites_list.update()
if self.score1 >= 5:
self.victory("Player 1")
elif self.score2 >= 5:
self.victory("Player 2")
# <-- outside `pause` - so it can display animation also when paused
# --- only draws (without updates,etc.) ---
# draws background and sprites onto screen each tick
screen.fill(BLACK)
pygame.draw.line(screen,WHITE,[400,0],580],1)
all_sprites_list.draw(screen)
# draws score at top
text1 = font.render(str(self.score1),BLUE)
screen.blit(text1,(300,10))
text2 = font.render(str(self.score2),BLUE)
screen.blit(text2,(470,10))
if self.pause:
text = font.render('PAUSE',RED)
rect = text.get_rect()
rect.center = screen.get_rect().center
screen.blit(text,rect)
# refreshes display each tick
pygame.display.flip()
# sets number of ticks per second
clock.tick(60)
def victory(self,winner):
pass
def pauseMenu(self):
if self.pause == True:
self.pause = False
elif self.pause == False:
self.pause = True
class Player(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = pygame.surface.Surface((10,100))
self.image.fill(GREEN)
self.rect = self.image.get_rect()
self.mask = pygame.mask.from_surface(self.image)
class Ball(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = pygame.surface.Surface((10,10))
self.image.fill(RED)
self.rect = self.image.get_rect()
self.mask = pygame.mask.from_surface(self.image)
# <--- I renamed `refresh` to `update()`
def update(self):
self.rect.x += 1
def bounce(self):
pass
# --- functions --- (PEP8: lower_case_names)
# ... empty ...
# --- main ---
size = (800,600)
pygame.init()
player1 = Player()
player2 = Player()
ball = Ball()
all_sprites_list = pygame.sprite.Group((player1,player2,ball))
clock = pygame.time.Clock()
Game(True).play(False)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。