我已经制作了一个程序,通过按下键盘来移动 turtle 的位置,但是有没有办法让它以较小的像素增量移动?

还有,有没有可能让 turtle 上下移动,而不是只左右移动?

from turtle import Screen, Turtle
TURTLE_SIZE = 200

# functions
def go_left():
    t.direction = 'left'

def go_right():
    t.direction = 'right'

screen = Screen()
screen.setup(1152,648)
screen.tracer(0)

# player
t = Turtle()
t.shape("circle")
t.speed("slowest")
t.color("blue")
t.penup()
t.setx(338)
t.sety(0)
t.direction = 'stop'

# Keyboard
screen.onkeypress(go_left, 'Left')
screen.onkeypress(go_right, 'Right')
screen.listen()

while True:
    x = t.xcor()

    if t.direction == 'left':
        if x > TURTLE_SIZE - 576:
            x -= 3
            t.setx(x)
        else:
            t.direction = 'stop'
    elif t.direction == 'right':
        if x < 576 - TURTLE_SIZE:
            x += 3
            t.setx(x)
        else:
            t.direction = 'stop'

    screen.update()

screen.mainloop()

推荐答案

你的圆点移动如此之快的原因是因为你的while True圈.

我将大部分逻辑移到了go_个函数中,并为您添加了一个上下函数.

from turtle import Screen, Turtle
TURTLE_SIZE = 200

def go_left():
    x = t.xcor()
    if x > TURTLE_SIZE - 576:
        x -= 3
        t.setx(x)
    screen.update()

def go_right():
    x = t.xcor()
    if x < 576 - TURTLE_SIZE:
        x += 3
        t.setx(x)
    screen.update()

def go_up():  # added this function
    y = t.ycor()
    if y < 576 - TURTLE_SIZE:
        y += 3
        t.sety(y)
    screen.update()

def go_down():  # added this function
    y = t.ycor()
    if y < 576 - TURTLE_SIZE:
        y -= 3
        t.sety(y)
    screen.update()

screen = Screen()
screen.setup(1152,648)
screen.tracer(0)

t = Turtle()
t.shape("circle")
t.speed("slowest")
t.color("blue")
t.penup()
t.setx(338)
t.sety(0)
screen.update()

# Keyboard
screen.onkeypress(go_left, 'Left')
screen.onkeypress(go_down, 'Down')   # added this listener
screen.onkeypress(go_up, 'Up')       # added this listner
screen.onkeypress(go_right, 'Right')
screen.listen()
screen.mainloop()

Python相关问答推荐

如何使用stride_tricks.as_strided逆转NumPy数组

如何处理嵌套的SON?

将DF中的名称与另一DF拆分并匹配并返回匹配的公司

ModuleNotFound错误:没有名为Crypto Windows 11、Python 3.11.6的模块

删除最后一个pip安装的包

NP.round解算数据后NP.unique

基于字符串匹配条件合并两个帧

Python虚拟环境的轻量级使用

如何将多进程池声明为变量并将其导入到另一个Python文件

如何在Polars中从列表中的所有 struct 中 Select 字段?

driver. find_element无法通过class_name找到元素'""

创建可序列化数据模型的最佳方法

重置PD帧中的值

如何找出Pandas 图中的连续空值(NaN)?

为什么'if x is None:pass'比'x is None'单独使用更快?

当单元测试失败时,是否有一个惯例会抛出许多类似的错误消息?

将链中的矩阵乘法应用于多组值

如何重新组织我的Pandas DataFrame,使列名成为列值?

Python协议不兼容警告

在一个数据帧中,我如何才能发现每个行号是否出现在一列列表中?