我的播放器如何与画布边框发生碰撞?

问题描述 投票:0回答:1

播放器应该与画布的边框碰撞,但我不知道该怎么做。

from tkinter import *
import time

窗户

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

画布

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")

玩家类别

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)

我应该在这个函数中写什么?

        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)

这是使一切正常工作的循环

while True:
    player = Player(canvas, canvas)
    tk.update()
    time.sleep(0.001)
python tkinter
1个回答
0
投票

您不应在脚本中添加其他函数,而应在 init 函数中添加 if 语句,例如 if 玩家的坐标 <500: for the right side and >0: 表示左侧。希望这有效!

© www.soinside.com 2019 - 2024. All rights reserved.