Tron街机游戏(Python,tkinter) - 碰撞检测

时间:2017-04-20 00:07:45

标签: python tkinter collision detection

我正在尝试使用tkinter在Python中编写Tron街机游戏。 我在碰撞检测方面遇到了一些问题。我的问题是,我不确定如何跟踪尾巴,玩家正在绘制他们移动的地方。 我的第一个想法是每次创建一个新矩形时创建一个新列表。然后在每次移动时检查这些列表与玩家位置的比较。虽然我不确定如何编写循环,但仍会检查新列表。 然后我发现可以将列表添加到另一个列表中。所以我想我可以制作一个包含矩形的所有坐标的列表,但它似乎只是在它们移动时覆盖旧坐标,而不是将其添加到它,即使我使用追加。 我正试图在功能移动中做这些事情。

这就是我的代码目前的样子,没有我刚才描述的先前尝试的任何代码。如果您需要任何其他信息,请告诉我。

#   Imports
from tkinter import*
import datetime
import math
from time import sleep
t = datetime.datetime.now

#   Variables
canvasHeight = 400
canvasWidth = 400

player1Spawn = 75, 200, 80, 205
player2Spawn = 325, 200, 320, 205

x1Move = 5
y1Move = 0
x2Move = -5
y2Move = 0

#   Window and canvas creation
window = Tk()
window.title("Tron")
canvas = Canvas(height = canvasHeight, width = canvasWidth)

canvas.pack()
canvas.focus_set()

#   Object creation
player1 = canvas.create_rectangle(player1Spawn, fill = "blue", outline = "blue")
player2 = canvas.create_rectangle(player2Spawn, fill = "red", outline = "red")

#   Movement and tail creation
def moving():
    global player1
    global player2
    global canvas
    p1Coords = canvas.coords(player1)
    p2Coords = canvas.coords(player2)
    p1CoordList = []
    p2CoordList = []
    p1CoordList.append(p1Coords)
    p2CoordList.append(p2Coords)
    canvas.create_rectangle(p1CoordList, fill = "blue", outline = "blue")
    canvas.create_rectangle(p2CoordList, fill = "red", outline = "red")
    del p1CoordList[0]
    del p2CoordList[0]
    canvas.move(player1, x1Move, y1Move)
    canvas.move(player2, x2Move, y2Move)
    window.after(50, moving)

def moveVar(event):
    global x1Move
    global y1Move
    global x2Move
    global y2Move

    if event.keysym == "Up":
        x1Move = 0
        y1Move = -5
    elif event.keysym == "Down":
        x1Move = 0
        y1Move = 5
    elif event.keysym == "Right":
        x1Move = 5
        y1Move = 0
    elif event.keysym == "Left":
        x1Move = -5
        y1Move = 0

    if event.keysym == "w":
        x2Move = 0
        y2Move = -5
    elif event.keysym == "s":
        x2Move = 0
        y2Move = 5
    elif event.keysym == "d":
        x2Move = 5
        y2Move = 0
   elif event.keysym == "a":
        x2Move = -5
        y2Move = 0

canvas.bind("<KeyPress>", moveVar)

moving()

0 个答案:

没有答案