【发布时间】:2023-01-10 21:55:23
【问题描述】:
我需要让正方形上下移动。从我的以下代码中,方块左右移动,但我需要确保它也上下移动。
import pygame, sys
from pygame.locals import QUIT
def draw_rectangle(surface, rectangle):
pygame.draw.rect(surface, (0, 255, 0), rectangle)
def main():
pygame.init()
#Intalise
DISPLAYSURF = pygame.display.set_mode((400, 300))
pygame.display.set_caption('Rectangles and Squares')
game_clock = pygame.time.Clock()
#Variables
x_position = 100
#Game Loop
running = True
while running:
#Update Section
#Update delta_time
delta_time = game_clock.tick(60)/100
#Handle events
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
#Process keyboard inputs
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
x_position -= 10 * delta_time
if keys[pygame.K_RIGHT]:
x_position += 10 * delta_time
#Draw Section
DISPLAYSURF.fill((128, 128, 128))
draw_rectangle(DISPLAYSURF, pygame.Rect(x_position, 100, 50, 50))
pygame.display.flip()
if __name__ == "__main__":
main()
【问题讨论】:
-
提示:代码中写着
pygame.Rect(x_position, 100, 50, 50),你认为这些数字是什么意思?特别是,100是什么意思?请注意此代码如何使用x_position变量,并且代码的另一部分变化这个变量?因为那是允许左右移动的原因……你认为什么可能允许上下移动? -
你必须改变 y 坐标而不是 x 坐标