2016-09-19 191 views
-1

我對Python比較陌生。我一直在修改這個遊戲代碼,包括一個開始屏幕等。我遇到的問題是,當遊戲結束時,我試圖讓用戶在12輸入y時重新開始。我已經按下了鍵,但是計時器似乎有問題。在6.4中它使用get.ticks(),但我似乎無法在遊戲重新啓動時重新初始化此計時器。 6.4用於繪製並倒計時。然後進一步下降到10比較的勝利/鬆動檢查,然後通過11決定是否顯示一個勝利/鬆散顯示。遊戲意味着只有90秒的時間限制,然後在遊戲重新初始化時重新啓動(即玩家在12時選擇y)。 (我已將其設置爲9秒進行調試)。遊戲的健康方面是有效的,但是當遊戲重新開始時,計時器也會生效。如果可以的話請幫忙。見下面的代碼。Python/Pygame遊戲中的計時器問題

# 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

不是問題,但我注意到,您導入'time'模塊,然後使用相同的名稱作爲遊戲中的定時器。如果你想使用這個模塊中的函數,這會在稍後導致問題。 – SiHa

+0

是啊,明白你的意思。沒有想到這一點。我會改變這一點。感謝那。 –

+0

我改了名字,仍然和以前一樣。任何其他想法可能有幫助? –

回答

0

我很遺憾不能測試我的建議,但這裏的邏輯將有所幫助。如果有什麼地方可以下載代碼,它會有所幫助 - 有資源遺漏,阻止我運行代碼。

您的#12沒有重新啓動遊戲,因爲它發生在rungame() def內。嘗試將它從rungame中移出,可能將它包裝在#2中開始rungame()的代碼中。如果這不起作用,請從main或任何其他退出點調用它。

EDIT 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() 
+0

感謝您的編輯,@Frogatto:D – JasonD

+0

明天我會放棄它。這說得通。謝謝你的幫助。我會及時向大家發佈。 –

+0

我試圖將#2移動到while循環,但我得到一個視頻未初始化錯誤。然後,我將它移到main中,但遇到與原始位置時相同的問題。問題似乎是,當重啓後在#10發生贏/鬆檢查時,由於時間大於9000,所以直接進入#11。這就是爲什麼我認爲這是一個計時器問題。我有我的意思,但似乎無法上傳的屏幕截圖。任何其他的想法? –