我想知道为什么我的变量在def moving(self)
方法中没有变化?我错过了什么吗?在此对象中,蛇应该移动(向上,向下,向左,向右),具体取决于dir_x
,dir_y
。
代码:
from tkinter import *
from tkinter import ttk
class Snake(object):
def __init__ (self, x, y, dir_x, dir_y, con_x, con_y):
self.x = x
self.y = y
self.dir_x = dir_x
self.dir_y = dir_y
self.con_x = con_x
self.con_y = con_y
self.snakey = root.create_rectangle((self.x+243, self.y+243, self.x+251, self.y+251), fill = "#000000")
def moving(self):
if self.dir_x == 10:
self.x = self.x + 10
root.coords(self.snakey, self.x, self.y, self.dir_x, self.dir_y, self.con_x, self.con_y)
if self.dir_x == -10:
self.x = self.x - 10
root.coords(self.snakey, self.x, self.y, self.dir_x, self.dir_y, self.con_x, self.con_y)
if self.dir_y == 10:
self.y = self.y + 10
root.coords(self.snakey, self.x, self.y, self.dir_x, self.dir_y, self.con_x, self.con_y)
if self.dir_y == -10:
self.y = self.y - 10
root.coords(self.snakey, self.x, self.y, self.dir_x, self.dir_y, self.con_x, self.con_y)
def __str__ (self):
return "<Snake x:%s y:%s dir_x:%s dir_y:%s con_x:%s con_y:%s>" % (self.x, self.y, self.dir_x, self.dir_y, self.con_x, self.con_y)
def moveup(event):
global dy, dx
dy = 10
dx = 0
def movedown(event):
global dy, dx
dy = -10
dx = 0
def moveleft(event):
global dx, dy
dx = -10
dy = 0
def moveright(event):
global dx, dy
dx = 10
dy = 0
win = Tk()
win.title("Snake")
root = Canvas(win, width = 493, height = 493, background = "white")
root.grid(row = 0, column = 0)
x = -1
d, c = 0, 0
xs, xy, dx, dy, cx, cy = 0, 0, 0, 0, 0, 0
for i in range(2, 492, 10):
root.create_line((i, 1, i, 500), fill = "#BFBFBF")
root.create_line((1, i, 500, i), fill = "#BFBFBF")
root.create_rectangle((2, 2, 493, 493), width = 4)
#S1 = Snake(xs, xy, dx, dy, cx, cy)
def Repeat():
S1 = Snake(xs, xy, dx, dy, cx, cy)
print("Tik", dx, dy)
print (S1)
root.after(500, Repeat)
Repeat()
root.bind("w", moveup)
root.bind("s", movedown)
root.bind("a", moveleft)
root.bind("d", moveright)
root.focus_set()
win.mainloop()
答案 0 :(得分:1)
您创建方法moving
,但从不调用它 - 它永远不会被执行。
你可能想重复打电话。像这样:
def Repeat():
S1 = Snake(xs, xy, dx, dy, cx, cy)
S1.moving ()
print("Tik", dx, dy)
print (S1)
root.after(500, Repeat)
但是请注意,变量只会在S1内部而不是在外部变化 - 如果你在每次调用repeat
时创建它,你就会丢弃像S1.x
这样的数据(所以蛇不会移动)