繁体   English   中英

如何在不多次按键的情况下让乌龟连续移动?

[英]How to make turtle move continuously without multiple key presses?

我正在制作一款游戏,玩家可以在屏幕底部的一条线上移动。

此时要移动它,用户反复敲击箭头键,但我想让它在按下键时连续移动。

我该如何解决?

您将要使用 Linkget_pressed()函数。

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)

请记住,这只是一个基本布局,您将不得不多读一些关于如何与其他键完成碰撞和/或移动的信息。 在这里介绍。

以下是我基于乌龟的解决方案。 它使用计时器使乌龟在窗口底部移动,但在无任何事件发生时(乌龟已在边缘停止)使计时器到期,并根据需要重新启动计时器:

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()

使用左右箭头控制乌龟的方向。

使用函数: onkeypress

这是一个例子, onkeypress是一个高阶函数:

def move_forward():
    t.forward(10)

screen.onkeypress(key='w', fun= move_forward)

您可以使用onkeypress(fun, key=None)

而不是使用 onkey( onkey()onkeyrelease() 这两个仅在释放键时注册输入。

onkeypress(fun, key=None)在按下键时注册它。

这是 Turtle 文档中的链接

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM