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

时间:2018-02-07 16:39:53

标签: python turtle-graphics

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

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

我该如何解决这个问题?

2 个答案:

答案 0 :(得分:0)

您需要使用Link get_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)

请记住,这只是一个基本布局,您需要多阅读一下如何使用其他键完成碰撞和/或移动。 Intro Here.

答案 1 :(得分:0)

以下是我的基于龟的解决方案。它使用一个计时器来保持乌龟在窗口底部移动,但是当没有任何事情发生时(乌龟在边缘停止)让计时器到期并根据需要重新启动计时器:

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

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