2014-04-12 2 views
0

도움을 주시면 도움이 될 것입니다. 나는 파이썬으로 간단한 게임을 만들고있다. 나는 카운트 다운 타이머가 화면에서 실행되도록하고 싶습니다. 이 사이트에서 답변 된 다른 질문에 따라 코드가 대부분 정확하다고 생각합니다. 문제는 "for"루프를 사용하여 타이머 코드를 실행하고 있다는 것입니다. 나는 정말로 그 순간 나를 위해 일하지 않는 이유를 모르겠다. 나는 게임을 할 때, 나는 아무런 실수도하지 않는다. 카운트 다운이 표시되지만, 그것은 단지 1 초 만에 카운트 다운을한다.). 모든 제안은 정말 감사하겠습니다. 내가 고민하고있는 코드는 게임의 메인 루프 (354 행)에서 "타이머 카운트 다운" ""이라는 섹션에서 프로그램이 끝나갈 무렵이다. 많은 감사합니다.for 루프의 반복을 타이밍하는 데 도움이 필요합니다.

# Ice Hockey Game 
from livewires import games, color 
from tkinter import* 
import pygame 
import math, random 
import os 
import sys 
import time 
pygame.init() 

games.init(screen_width = 1016, screen_height = 511, fps = 50) 



################################################################################ 
"""timer variables""" 
################################################################################ 
clock = pygame.time.Clock() 
font = pygame.font.Font(None, 25) 
red  = (255, 0, 0) 
frame_count = 0 
frame_rate = 50 
start_time = 90 
done= False 
output_string = "" 

################################################################################ 
"""Score display variables""" 
################################################################################ 
right_score = games.Text(value = 0, size = 25, color = color.black, 
           top = 30, right = games.screen.width - 250, 
           is_collideable = False) 
games.screen.add(right_score) 

left_score = games.Text(value = 0, size = 25, color = color.black, 
           top = 30, right = 250, 
           is_collideable = False) 
games.screen.add(left_score) 

player1_message = games.Message(value = "Player 1 Score", 
          size = 35, 
          color = color.black, 
          x = 250, 
          y = 15, 
          lifetime = 100000000, 
          is_collideable = False) 

games.screen.add(player1_message) 

player2_message = games.Message(value = "Player 2 Score", 
          size = 35, 
          color = color.black, 
          x = 750, 
          y = 15, 
          lifetime = 100000000, 
          is_collideable = False) 

games.screen.add(player2_message) 

############################################################################### 
"""Player 1 and Player 2 WIN messages""" 
############################################################################### 

p1_won_message = games.Message(value = "Player 1 Wins!!!", 
          size = 100, 
          color = color.blue, 
          x = games.screen.width/2, 
          y = games.screen.height/2, 
          lifetime = 500, 
          after_death = games.screen.quit, 
          is_collideable = False) 

p2_won_message = games.Message(value = "Player 2 Wins!!!", 
          size = 100, 
          color = color.blue, 
          x = games.screen.width/2, 
          y = games.screen.height/2, 
          lifetime = 500, 
          after_death = games.screen.quit, 
          is_collideable = False) 

############################################################################## 
"""Goal animation images and functions""" 
################################################################################ 

"""Animation images""" 
goal_anim_files = ["Goal_Anim_001.bmp", "Goal_Anim_002.bmp", "Goal_Anim_003.bmp", 
      "Goal_Anim_004.bmp","Goal_Anim_005.bmp","Goal_Anim_006.bmp", 
      "Goal_Anim_007.bmp","Goal_Anim_008.bmp","Goal_Anim_009.bmp","Goal_Anim_010.bmp", "Goal_Anim_011.bmp", "Goal_Anim_012.bmp", "Goal_Anim_013.bmp", 
      "Goal_Anim_014.bmp","Goal_Anim_015.bmp","Goal_Anim_016.bmp", 
      "Goal_Anim_017.bmp","Goal_Anim_018.bmp","Goal_Anim_019.bmp","Goal_Anim_020.bmp", "Goal_Anim_021.bmp","Goal_Anim_022.bmp", "Goal_Anim_023.bmp", 
      "Goal_Anim_024.bmp","Goal_Anim_025.bmp"] 

def goal_msg_left(self): 
    global goal_anim_left  
    goal_anim_left = games.Animation(images = goal_anim_files, x = 250, 
        y= games.screen.height/2, n_repeats = 1, 
        repeat_interval = 1, is_collideable = False) 

    #print("inside goal_msg_left") 

def goal_msg_right(self): 
    global goal_anim_right 
    goal_anim_right = games.Animation(images = goal_anim_files, x = 750, 
        y= games.screen.height/2, n_repeats = 1, 
        repeat_interval = 1, is_collideable = False) 

    #print("inside goal_msg_right") 

