从主菜单过渡到游戏 pygame 时出错



呃,对不起,标题超级模糊,我也不知道我的代码出了什么问题。

if event.type == pygame.K_SPACE:
run= True

运行此行时似乎存在问题,例如代码在我的屏幕上着色为不同的颜色,并且它不会将 run 更改为 True 如果我删除,这个问题似乎已解决: def mainmenu(( 并且只是使用一个while循环,但是,我认为它变得非常混乱,并且对删除它犹豫不决。

此外,当我运行mainmenu((函数时,加载需要相当长的时间,这是我迄今为止还没有遇到的问题,我不确定为什么或如何解决它。

import pygame
import time
import random
pygame.init()
window = pygame.display.set_mode((1000,700))

White=(255,255,255)
font = pygame.font.SysFont("comicsansms", 25)
#for easier counting of lives, score here starts from 1, just simply subtract 1 from whats displayed later
score = 1
clicks = 1
lives = 3
run=False
intro=True
def mainmenu():

while intro:
window.fill((0, 0, 0))
text = font.render("Press space to start!" , True, White)
window.blit(text, (500, 350))
for event in pygame.event.get():
if event.type == pygame.QUIT:
intro = False
pygame.quit()
quit()
if event.type == pygame.K_SPACE:
run= True

class Circle():
def __init__(self, color, x, y, radius, width):
self.color = color
self.x = x
self.y = y
self.radius = radius
self.width = width

def draw(self, win, outline=None):
pygame.draw.circle(win, self.color, (self.x, self.y), self.radius, self.width)
def isOver(self, mouse):

dx, dy = mouse[0] - self.x, mouse[1] - self.y
return (dx * dx + dy * dy) <= self.radius * self.radius

circles = []
def redrawWindow():
window.fill((0, 0, 0))
for c in circles:
c.draw(window)
text = font.render("Score:" + str(score-1), True, White)
window.blit(text, (0,0))
text = font.render("Lives:" + str(lives), True, White)
window.blit(text, (900, 0))

clock = pygame.time.Clock()
FPS = 60
x = str(pygame.time.get_ticks())
current_time = 0
next_circle_time = 0

while run:
delta_ms = clock.tick()
current_time += delta_ms
if  current_time > next_circle_time:
next_circle_time = current_time + 1000 # 1000 milliseconds (1 second)
r = 20
new_circle = Circle((255, 255, 255), random.randint(r, 800-r), random.randint(r, 600-r), r, r)
circles.append(new_circle)
print()
redrawWindow()
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
run=False
pygame.quit()
quit()
if event.type == pygame.MOUSEBUTTONDOWN:
clicks += 1
mouse = pygame.mouse.get_pos()
for circle in circles:
if circle.isOver(mouse):
score += 1
circles.pop(circles.index(circle))
lives= 3-(clicks-score)
pygame.display.update()
run

是全局命名空间中的一个变量。如果要在函数的全局命名空间中编写变量,则必须使用global语句,这意味着列出的标识符将被解释为全局:

run=False
intro=True
def mainmenu():
global run, intro
while intro:
window.fill((0, 0, 0))
text = font.render("Press space to start!" , True, White)
window.blit(text, (500, 350))
for event in pygame.event.get():
if event.type == pygame.QUIT:
intro = False
pygame.quit()
quit()
if event.type == pygame.K_SPACE:
run = True

最新更新