Python代码什么都不做就退出了

2024-06-02 08:09:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我有个问题。我正在为我正在制作的python游戏编写一个菜单。但我有个问题。每次我运行代码时,代码都会退出,甚至什么都不做。我查了一下密码,没有发现任何能导致这种情况的东西。代码如下:

#importing the libraries
import pygame
import sys

WINDOWWIDTH = 640
WINDOWHEIGHT = 480
#colour       R    G    B
WHITE     = (255, 255, 255)
BLACK     = (  0,   0,   0)
RED       = (255,   0,   0)
GREEN     = (  0, 255,   0)
DARKGREEN = (  0, 155,   0)
DARKGREY  = ( 40,  40,  40)
BGCOLOR = BLACK

DISPLAYSURF = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))

def main():
global DISPLAYSURF, BASICFONT

pygame.init()
DISPLAYSURF = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
BASICFONT = pygame.font.Font('DrippingCool.ttf, 18')
pygame.display.set_caption('Badger Defense - Aplha(0.0.1)')

showStartScreen()

#Drawing the screen
DISPLAYSURF.fill(BGCOLOR)
pygame.display.update()

#Drawing the message
def drawPressKeyMsg():
pressKeySurf = BASICFONT.render("Press a key to play...", True, DARKGREY)
pressKeyRect = pressKeySurf.get_rect()
pressKeyRect.topleft = (WINDOWWIDTH - 200, WINDOWHEIGHT - 30)
DISPLAYSURF.blit(pressKeySurf, pressKeyRect)

#Reaction to the message
def checkForKeyPress():
if len(pygame.event.get(QUIT)) > 0:
    terminate()

keyUpEvents = pygame.event.get(KEYUP)
if len(keyUpEvent) == 0:
    return None
if keyUpEvents[0].key == K_SPACE:
    terminate()
return keyUpEvents[0].key

#Showing the start screen
def showStartScreen():
titleFont = pygame.font.Font('DrippingCool.ttf', 100)
titleMain = titleFont.render('Badger Defense', True, WHITE, DARKGREEN)
titleSecond = titleFont.render('Badger Defense', True, GREEN)

degrees1 = 0
degrees2 = 0
while True:
    DISPLAYSURF.fill(BCOLOR)
    rotatedSurf1 = pygame.transform.rotate(titleSurf1, degrees1)
    rotatedRect1 = rotatedSurf1.get_rect()
    rotatedRect1.center = (WINDOWWIDTH / 2, WINDOWHEIGHT / 2)
    DISPLAYSURF.blit(rotatedSurf1, rotatedRect1)

    rotatedSurf2 = pygame.transform.rotate(titleSurf2, degrees2)
    rotatedRect2 = rotatedSurf2.get_rect()
    rotatedRect2.center = (WINDOWWIDTH / 2, WINDOWHEIGHT / 2)
    DISPLAYSURF.blit(rotatedSurf2, rotatedRect2)

    drawPressKeyMsg()

    if checkForKeyPress():
        pygame.event.get()
        return
    pygame.display.update()
    degrees1 += 3 #rotate by 3 degrees each frame
    degrees2 += 7 #rotate by 7 degrees each frame

def terminate():
pygame.quit()
sys.exit()

我正在运行Ubuntu 12.04。我写了崇高的代码,但试图运行它在Geany以及。两个都没用。你知道吗

提前谢谢你的帮助。你知道吗


Tags: the代码truegetifdefdisplaypygame
1条回答
网友
1楼 · 发布于 2024-06-02 08:09:03

您的代码底部似乎没有if __name__ == '__main__':部分,或者其他任何实际运行代码的部分。你正在定义一切,但是没有任何东西运行,因为你没有告诉它运行。你知道吗

尝试在代码底部添加类似的内容:

if __name__ == '__main__':
    main()

StackOverflow问题What does if __name__ == "__main__": do?讨论了为什么要将其放入文件中。你知道吗

相关问题 更多 >