class Leftgoalanim(games.Animation): 
    """goal animation""" 


    def update(self): 
     self.check_collide() 

    def check_collide(self): 
     for player1 in self.overlapping_sprites: 
      player1.handle_player_collide() 
     for player2 in self.overlapping_sprites: 
      player2.handle_player_collide() 

class Leftgoal(games.Sprite): 

    def update(self):  
     self.check_collide() 
     self.check_goal() 
    def check_collide(self): 
     """ Check for collision with puck. """ 
     for puck in self.overlapping_sprites: 
      puck.handle_collide() 

    def handle_collide(self): 
     """ Move to a random screen location. """ 
     self.dx = -self.dx 
     self.dy = 0 
     self.x = games.screen.width/2 
     self.y = games.screen.height/2 



    def check_goal(self): 
     """ Check if left goal. """ 

     global goal_anim_left  
     for puck in self.overlapping_sprites: 

      #puck.handle_collide() 
      goal_msg_left(self) 
      games.screen.add(goal_anim_left) 
      right_score.value += 1 
      if right_score.value >= 10: 
       games.screen.add(p2_won_message) 


class Rightgoal(games.Sprite): 
    def update(self):  
     self.check_collide() 
     self.check_goal() 
    def check_collide(self): 
     """ Check for collision with puck. """ 
     for puck in self.overlapping_sprites: 
      puck.handle_collide() 

    def handle_collide(self): 
     """ Move to a random screen location. """ 
     self.dx = -self.dx 
     self.dy = 0 
     self.x = games.screen.width/2 
     self.y = games.screen.height/2 

    def check_goal(self): 
     """ Check if left goal. """ 
     for puck in self.overlapping_sprites: 

      #puck.handle_collide() 
      goal_msg_right(self) 
      games.screen.add(goal_anim_right) 
      left_score.value += 1 
      if left_score.value >= 10: 
       games.screen.add(p1_won_message) 


################################################################################ 
"""Classes for Players sprites"""   
################################################################################ 

class Player1(games.Sprite): 
    """move the player 1""" 
    VELOCITY_STEP = .03 
    VELOCITY_MAX = 3 

    def update(self): 
     if games.keyboard.is_pressed(games.K_w): 
      self.y -= 3 
     if games.keyboard.is_pressed(games.K_s): 
      self.y += 3 
     if games.keyboard.is_pressed(games.K_a): 
      self.x -= 3 
     if games.keyboard.is_pressed(games.K_d): 
      self.x += 3 

     if self.right > 940: 
      self.x = 913 
     if self.left < 85: 
      self.x = 108 

     if self.bottom > games.screen.height: 
      self.y = 475 
     if self.top < 0: 
      self.y = 50 

     self.check_collide() 

    def check_collide(self): 
     """ Check for collision with puck. """ 
     for puck in self.overlapping_sprites: 
      puck.handle_collide() 

    def handle_player_collide(self): 
     self.dx = -self.dx 
     self.dy = 0 


    def handle_collide(self): 
     """ Move to a random screen location. """ 
     self.dx = -self.dx 
     self.dy = 0 



class Player2(games.Sprite): 
    """move the player 2""" 
    VELOCITY_STEP = .03 
    VELOCITY_MAX = 3 
    def update(self): 

     if games.keyboard.is_pressed(games.K_UP): 
      self.y -= 3 
     if games.keyboard.is_pressed(games.K_DOWN): 
      self.y += 3 
     if games.keyboard.is_pressed(games.K_LEFT): 
      self.x -= 3 
     if games.keyboard.is_pressed(games.K_RIGHT): 
      self.x += 3 

     if self.right > 940: 
      self.x = 913 
     if self.left < 85: 
      self.x = 108 

     if self.bottom > games.screen.height: 
      self.y = 475 
     if self.top < 0: 
      self.y = 50 

     self.check_collide() 


    def check_collide(self): 
     """ Check for collision with puck. """ 
     for puck in self.overlapping_sprites: 
      puck.handle_collide() 

    def handle_collide(self): 
     """ Move to a random screen location. """ 
     self.dx = -self.dx 
     self.dy = 0 

    def handle_player_collide(self): 
     self.dx = -self.dx 
     self.dy = 0 


################################################################################ 
"""Class for Puck""" 
################################################################################ 

class Puck(games.Sprite): 
    """ A bouncing puck. """ 

    def update(self): 
     """ Reverse a velocity component if edge of screen reached. """ 
     if self.right > games.screen.width or self.left < 0: 
      self.dx = -self.dx 

     if self.bottom > games.screen.height or self.top < 0: 
      self.dy = -self.dy 

    def handle_collide(self): 
     """ reverses x direction when collides. """ 
     self.dx = -self.dx 
     self.dy = self.dy 

    def handle_goal(self): 
     """what happens to the puck when goal""" 
     self.dx = -self.dx 
     self.dy = self.dy 


