[Python] How can my player collides with the border of the canvas?

Discussão em 'Python' iniciado por Stack, Dezembro 17, 2024.

  1. Stack

    Stack Membro Participativo

    The Player should collide with the border of the canvas, but I don't know how to do it.

    from tkinter import *
    import time


    the window

    tk = Tk()
    tk.title("Game")
    tk.geometry("500x500")
    tk.wm_attributes("-topmost", 1)
    tk.resizable(0, 0)


    the canvas

    canvas = Canvas(tk, width=500, height=500, bg="#FFD700")
    canvas.pack()
    canvasx = canvas.winfo_width()
    canvasy = canvas.winfo_height()

    player = canvas.create_rectangle(240, 240, 260, 260, fill="blue",
    outline="dark blue")


    the Player class

    class Player:
    def __init__(self, event, canvas):
    def move(event):
    if event.keysym == "Up" or event.keysym == "w":
    canvas.move(1, 0, -5)
    elif event.keysym == "Down" or event.keysym == "s":
    canvas.move(1, 0, 5)
    elif event.keysym == "Right" or event.keysym == "d":
    canvas.move(1, 5, 0)
    else:
    canvas.move(1, -5, 0)


    what should I write in this function?

    def hit_border():
    pass

    canvas.bind_all("<KeyPress-Up>", move)
    canvas.bind_all("<KeyPress-w>", move)
    canvas.bind_all("<KeyPress-Down>", move)
    canvas.bind_all("<KeyPress-s>", move)
    canvas.bind_all("<KeyPress-Right>", move)
    canvas.bind_all("<KeyPress-d>", move)
    canvas.bind_all("<KeyPress-Left>", move)
    canvas.bind_all("<KeyPress-a>", move)


    here is the loop that makes the everything work

    while True:
    player = Player(canvas, canvas)
    tk.update()
    time.sleep(0.001)

    Continue reading...

Compartilhe esta Página