2024-05-17 01:14:05 发布
网友
我在做一个游戏,玩家可以在屏幕底部的一条线上移动。在
此时要移动它,用户反复点击箭头键,但我想让它在按下键时连续移动。在
我怎么解决这个问题?在
您需要使用键的get_pressed()功能,Link。在
import pygame pygame.init() # Variables black_background = (0, 0, 0) screen = pygame.display.set_mode((1280, 960)) running = True turtle_image = pygame.image.load('location/to/turtle/image.png') turtle_rect = turtle_image.get_rect() # Using rect allows for collisions to be checked later # Set spawn position turtle_rect.x = 60 turtle_rect.y = 60 while running: keys = pygame.key.get_pressed() #keys pressed for event in pygame.event.get(): if event.type == pygame.QUIT: running = False if keys[pygame.K_LEFT]: turtle_rect.x -= 1 if keys[pygame.K_RIGHT]: turtle_rect.x += 1 screen.fill(black_background) screen.blit(turtle_image, turtle_rect)
请记住,这只是一个基本的布局,您需要进一步了解如何使用其他关键点来完成碰撞和/或移动。Intro Here.
下面是我基于海龟的解决方案。它使用一个计时器使海龟在窗口底部移动,但在没有任何事情发生时让计时器过期(turtle已在边缘停止),并根据需要重新启动计时器:
from turtle import Turtle, Screen CURSOR_SIZE = 20 def move(new_direction=False): global direction momentum = direction is not None # we're moving automatically if new_direction: direction = new_direction if direction == 'right' and turtle.xcor() < width / 2 - CURSOR_SIZE: turtle.forward(1) elif direction == 'left' and turtle.xcor() > CURSOR_SIZE - width / 2: turtle.backward(1) else: direction = None if ((not new_direction) and direction) or (new_direction and not momentum): screen.ontimer(move, 10) screen = Screen() width, height = screen.window_width(), screen.window_height() turtle = Turtle('turtle', visible=False) turtle.speed('fastest') turtle.penup() turtle.sety(CURSOR_SIZE - height / 2) turtle.tilt(90) turtle.showturtle() direction = None screen.onkeypress(lambda: move('left'), "Left") screen.onkeypress(lambda: move('right'), "Right") screen.listen() screen.mainloop()
使用左右箭头控制海龟的方向。在
您需要使用键的get_pressed()功能,Link。在
请记住,这只是一个基本的布局,您需要进一步了解如何使用其他关键点来完成碰撞和/或移动。Intro Here.
下面是我基于海龟的解决方案。它使用一个计时器使海龟在窗口底部移动,但在没有任何事情发生时让计时器过期(turtle已在边缘停止),并根据需要重新启动计时器:
使用左右箭头控制海龟的方向。在
相关问题 更多 >
编程相关推荐