我对Python比较陌生。我一直在修改这个游戏代码并包含一个开始屏幕等。我遇到的问题是,当游戏结束时,我试图让用户在12点输入y时再次启动它。我有按键按下但是计时器似乎有问题。在6.4中它使用的是get.ticks()但是我似乎无法在游戏重启时重新初始化此计时器。 6.4用于绘制和倒计时。然后在10中进一步向下进行比较获胜/松散检查,然后进入11,确定是否显示获胜/松散显示。游戏意味着只有90秒的时间限制,然后在游戏重新初始化时重新启动(即玩家在12时选择y)。 (我已将其设置为9秒进行调试)。游戏的健康方面可以工作,但是当游戏重新启动时,计时器也会生效。如果可以的话请帮忙。请参阅下面的代码。
# 1 - Import library
import pygame
from pygame.locals import *
import math
import random
import time
import sys
# 2 - Initialize the game
width, height = 640, 480
keys = [False, False, False, False]
fps = 15
# 2.0.1 - Initialises colours 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
def main():
print "1"
global screen, basicfont, fpsclock
pygame.init()
fpsclock = pygame.time.Clock()
screen = pygame.display.set_mode((width, height))
# 2.0.2 - Sets font and size for press any key on start screen ---
basicfont = pygame.font.Font('freesansbold.ttf', 15)
# 2.0.3 - Sets Game name in window much like Title tag in HTML -
pygame.display.set_caption('Developed by: xxxx')
#-------------------------------------------------------------
# 2.0.4 - Puts a game icon next to your caption ----------------
gameIcon = pygame.image.load("resources/images/plane.png")
pygame.display.set_icon(gameIcon)
#-------------------------------------------------------
startScreen()
def restart():
pygame.quit()
main()
def drawPressKeyMsg():
pressKeySurf = basicfont.render('Press any key to play.', True, white)
pressKeyRect = pressKeySurf.get_rect()
pressKeyRect.topleft = (width - 200, height - 30)
screen.blit(pressKeySurf, pressKeyRect)
def terminate():
pygame.quit()
sys.exit()
def checkForKeyPress():
if len(pygame.event.get(QUIT)) > 0:
terminate()
keyUpEvents = pygame.event.get(KEYUP)
if len(keyUpEvents) == 0:
return None
if keyUpEvents[0].key == K_ESCAPE:
terminate()
return keyUpEvents[0].key
def startScreen():
# 2.0. - Change start screen attributes between hashes --------------
titleFont = pygame.font.Font('freesansbold.ttf', 60)
titleSurf1 = titleFont.render('Naval Warfare', True, red)
titleSurf2 = titleFont.render('Naval Warfare', True, green)
#---------------------------------------------------------------------
degrees1 = 0
degrees2 = 0
while True:
background = pygame.image.load("resources/images/falcons.png")
screen.blit(background, (0,0))
rotatedSurf1 = pygame.transform.rotate(titleSurf1, degrees1)
rotatedRect1 = rotatedSurf1.get_rect()
rotatedRect1.center = (width/2, height/2)
screen.blit(rotatedSurf1, rotatedRect1)
rotatedSurf2 = pygame.transform.rotate(titleSurf2, degrees2)
rotatedRect2 = rotatedSurf2.get_rect()
rotatedRect2.center = (width/2, height/2)
screen.blit(rotatedSurf2, rotatedRect2)
drawPressKeyMsg()
if checkForKeyPress():
pygame.event.get() # clear event queue
runGame()
return
pygame.display.update()
fpsclock.tick(fps)
degrees1 -= 7 # rotate by -7 degrees each frame
degrees2 += 7 # rotate by 7 degrees each frame
def runGame():
print"2"
# 2.1 - Changes initial player position --
playerpos=[100,240]
# ----------------------------------------
acc=[0,0]
arrows=[]
badtimer=100
badtimer1=0
badguys=[[640,100]]
healthvalue=194
pygame.mixer.init()
# 3 - Load image
# 3.0.1 - Remember when using own images change file names below ----------
player = pygame.image.load("resources/images/plane.png")
grass = pygame.image.load("resources/images/wave.png")
castle = pygame.image.load("resources/images/carrier.png")
arrow = pygame.image.load("resources/images/missile.png")
badguyimg1 = pygame.image.load("resources/images/helo.png")
badguyimg=badguyimg1
healthbar = pygame.image.load("resources/images/healthbar.png")
health = pygame.image.load("resources/images/health.png")
gameover = pygame.image.load("resources/images/gameover.png")
youwin = pygame.image.load("resources/images/youwin.png")
# 3.1 - Load audio
hit = pygame.mixer.Sound("resources/audio/explode.wav")
enemy = pygame.mixer.Sound("resources/audio/enemy.wav")
shoot = pygame.mixer.Sound("resources/audio/shoot.wav")
hit.set_volume(0.05)
enemy.set_volume(0.05)
shoot.set_volume(0.05)
pygame.mixer.music.load('resources/audio/moonlight.wav')
pygame.mixer.music.play(-1, 0.0)
pygame.mixer.music.set_volume(0.25)
# 4 - keep looping through
running = 1
exitcode = 0
print "exitcode before if: ", exitcode
while running:
print running, " running"
badtimer-=1
# 5 - clear the screen before drawing it again
screen.fill(0)
# 6 - draw the castles and the background
# ------------------------------------------------------------------------
# 6.0.1 - If using a 640 x 480 image remove code between hashes
# for x in range(width/grass.get_width()+1):
# for y in range(height/grass.get_height()+1):
# screen.blit(grass,(x*100,y*100))
# ------------------------------------------------------------------------
# 6.0.2- Replace code below with: screen.blit(grass,(0,0)) and remove indent
screen.blit(grass,(0,0))
# ------------------------------------------------------------------------
screen.blit(castle,(0,30))
screen.blit(castle,(0,135))
screen.blit(castle,(0,240))
screen.blit(castle,(0,345 ))
# 6.1 - Set player position and rotation
position = pygame.mouse.get_pos()
angle = math.atan2(position[1]-(playerpos[1]+32),position[0]-(playerpos[0]+26))
playerrot = pygame.transform.rotate(player, 360-angle*57.29)
playerpos1 = (playerpos[0]-playerrot.get_rect().width/2, playerpos[1]-playerrot.get_rect().height/2)
screen.blit(playerrot, playerpos1)
# 6.2 - Draw arrows
for bullet in arrows:
index=0
# 6.2.1 - Changing the multiplier value changes the speed at which bullets travel ie 10 -> 5
velx=math.cos(bullet[0])*5
vely=math.sin(bullet[0])*5
# ----------------------------------------------------------------------------
bullet[1]+=velx
bullet[2]+=vely
if bullet[1]<-64 or bullet[1]>640 or bullet[2]<-64 or bullet[2]>480:
arrows.pop(index)
index+=1
for projectile in arrows:
arrow1 = pygame.transform.rotate(arrow, 360-projectile[0]*57.29)
screen.blit(arrow1, (projectile[1], projectile[2]))
# 6.3 - Draw badgers
if badtimer==0:
badguys.append([640, random.randint(50,430)])
badtimer=100-(badtimer1*2)
if badtimer1>=35:
badtimer1=35
else:
badtimer1+=5
index=0
for badguy in badguys:
if badguy[0]<-64:
badguys.pop(index)
# 6.3.0 - Initial x position value is 640. The more we subtract the faster the x position reduces.
# Hence the faster the badger moves across the screen when it updates the x position in the loop.
badguy[0]-=2 # ie 7 -> 2
# ----------------------------------------------------------------------------
# 6.3.1 - Attack castle
badrect=pygame.Rect(badguyimg.get_rect())
badrect.top=badguy[1]
badrect.left=badguy[0]
if badrect.left<64:
hit.play()
healthvalue -= random.randint(5,20)
badguys.pop(index)
# 6.3.2 - Check for collisions
index1=0
for bullet in arrows:
bullrect=pygame.Rect(arrow.get_rect())
bullrect.left=bullet[1]
bullrect.top=bullet[2]
if badrect.colliderect(bullrect):
enemy.play()
acc[0]+=1
badguys.pop(index)
arrows.pop(index1)
index1+=1
# 6.3.3 - Next bad guy
index+=1
for badguy in badguys:
screen.blit(badguyimg, badguy)
# 6.4 - Draw clock
time = pygame.time.get_ticks()
font = pygame.font.Font(None, 24)
survivedtext = font.render(str((90000-time)/60000)+":"+str((90000-time)/1000%60).zfill(2), True, (0,0,0))
textRect = survivedtext.get_rect()
textRect.topright=[635,5]
screen.blit(survivedtext, textRect)
# 6.5 - Draw health bar
screen.blit(healthbar, (5,5))
for health1 in range(healthvalue):
screen.blit(health, (health1+8,8))
# 7 - update the screen
pygame.display.flip()
# 8 - loop through the events
for event in pygame.event.get():
# check if the event is the X button
if event.type==pygame.QUIT:
# if it is quit the game
terminate()
if event.type == pygame.KEYDOWN:
if event.key==K_w:
keys[0]=True
elif event.key==K_a:
keys[1]=True
elif event.key==K_s:
keys[2]=True
elif event.key==K_d:
keys[3]=True
if event.type == pygame.KEYUP:
if event.key==pygame.K_w:
keys[0]=False
elif event.key==pygame.K_a:
keys[1]=False
elif event.key==pygame.K_s:
keys[2]=False
elif event.key==pygame.K_d:
keys[3]=False
if event.type==pygame.MOUSEBUTTONDOWN:
shoot.play()
position=pygame.mouse.get_pos()
acc[1]+=1
arrows.append([math.atan2(position[1]-(playerpos1[1]+32),position[0]-(playerpos1[0]+26)),playerpos1[0]+32,playerpos1[1]+32])
# 9 - Move player
if keys[0]:
playerpos[1]-=5
elif keys[2]:
playerpos[1]+=5
if keys[1]:
playerpos[0]-=5
elif keys[3]:
playerpos[0]+=5
print running , "before win lose check"
#10 - Win/Lose check
if time >=9000:
running=0
print running, "time check"
exitcode=1
if healthvalue<=0:
running=0
print running, "health check"
exitcode=0
if acc[1]!=0:
accuracy=acc[0]*1.0/acc[1]*100
else:
accuracy=0
print running , "after win lose check"
# 11 - Win/lose display
if exitcode==0:
pygame.font.init()
font = pygame.font.Font(None, 24)
text = font.render("Accuracy: "+str(accuracy)+"%", True, white)
textRect = text.get_rect()
textRect.centerx = screen.get_rect().centerx
textRect.centery = screen.get_rect().centery+24
screen.blit(gameover, (0,0))
screen.blit(text, textRect)
pygame.display.flip()
else:
pygame.font.init()
font = pygame.font.Font(None, 24)
text = font.render("Accuracy: "+str(accuracy)+"%.", True, white)
textRect = text.get_rect()
textRect.centerx = screen.get_rect().centerx
textRect.centery = screen.get_rect().centery+24
screen.blit(youwin, (0,0))
screen.blit(text, textRect)
pygame.display.flip()
print time
print "3"
print "exitcode in win/lose display: ", exitcode
print "running" , running
#12 player selections at end of game
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT:
terminate()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_y:
print "y pressed down."
restart()
break
elif event.key == pygame.K_n:
print "n pressed down."
terminate()
elif event.type == pygame.KEYUP:
if event.key == pygame.K_y:
print "y released."
elif event.key == pygame.K_n:
print "n released."
terminate()
if __name__ == '__main__':
main()
答案 0 :(得分:0)
遗憾的是,我不能测试我的建议,但这里的逻辑会有所帮助。如果有一个地方可以下载代码,那将会有所帮助 - 缺少资源,导致我无法运行代码。
你的#12没有重启游戏,因为它发生在rungame()
def内。尝试将其移出rungame
,可能将其包裹在#2中以rungame()
开头的代码中。如果这不起作用,请从main或任何其他出口点调用它。
编辑1:
尝试将代码移至2.0.4以下部分,如下例所示。以下代码旨在完全替换startScreen()
。
注意:由于restart()
代码,pygame.quit()
函数可能会导致问题...
#-------------------------------------------------------
start_game = True
while 1:
if start_game:
startScreen()
start_game = False
for event in pygame.event.get():
if event.type == pygame.QUIT:
terminate()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_y:
print "y pressed down."
##########
start_game = True
##########
#restart()
#break
elif event.key == pygame.K_n:
print "n pressed down."
terminate()
elif event.type == pygame.KEYUP:
if event.key == pygame.K_y:
print "y released."
##########
start_game = True
##########
elif event.key == pygame.K_n:
print "n released."
terminate()