我有以下设置:我有一个可以射箭的射手,它总是类箭头的新实例,我有一个类blackMonster的实例。我的问题是,是否有可能检测我的一个箭头实例是否与这个黑色怪物实例发生碰撞?什么时候有可能呢?我过去经常这么想,但我找不到解决方案而且真的很令人沮丧。这是我的代码......请不要过于刻板地判断我的工作。
from Tkinter import *
from PIL import ImageTk, Image
class App(Frame):
def __init__(self, master=None):
Frame.__init__(self, master, height=400, width=400)
self.master = master
self.master.bind('<Shift_L>', self.createArrow)
self.charImg = ImageTk.PhotoImage(Image.open("./Archer.gif"))
self.charLabel = Label(self, image = self.charImg)
self.charLabel.pack()
self.down = False
self.right = False
self.left = False
self.up = False
self.x_coord = 200
self.y_coord = 200
self.pack_propagate(0)
self.pack()
self.monster = blackMonster(self)
self.monster.createMonster(self.monster, 300, 300)
def createArrow(self, event):
self.arrow = Arrow(self)
self.arrow.moveArrow(self.arrow, self.x_coord, self.y_coord + 15)
def moveableImage(self):
self.charLabel.place(y=self.y_coord, x=self.x_coord)
def keyPressed(self, event):
if event.keysym == 'Down':
self.down = True
elif event.keysym == 'Right':
self.right = True
elif event.keysym == 'Left':
self.left = True
elif event.keysym == 'Up':
self.up = True
def keyReleased(self, event):
if event.keysym == 'Down':
self.down = False
elif event.keysym == 'Right':
self.right = False
elif event.keysym == 'Left':
self.left = False
elif event.keysym == 'Up':
self.up = False
def task(self):
if self.down and self.y_coord < 360:
self.y_coord += 10
elif self.right and self.x_coord < 370:
self.x_coord += 10
elif self.left and self.x_coord > 10:
self.x_coord -= 10
elif self.up and self.y_coord > 10:
self.y_coord -= 10
root.after(20,self.task)
self.moveableImage()
class Arrow(Frame):
def __init__(self, master):
Frame.__init__(self, master)
self.arrowImage = ImageTk.PhotoImage(Image.open("./arrow.gif"))
Label(self, image=self.arrowImage).pack()
self.damage = 20
def moveArrow(self, arrow, xCoord, yCoord):
arrow.place_forget()
arrow.place(x = xCoord, y = yCoord)
self.after(10, self.moveArrow, arrow, xCoord+5, yCoord)
class blackMonster(Frame):
def __init__(self, master):
Frame.__init__(self, master)
self.monsterImage = ImageTk.PhotoImage(Image.open("./monster.gif"))
Label(self, image=self.monsterImage).pack()
self.health = 100
def createMonster(self, monster, x_Coord, y_Coord):
monster.place(x = x_Coord, y = y_Coord)
root = Tk()
root.title("Frametitel")
app = App(master=root)
root.bind_all('<Key>', app.keyPressed)
root.bind_all('<KeyRelease>', app.keyReleased)
root.after(20, app.task)
app.mainloop()
答案 0 :(得分:3)
你使用标签和地方来代表怪物和箭头吗?如果您使用画布而不是标签,编码会更容易。画布具有轻松获取已绘制对象坐标的方法。那就是它只不过是一个小数学。你得到箭头的当前坐标,你得到怪物的坐标,然后检查箭头尖端的坐标是否在怪物占据的空间内。您可以使用bbox方法获取ana对象的坐标。