试图使一条线沿着随机路径移动

2024-04-25 11:56:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在Python中使一行跟随随机路径。我必须用SimpleGUI来做这件事。到目前为止,我已经做了足够多的工作,使该行遵循随机路径,但是在for循环之后,代码重新启动。我对SimpleGUI不太熟悉,因此我确信重新启动代码有一个很好的理由,但我不知道如何修复它。我已经提供了下面的code,提前感谢

import simplegui
import random

def draw_handler(canvas):
    x=300 #Should be the center; this is the center of 600x600
    y=300
    for i in range(1000):
        direction=random.randint(1,4) #1=up,2=left,3=down,4=right
        if (direction==1):
            canvas.draw_line([x,y],[x,y-3],3,"Black")
            y=y-3
        if (direction==2):
            canvas.draw_line([x,y],[x-3,y],3,"Black")
            x=x-3
        if (direction==3):
            canvas.draw_line([x,y],[x,y+3],3,"Black")
            y=y+3
        if (direction==4):
            canvas.draw_line([x,y],[x+3,y],3,"Black")
            x=x+3


frame = simplegui.create_frame('Testing', 600, 600)
frame.set_canvas_background("White")
frame.set_draw_handler(draw_handler)
frame.start() 

Tags: 代码import路径foriflinerandomframe
1条回答
网友
1楼 · 发布于 2024-04-25 11:56:13

每秒调用drawing handler function60次,以完全重新绘制画布。 我在SimpleGUICS2Pygame的文档中明确了这一点,它在标准Python实现中重新实现了SimpleGUI

您需要累积路径,在每次调用绘图处理程序函数时添加一个点,然后绘制所有路径。见此example

#!/usr/bin/env python3
"""
Random path
"""
import random

try:
    import simplegui
except ImportError:
    # SimpleGUICS2Pygame: https://simpleguics2pygame.readthedocs.io/
    import SimpleGUICS2Pygame.simpleguics2pygame as simplegui


def main():
    width = 600
    height = 600

    points = [(width // 2, height // 2)]

    def draw_handler(canvas):
        last_x, last_y = points[-1]
        new_x = last_x
        new_y = last_y
        direction = random.choice((-1, 1))
        if random.randrange(2) == 0:
            new_y += direction * 3
        else:
            new_x += direction * 3

        points.append((new_x, new_y))

        a = points[0]
        for b in points[1:]:
            canvas.draw_line(a, b, 1, 'Black')
            a = b

    frame = simplegui.create_frame('Random path', width, height)
    frame.set_canvas_background('White')
    frame.set_draw_handler(draw_handler)
    frame.start()


if __name__ == '__main__':
    main()

相关问题 更多 >