需要帮助定时for循环的迭代

时间:2014-04-12 16:39:49

标签: python for-loop pygame countdown

你能给我的任何帮助都会很棒。我正在使用python中的简单游戏。我想在屏幕上运行一个倒数计时器。根据本网站上回答的其他问题,我认为我的代码大多是正确的,我遇到的问题是我使用“for”循环运行定时器代码。我不太确定为什么它现在不适合我,当我运行游戏时,我没有得到任何错误,倒计时显示但它只倒计时一秒而且它坚持这一次(01:29 )。任何建议都会非常感激。我正在努力的代码是在游戏的主循环(第354行)中名为“”“Timer Countdown”“”的部分中的程序结束。非常感谢。

# 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()

1 个答案:

答案 0 :(得分:1)

使用pygame.time.get_ticks()存储开始时间, 再次调用此帧将给出比存储的开始时间更长的时间,只需从此减去开始时间以获得自计时器启动以来的毫秒间隔

正如@jonrsharpe所说,它应该是一个代码&#34;样本&#34;,而不是整个sodding的东西,因此我可能没有真正回答你的问题,我不能告诉因为我&# 39;我不会阅读和理解整个代码。