【问题标题】:Pygame window freezing with shell input使用 shell 输入冻结 Pygame 窗口
【发布时间】:2015-03-24 15:43:41
【问题描述】:

所以,我有一个由 shell 输入控制的游戏。我遇到的问题是,每当我单击 Pygame 窗口时,它都会停止响应。一旦我输入更多的 shell 输入,它就会开始响应,但这仍然是我宁愿不发生的事情。游戏的运作方式,让您可以尝试一下,您只需输入x += (a number)y += (a number),它就会改变您的玩家位置。关于如何防止冻结的任何想法?我尝试使用线程而不是将输入放在while 循环中,但后来我无法修改函数中的变量。

import pygame

pygame.init()

display_width = 1366
display_height = 768

gameDisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption('A game for teaching python')

black = (0,0,0)
white = (255,255,255)

clock = pygame.time.Clock()
crashed = False
carImg = pygame.image.load('player.png')
def player(x,y):
    gameDisplay.blit(carImg, (x,y))
x =  (display_width * 0.45)
y = (display_height * 0.8)
x_change = 0
car_speed = 0
while not crashed:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            crashed = True     
    gameDisplay.fill(black)
    player(x,y)
    pygame.display.update()
    clock.tick(60)
    exec(input(">>> "))

pygame.quit()
quit()

【问题讨论】:

标签: python pygame python-3.4


【解决方案1】:

我制作了一款与此极为相似的游戏。我所做的是创建了一个 Player() 类,然后使用线程来制作一个控制台,这样我就可以编辑 Player.x 和 Player.y 属性。例如:

class Player():
    def __init__(self,startx,starty):
        self.x = startx
        self.y = starty

    #Move method is optional, as you can just edit the x and y attributes
    #directly
    def move(self,x=0,y=0):
        self.x += x
        self.y += y

现在,要制作一个好的线程控制台,您需要执行以下操作。

import thread
consoling = False

def threadedConsole():
    global consoling
    consoling = True
    try:
        exec(raw_input(">> "))
    except Exception as error:
        print error
    consoling = False

#Game loop
while True:
    if not consoling: thread.start_new_thread(threadedConsole,())
    #Game stuff

然后你只需在控制台中调用 Player.move 方法。全局变量在线程中不可编辑,但对象可以。顺便说一下乱七八糟的代码,我才 15 岁。

【讨论】:

    【解决方案2】:

    我想到了两种方法: 第一个是使用线程:一个用于 shell,另一个用于 pygame 程序。 第二个是从窗口获取输入,而不是使用 shell。 假设您将一个名为“number”的变量初始化为 0,您可以将此代码修改为您的:

        elif i.type == pygame.KEYDOWN:
            if i.unicode in [str (i) for i in range(10)]:
                number = number * 10 + int (i.unicode)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-07
      • 1970-01-01
      相关资源
      最近更新 更多