在我的简单程序中,我有一个开始按钮并检查事件,如果单击开始,我希望开始文本更改颜色然后我想要更改为false以便游戏开始。这种情况从未发生过,并且pygame不停地插入屏幕。我希望while循环开始,然后它将转到另一个while循环。如何检查是否单击了开始,更改文本颜色,然后在以下代码中结束while循环?
import pygame, sys
from pygame.locals import *
pygame.init()
FPS = 60 # frames per second setting
clock = pygame.time.Clock()
screen = pygame.display.set_mode((700, 800))
window_width = 540
window_height = 800
#Title screen fonts
fontObj2 = pygame.font.Font('freesansbold.ttf', 60)
start = fontObj2.render("Start", True,(255,255,255))
into=True
while into==True:
screen.blit(start, (window_width / 2, 600))
for event in pygame.event.get(): #Closes game
if event.type == QUIT:
pygame.quit()
sys.exit()
elif start.get_rect().collidepoint(pygame.mouse.get_pos()):
x, y = event.pos
if start.get_rect().collidepoint(x, y):
start = fontObj2.render("Start", True, (192,192,192))
into=False
elif event.type == pygame.MOUSEBUTTONDOWN:
x, y = event.pos
if start.get_rect().collidepoint(x, y):
start = fontObj2.render("Start", True, (192,192,192))
into = False
pygame.display.flip()
pygame.display.update()
clock.tick(FPS)
答案 0 :(得分:0)
首先,你可以摆脱start.get_rect().collidepoint(pygame.mouse.get_pos())
,因为你已经在event.type == pygame.MOUSEBUTTONDOWN
中定义了它。
您的代码无法正常工作,因为start.get_rect()
的位置并非位于屏幕上的位置。如果您打印它,您会在左上角看到<rect(0, 0, 140, 61)>
这是一个矩形。
要解决此问题,您只需将其更改为start.get_rect(x=window_width / 2, y=600) #where you blit the font
即可设置矩形的位置。
所以要克制:
import pygame, sys
from pygame.locals import *
pygame.init()
FPS = 60
clock = pygame.time.Clock()
screen = pygame.display.set_mode((700, 800))
window_width = 540
window_height = 800
fontObj2 = pygame.font.Font('freesansbold.ttf', 60)
start = fontObj2.render("Start", True,(255,255,255))
into=True
while into: #Equivalent to into == True
screen.blit(start, (window_width / 2, 600))
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
#got rid of another if statement
elif event.type == pygame.MOUSEBUTTONDOWN:
x, y = event.pos
if start.get_rect(x=window_width / 2, y=600).collidepoint(x, y): #changed start.get_rect
start = fontObj2.render("Start", True, (192,192,192))
into = False
#same as before
pygame.display.flip()
pygame.display.update()
clock.tick(FPS)