################################################################################ 

"""Main Loop For Game""" 

################################################################################ 



def main(): 
    wall_image = games.load_image("Table_002_1016H_511W.jpg", transparent = False) 
    games.screen.background = wall_image 



    #########image left and right goal images and add them to game########## 
    left_goal_image = games.load_image("Goal_left_cropped.bmp") 
    the_left_goal = Leftgoal(image = left_goal_image, 
          x = 40, 
          y = games.screen.height/2, 
          ) 

    right_goal_image = games.load_image("Goal_right_cropped.bmp") 
    the_right_goal = Rightgoal(image = right_goal_image, 
          x = 976, 
          y = games.screen.height/2, 
          ) 


    #########player 1 import image and add to game########################## 
    player1_image = games.load_image("Player_red_half_50_75_Fixed.bmp") 
    the_player1 = Player1(image = player1_image, 
         x = games.screen.width/4, 
         y = games.screen.height/2) 
    games.screen.add(the_player1) 

    #########player 2 import image and add to game########################## 
    player2_image = games.load_image("Player_green_half_50_75_flipped_fixed.bmp") 
    the_player2 = Player2(image = player2_image, 
         x = 750, 
         y = games.screen.height/2) 

    games.screen.add(the_player2) 

    ################Import image for the Puck and Add to the game########### 
    puck_image = games.load_image("puck_small.png", transparent = True) 
    the_puck = Puck(image = puck_image, 
         x = games.screen.width/2, 
         y = games.screen.height/2, 
         dx = -3, 
         dy = 3) 
    counter = 0 

########################################################################### 
    """TIMER COUNTDOWN""" 
########################################################################### 
    clock = pygame.time.Clock() 
    font = pygame.font.Font(None, 25) 
    red  = (255, 0, 0) 
    frame_count = 0 
    frame_rate = 50 
    start_time = 90 
    done= False 
    output_string = "" 
    for n in reversed(range(0, start_time)): 
     total_seconds = frame_count // frame_rate 

     minutes = total_seconds // 60 

     seconds = total_seconds % 60 

     output_string = "Time: {0:02}:{1:02}".format(minutes, seconds) 
     # Blit to the screen 
     text = font.render(output_string, True, red) 
     #screen.blit(text, [250, 250]) 

     # --- Timer going down --- 
     # --- Timer going up --- 
     # Calculate total seconds 
     total_seconds = start_time - (frame_count // frame_rate) 
     if total_seconds < 0: 
      total_seconds = 0 

     # Divide by 60 to get total minutes 
     minutes = total_seconds // 60 

     # Use modulus (remainder) to get seconds 
     seconds = total_seconds % 60 

     # Use python string formatting to format in leading zeros 
     output_string = "Time left: {0:02}:{1:02}".format(minutes, seconds) 

     # Blit to the screen 
     text = font.render(output_string, True, red) 

     #screen.blit(text, [250, 280]) 

     # ALL CODE TO DRAW SHOULD GO ABOVE THIS COMMENT 
     frame_count += 1 
     # Limit to 20 frames per second 
     clock.tick_busy_loop(50) 

     # Go ahead and update the screen with what we've drawn. 
     pygame.display.flip() 

    ###Timer Display### 

    timer_text = games.Message(value = "TIME", 
           size = 45, 
           color = color.red, 
           top = 30, right = games.screen.width/2, 
           lifetime = 100000000, 
           is_collideable = False) 
    timer_countdown = games.Text(value = output_string, size = 25, color = color.red, 
            top = 60, right = 600, 
            is_collideable = False) 

    games.screen.add(timer_countdown) 
    games.screen.add(timer_text)  
    games.screen.add(the_left_goal) 
    games.screen.add(the_right_goal) 
    games.screen.add(the_puck) 
    games.screen.event_grab = True 
    games.mouse.is_visible = False 
    games.screen.mainloop() 

# start the game 
main() 
+7

코드를 최소한으로 줄이십시오. http://stackoverflow.com/help/mcve를 참조하십시오. – jonrsharpe

답변

1

사용 pygame.time.get_ticks() 간격의를 얻기 위해 단순히이에서 시작 시간을 빼기, 저장된 시작 시간보다 더 많은 시간을 줄 것이다이 다시 모든 프레임을 호출 를 시작 시간을 저장하기 타이머가 시작된 이래로 밀리 초

@jonrsharpe가 말한 것처럼, "샘플"코드가되어야하며, 모든 sodding 물건이 아니기 때문에 실제로 질문에 대답하지 않았을 수도 있습니다. 전체 코드를 읽고 이해하지 않을 것입니다.

관련 문제