为什么Blue Square在Python Pygame库中无限期地移动
我正在学习Python,并尝试使用Pygame库制作蛇游戏。我制作了一个矩形,该矩形使用键的按压移动,但没有移动一个块,而是移动到块的末端。 每当我按任何方向向上,向左,向右还是向下,而不是移动1个盒子大小,它会移动到另一个方向的末端 有人可以告诉我为什么会发生这种情况。
import pygame
box_size = 50
num_box = 15
color1 = (169, 215, 81)
color2 = (169,250,81)
x = 0
y = 0
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
break
keys = pygame.key.get_pressed()
if keys[pygame.K_RIGHT]:
if x < width - box_size:
x = x + box_size
if keys[pygame.K_LEFT]:
if x > 0:
x = x - box_size
if keys[pygame.K_UP]:
if y > 0:
y = y - box_size
if keys[pygame.K_DOWN]:
if y < height - box_size:
y = y + box_size
print(x,y)
for i in range(0,num_box):
if i %2 == 0:
for j in range(0,num_box):
if j%2 == 0:
pygame.draw.rect(win, color1, (box_size*j, box_size*i, box_size, box_size))
else:
pygame.draw.rect(win, color2, (box_size * j, box_size * i, box_size, box_size))
else:
for k in range(0,num_box):
if k%2 == 0:
pygame.draw.rect(win, color2, (box_size*k, box_size*i, box_size, box_size))
else:
pygame.draw.rect(win, color1, (box_size * k, box_size * i, box_size, box_size))
pygame.draw.rect(win, (0, 0, 250), (x, y, box_size, box_size))
# # rect(surface, color, (left, top, width, height))
pygame.display.update()
pass
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
参见 ) :
使用 每秒控制帧,从而控制游戏速度。方法 对象,以这种方式延迟游戏,循环的每个迭代都会在同一时间段内消耗。例如:
如果要逐步移动对象,则需要使用
keydown
事件,而不是pygame.key.get_pressed()
:请参阅>如何在pygame中输入键盘? /stackoverflow.com/questions/9961563/how-can-i-make-a-sprite-move-move-when-key-is-held-held-down">如何在钥匙降低时做一个精灵的举动 。
返回每个密钥状态的序列。如果按键键,则密钥的状态为
true
,否则false
。使用 评估按钮的当前状态并获得连续移动。键盘事件(请参阅 pygame.event.event 模块仅在状态发生一次关键更改。每次按键时,就会发生
键盘
事件。键
每次释放键时就会发生。使用键盘事件进行单个动作,例如跳跃或产卵子弹或逐步运动。See
pygame.time.Clock.tick()
:Use
pygame.time.Clock
to control the frames per second and thus the game speed. The methodtick()
of apygame.time.Clock
object, delays the game in that way, that every iteration of the loop consumes the same period of time. e.g.:If you want to move the object step by step you need to use
KEYDOWN
event instead ofpygame.key.get_pressed()
:See How to get keyboard input in pygame? and How can I make a sprite move when key is held down.
pygame.key.get_pressed()
returns a sequence with the state of each key. If a key is held down, the state for the key isTrue
, otherwiseFalse
. Usepygame.key.get_pressed()
to evaluate the current state of a button and get continuous movement.The keyboard events (see pygame.event module) occur only once when the state of a key changes. The
KEYDOWN
event occurs once every time a key is pressed.KEYUP
occurs once every time a key is released. Use the keyboard events for a single action like jumping or spawning a bullet or a step-by-step movement.