如何在一定时间后停止Python程序

时间:2013-09-16 00:38:10

标签: python random time pygame sys

我想帮助在一段时间后停止一个python程序,正如它在标题上所说的那样。 我的程序是一个有趣的程序,我正在尝试。 代码:

import pygame, sys, random, time, os

skier_images = ["puffle_down.png", "puffle_down.png", "puffle_down.png",
                 "puffle_down.png", "puffle_down.png"]

class SkierClass(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.image.load("puffle_down.png")
        self.rect = self.image.get_rect()
        self.rect.center = [320, 100]
        self.angle = 0

    def turn(self, direction): 
        self.angle = self.angle + direction
        if self.angle < -2:  self.angle = -2
        if self.angle >  2:  self.angle =  2 
        center = self.rect.center
        self.image = pygame.image.load(skier_images[self.angle])
        self.rect = self.image.get_rect()
        self.rect.center = center
        speed = [self.angle, 6 - abs(self.angle) * 2]
        return speed

    def move(self, speed):
        self.rect.centerx = self.rect.centerx + speed[0]
        if self.rect.centerx < 20:  self.rect.centerx = 100
        if self.rect.centerx > 620: self.rect.centerx = 620 

class ObstacleClass(pygame.sprite.Sprite):
    def __init__(self, image_file, location, type):
        pygame.sprite.Sprite.__init__(self) 
        self.image_file = image_file        
        self.image = pygame.image.load(image_file)
        self.location = location
        self.rect = self.image.get_rect()
        self.rect.center = location
        self.type = type
        self.passed = False

    def scroll(self, terrainPos):
        self.rect.centery = self.location[1] - terrainPos

def create_map(start, end):
    obstacles = pygame.sprite.Group()
    locations = []
    gates = pygame.sprite.Group()
    for i in range(10):                
        row = random.randint(start, end)
        col = random.randint(0, 9)
        location  = [col * 64 + 20, row * 64 + 20] 
        if not (location in locations):        
            locations.append(location)          
            type = random.choice(["tree", "flag"])
            if type == "tree": img = "puffle_bomb.png"
            elif type == "flag":  img = "puffle-o.png"
            obstacle = ObstacleClass(img, location, type)
            obstacles.add(obstacle)
    return obstacles


def animate():
    screen.fill([255, 255, 255])
    pygame.display.update(obstacles.draw(screen)) 
    screen.blit(skier.image, skier.rect)
    screen.blit(score_text, [10, 10])
    pygame.display.flip()    

def updateObstacleGroup(map0, map1):
    obstacles = pygame.sprite.Group()
    for ob in map0:  obstacles.add(ob)
    for ob in map1:  obstacles.add(ob)
    return obstacles


pygame.init()
screen = pygame.display.set_mode([640,640])
clock = pygame.time.Clock()
skier = SkierClass()
speed = [0, 6]
map_position = 0
points = 0
map0 = create_map(20, 29)
map1 = create_map(10, 19)
activeMap = 0


obstacles = updateObstacleGroup(map0, map1)


font = pygame.font.Font(None, 50)


while True:
    clock.tick(30)
    for event in pygame.event.get():
        if event.type == pygame.QUIT: os._exit(0)
        if event.type == pygame.KEYDOWN:          
            if event.key == pygame.K_LEFT:        
                speed = skier.turn(-1)
            elif event.key == pygame.K_RIGHT:     
                speed = skier.turn(1)
    skier.move(speed)
    map_position += speed[1]                      

    if map_position >=640 and activeMap == 0:
        activeMap = 1
        map0 = create_map(20, 29)
        obstacles = updateObstacleGroup(map0, map1)
    if map_position >=1280 and activeMap == 1:                        
        activeMap = 0
        for ob in map0:
            ob.location[1] = ob.location[1] - 1280   
        map_position = map_position - 1280           
        map1 = create_map(10, 19)
        obstacles = updateObstacleGroup(map0, map1)

    for obstacle in obstacles:
        obstacle.scroll(map_position)

    hit =  pygame.sprite.spritecollide(skier, obstacles, False)
    if hit:
        if hit[0].type == "tree" and not hit[0].passed:  
            points = points - 100
            skier.image = pygame.image.load("puffle_crash.jpg")  
            animate()  
            pygame.time.delay(1000)
            skier.image = pygame.image.load("puffle_down.png")  
            skier.angle = 0
            speed = [0, 6]
            hit[0].passed = True
        elif hit[0].type == "flag" and not hit[0].passed:   
            points += 100
            obstacles.remove(hit[0])                    

    score_text = font.render("Score: " +str(points), 1, (0, 0, 0))
    animate()

我不确定使用什么模块,以及如何使用。我会使用Time模块吗?所以基本上就是这样。

注意:只是说,我知道还有其他这样的问题,但我是一名新程序员,所以我想要一个更基本的答案。

1 个答案:

答案 0 :(得分:2)

使用pygame.time模块。节省游戏开始时的时间(或任何时候)。然后,在主while循环期间不断检查当前时间。如果两次之间的差异大于某个阈值,则终止程序。

以下是代码的缩短段,作为示例 - 程序应在60秒后终止:

import sys
import pygame

pygame.init()

def end_game():
    pygame.quit()
    sys.exit(0)    # Use sys.exit, not os._exit

screen = pygame.display.set_mode([640,640])
clock = pygame.time.Clock()

start_time = pygame.time.get_ticks()   # Time in milliseconds
stop_after = 60 * 1000                 # Stop after 60 seconds of gameplay    

while True:
    clock.tick(30)
    for event in pygame.event.get():
        if event.type == pygame.QUIT: 
            end_game()

    current_time = pygame.time.get_ticks()
    if (current_time - start_time) >= stop_after:
        end_game()