Python Pygame在执行循环时运行命令
我有一个pygame脚本,允许我移动精灵(bot),我可以使用这个Python Pygame在执行循环时运行命令,python,pygame,subprocess,Python,Pygame,Subprocess,我有一个pygame脚本,允许我移动精灵(bot),我可以使用这个bot.moveForward(5)运行它 这是我的剧本: 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) PUR
bot.moveForward(5)
运行它
这是我的剧本:
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()
在这一行
exec(open(“test.pybot”).read()
中,它打开一个包含以下内容的文件:bot.moveForward(5)
,并执行它。我希望它执行脚本一次(除非脚本包含循环)。但是,如果我在while循环中运行它,它会反复循环。我不能把它放在上面或下面,因为循环会更新屏幕。当pygame在屏幕上显示文件时,是否仍然可以执行该文件,例如使用子进程或其他方法?您可以使用True/False变量吗?执行后,您会更改它的值。@MaLiN2223如果我运行完整代码,它会将其全部移动,并继续循环,将其写入屏幕,以便在脚本结束之前不会显示任何内容。顺便说一句,我正在制作类似robocode的东西:我希望我有足够的代表获得赏金