Untitled

mail@pastecode.io avatar
unknown
python
2 years ago
2.4 kB
2
Indexable
Never
import turtle
import tkinter as tk

step = 10
WIDTH = 500
HEIGHT = 500


class App:
    def __init__(self, master):
        self.master = master
        self.master.title("Raw Turtle")
        self.canvas = tk.Canvas(master)
        self.canvas.config(width=HEIGHT, height=HEIGHT)
        self.canvas.pack(side=tk.BOTTOM)
        self.screen = turtle.TurtleScreen(self.canvas)
        self.screen.bgcolor("cyan")
        self.input = tk.Entry(self.master)
        self.input.pack(side=tk.TOP)
        self.my_turtle = turtle.RawTurtle(self.screen)
        self.my_turtle.color("green")
        self.is_fly = False
        self.master.bind('<Control-f>', self.do_figure)
        self.master.bind('<w>', self.turtle_forward)
        self.master.bind('<a>', self.turtle_left)
        self.master.bind('<d>', self.turtle_right)
        self.master.bind('<space>', self.fly)

    def fly(self, _):
        self.is_fly = not self.is_fly
        self.my_turtle.up() if self.is_fly else self.my_turtle.down()

    def validate_position(self):
        self.my_turtle.up()
        if self.my_turtle.position()[0] + step > WIDTH/2:
            self.my_turtle.speed(WIDTH)
            self.my_turtle.setx(-WIDTH/2)
        elif self.my_turtle.position()[0] - step < -WIDTH/2:
            self.my_turtle.speed(WIDTH)
            self.my_turtle.setx(WIDTH/2)
        elif self.my_turtle.position()[1] + step > HEIGHT/2:
            self.my_turtle.speed(HEIGHT)
            self.my_turtle.sety(-HEIGHT/2)
        elif self.my_turtle.position()[1] - step < -HEIGHT/2:
            self.my_turtle.speed(HEIGHT)
            self.my_turtle.sety(HEIGHT/2)
        self.my_turtle.down()

    def turtle_forward(self, _):
        self.validate_position()
        self.my_turtle.forward(step)

    def turtle_left(self, _):
        self.my_turtle.left(15)

    def turtle_right(self, _):
        self.my_turtle.right(15)

    def do_figure(self, _):
        angles = int(self.input.get()) if self.input.get() else 4
        self.my_turtle.speed(360/angles/10)
        for _ in range(angles):
            self.my_turtle.forward(360/angles)
            self.my_turtle.left(360/angles)
        self.my_turtle.color('black')


if __name__ == '__main__':
    root = tk.Tk()
    app = App(master=root)
    root.mainloop()