从主菜单过渡到游戏pygame的错误

问题描述 投票:1回答:1

对不起,标题太模糊了,我也不知道我的代码有什么问题。

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

运行此行时似乎有问题,例如代码在我的屏幕上以不同的颜色显示为阴影,并且运行时不会更改为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()
python pygame boolean
1个回答
1
投票

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

global
© www.soinside.com 2019 - 2024. All rights reserved.