gpt4 book ai didi

python - Pygame 通过键盘输入移动形状

转载 作者:行者123 更新时间:2023-12-01 05:15:12 25 4
gpt4 key购买 nike

创建了第一个 pygame 程序来在屏幕上移动矩形。无法弄清楚为什么形状实际上没有移动。我之前用一个简单的方法就可以工作

  shape = shape.move(speed)

但现在使用键盘输入时,形状不会移动。我使用了一些打印语句来确保函数 checkKeys 正在渲染我的按键(以及它们所做的速度变化),而且确实如此。然而形状仍然没有移动。

import sys, pygame
pygame.init()

size = width, height = 320, 240
black = (0, 0, 0)
red = (255, 0, 0)
pygame.display.set_caption("Object Move Test")
clock = pygame.time.Clock()

def main():
screen = pygame.display.set_mode(size)
shape = pygame.draw.rect(screen, (255, 0, 0), (200, 100, 10, 10,))
ballrect = pygame.Surface((10,10), 0, shape)

def checkKeys(speedY, speedX, shape):
key = pygame.key
pygame.event.pump()
if key.get_pressed()[pygame.K_UP] and speedY < 1:
speedY = speedY - 1
#print 'UP'
if key.get_pressed()[pygame.K_DOWN] and speedY > -1:
speedY = speedY - 1
#print 'DOWN'
if key.get_pressed()[pygame.K_LEFT] and speedX > -1:
speedX = speedX - 1
#print 'LEFT'
if key.get_pressed()[pygame.K_RIGHT] and speedX < 1:
speedX = speedX + 1
#print speedX
speed = [speedX, speedY]
#print speed
moveShape(speed, shape)

def moveShape(speed, shape):
print speed
shape = shape.move(speed)
if shape.left < 0 or shape.right > width:
speed[0] = -speed[0]
if shape.top < 0 or shape.bottom > height:
speed[1] = -speed[1]

while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()

speedX, speedY = (0, )*2
speed = [speedX, speedY]
screen.fill((255,255,255))
clock.tick(20)
checkKeys(speedX, speedY, shape)

screen.blit(ballrect, shape)
pygame.display.flip()

if __name__ == '__main__':
main()

最佳答案

我对pygame不太熟悉,所以这只是一个猜测。然而,对我来说最有问题的是这一行(在 moveShape 的定义中):

shape = shape.move(speed)

这是一个问题的原因是 shapemoveShape 中局部变量的名称,但我猜测您打算通过 equals 赋值来更新非局部 shape 对象(在 main() 定义顶部声明的对象。当您调用 shape.move(speed) 时,返回值是一个新的 pygame Rect 对象,它被分配名称 shape。但此分配发生在 moveShape 内部> 函数,因此更新在该范围之外不可见。

看起来您可以用“就地”版本 ( http://www.pygame.org/docs/ref/rect.html#pygame.Rect.move_ip ) 替换这一行,该版本将更改对象而不返回新对象:

shape.move_ip(speed)

也许这对你有用?

关于python - Pygame 通过键盘输入移动形状,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23370104/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com