Untitled

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


class App:
    def __init__(self, master):
        self.master = master
        self.master.title("Raw Turtle")
        self.canvas = tk.Canvas(master)
        self.canvas.config(width=500, height=500)
        self.canvas.pack(side=tk.LEFT)
        self.screen = turtle.TurtleScreen(self.canvas)
        self.screen.bgcolor("#f9f9f9")
        self.my_lovely_turtle = turtle.RawTurtle(self.screen, shape="turtle")
        self.my_lovely_turtle.color("red")
        self.my_lovely_turtle.speed(500)
        self.turtle_pos = 'down'
        self.master.bind('<w>', self.keyboard_bind_w)
        self.master.bind('<a>', self.keyboard_bind_a)
        self.master.bind('<d>', self.keyboard_bind_d)
        self.master.bind('<space>', self.keyboard_bind_space)
        self.master.bind('<q>', self.keyboard_bind_q)
        self.label = tk.Label(self.master, text='x: 0.0; y: 0.0;')
        self.label.pack(side=tk.TOP)

    def get_turtle_position(self):
        pos = self.my_lovely_turtle.position()
        return pos

    def keyboard_bind_q(self, _):
        self.my_lovely_turtle.clear()

    def keyboard_bind_space(self, _):
        if self.turtle_pos == 'down':
            self.my_lovely_turtle.penup()
            self.turtle_pos = 'up'
        else:
            self.my_lovely_turtle.pendown()
            self.turtle_pos = 'down'

    def check_pos(self):
        pos = self.get_turtle_position()
        if pos[0] > 250:
            self.my_lovely_turtle.up()
            self.my_lovely_turtle.setx(-250)
            self.my_lovely_turtle.down()
        if pos[0] < -250:
            self.my_lovely_turtle.up()
            self.my_lovely_turtle.setx(250)
            self.my_lovely_turtle.down()
        if pos[1] > 250:
            self.my_lovely_turtle.up()
            self.my_lovely_turtle.sety(-250)
            self.my_lovely_turtle.down()
        if pos[1] < -250:
            self.my_lovely_turtle.up()
            self.my_lovely_turtle.sety(250)
            self.my_lovely_turtle.down()

    def keyboard_bind_w(self, _):
        self.my_lovely_turtle.forward(10)
        pos = [*self.get_turtle_position()]
        pos[0] = round(pos[0] * 10) / 10
        pos[1] = round(pos[1] * 10) / 10
        self.label.config(text='x: {pos[0]}; y: {pos[1]};'.format(pos=pos))
        self.check_pos()

    def keyboard_bind_a(self, _):
        self.my_lovely_turtle.left(45)

    def keyboard_bind_d(self, _):
        self.my_lovely_turtle.right(45)


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