Pygame在执行循环时运行命令

2024-03-29 06:42:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个pygame脚本,允许我移动sprite(bot),并且我可以使用这个^{{cd1>}运行它。

这是我的脚本:

import pygame, random
import time
#Let's import the Car Class
from car import Car
pygame.init()
GREEN = (20, 255, 140)
GREY = (210, 210 ,210)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
PURPLE = (255, 0, 255)

SCREENWIDTH=400
SCREENHEIGHT=500
size = (SCREENWIDTH, SCREENHEIGHT)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Car Racing")

#This will be a list that will contain all the sprites we intend to use in our game.
all_sprites_list = pygame.sprite.Group()

bot = Car(RED, 20, 30)
bot.rect.x = 200
bot.rect.y = 300

# Add the car to the list of objects
all_sprites_list.add(bot)

#Allowing the user to close the window...
carryOn = True
clock=pygame.time.Clock()

while carryOn:
        for event in pygame.event.get():
            if event.type==pygame.QUIT:
                carryOn=False
            elif event.type==pygame.KEYDOWN:
                if event.key==pygame.K_x: #Pressing the x Key will quit the game
                     carryOn=False

        keys = pygame.key.get_pressed()
        '''
        if keys[pygame.K_LEFT]:
            bot.moveLeft(5)
        if keys[pygame.K_RIGHT]:
            bot.moveRight(5)
        if keys[pygame.K_UP]:
            bot.moveForward(5)
        if keys[pygame.K_DOWN]:

        '''
        exec(open("test.pybot").read())
        #Game Logic
        all_sprites_list.update()

        #Drawing on Screen
        screen.fill(GREY)
        #Draw The Road
        #pygame.draw.rect(screen, GREY, [40,0, 200,300])
        #Draw Line painting on the road
        #pygame.draw.line(screen, WHITE, [140,0],[140,300],5)

        #Now let's draw all the sprites in one go. (For now we only have 1 sprite!)
        all_sprites_list.draw(screen)

        #Refresh Screen
        pygame.display.flip()

        #Number of frames per second e.g. 60
        clock.tick(60)
pygame.quit()

在这行^{cd2>}它打开一个包含以下内容的文件:^{{cd1>}并执行它。我希望它执行一次脚本(除非脚本包含循环)。但是,如果我在while循环中运行,它就会反复循环。我不能把它放在上面或下面,因为循环会更新屏幕。pygame在屏幕上显示文件时是否有执行文件,比如使用子进程或其他什么?


Tags: theimport脚本eventifbotkeysall