坚持tkinter帆布游戏的一个关键功能

时间:2016-02-25 20:29:04

标签: python canvas tkinter

这是我的代码我需要帮助关闭位置识别功能 基本上是游戏的主要机制,告诉你何时可移动 character(man)是一个坏人物(坏人); 我的问题是如何做if语句告诉我:   如果男人不好的话

这是我的代码,让男人四处走动并产生不良

P.S不要用勺子喂食:

from tkinter import *

import random


def up(event):
    c.move(man, 0, -150)
def down(event):
    c.move(man, 0, 150)
def right(event):
    c.move(man, 150, 0)
def left(event):
    c.move(man, -150, 0)

wd = Tk()
wd.bind('<Up>', up)
wd.bind('<Down>', down)
wd.bind('<Right>', right)
wd.bind('<Left>', left)

c = Canvas(wd, height=475, width=450, bg='white', cursor='plus')#room at bottom
c.pack()

plc = random.randint(1,9)
if plc == 1:
    bad = c.create_oval(50,50,100,100,fill='blue')
if plc == 2:
    bad = c.create_oval(200,50,250,100,fill='blue')
if plc == 3:
    bad = c.create_oval(350,50,400,100,fill='blue')
if plc == 4:
    bad = c.create_oval(50,200,100,250,fill='blue')
if plc == 5:
    bad = c.create_oval(200,200,250,250,fill='blue')
if plc == 6:
    bad = c.create_oval(350,200,400,250,fill='blue')
if plc == 7:
    bad = c.create_oval(50,350,100,400,fill='blue')
if plc == 8:
    bad = c.create_oval(200,350,250,400,fill='blue')
if plc == 9:
    bad = c.create_oval(350,350,400,400,fill='blue')

sq1 = c.create_rectangle(0,0,150,150,fill='white')
sq2 = c.create_rectangle(0,150,150,300,fill='white')
sq3 = c.create_rectangle(0,300,150,450,fill='white')
sq4 = c.create_rectangle(150,0,300,150,fill='white')
sq5 = c.create_rectangle(150,150,300,300,fill='white')
sq6 = c.create_rectangle(150,300,300,450,fill='white')
sq7 = c.create_rectangle(300,0,450,150,fill='white')
sq8 = c.create_rectangle(300,150,450,300,fill='white')
sq9 = c.create_rectangle(300,300,450,450,fill='white')

man = c.create_oval(175,175,275,275,fill='red')#25 in each way

catch()

wd.mainloop()

1 个答案:

答案 0 :(得分:1)

来自Methods on Canvas Widget

您可以将.find_encloseddef is_intercecting(canvas,tag1,tag2): return tag1 in canvas.find_enclosed(*canvas.bbox(tag2)) 结合使用来检查两个对象是否相交:

def is_man_touching_bad():
    return bad in c.find_enclosed(*c.bbox(man))

或具体针对您的情况:

catch

然后每次调用其中一个移动功能时,您可以使用它来检查它们是否发生碰撞。

(我猜这会在您调用的is_man_touching_bad函数中使用,但不会在您提供的代码中定义)

编辑:根据请求,这是man的示例使用,这会在bad移动时将def catch(): if is_man_touching_bad(): c.itemconfigure(man,fill="black") else: c.itemconfigure(man,fill="red") 设为黑色:

def up(event):
    c.move(man, 0, -150)
    catch()
def down(event):
    c.move(man, 0, 150)
    catch()
def right(event):
    c.move(man, 150, 0)
    catch()
def left(event):
    c.move(man, -150, 0)
    catch()

请务必在每次更新位置时调用此方法:

 string[] files = Directory.GetFiles(directory);
 foreach (Datarow row in dataTable.Rows)
   for (int i=0; i<files.Length; i++)
      if (row[0].equals(files[i]) {
          files[i].delete();
          break;
       }