我有问题。我正在尝试为我正在制作的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。我在Sublime中编写了代码,但也尝试在Geany中运行它。两者都没有用。
感谢您的帮助。
答案 0 :(得分:0)
您的代码底部似乎没有if __name__ == '__main__':
部分,或者其他任何实际运行代码的部分。你正在定义所有东西,但没有任何东西在运行,因为你没有告诉它运行。
尝试在代码底部添加类似内容:
if __name__ == '__main__':
main()
StackOverflow问题What does if __name__ == "__main__": do?说明了为什么要将其放入文件中。