1

正如标题上所说,我想在一段时间后停止 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 模块吗?如何使用?所以基本上,就是这样。

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

4

1 回答 1

3

使用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()
于 2013-09-16T03:53:19.870 回答