Friday 15 February 2013

python - One of functions in class not working? -



python - One of functions in class not working? -

i know why variables not changing in def moving(self) method? missing something? in object snake should move (up, down, left, right) depending on dir_x, dir_y.

the code:

from tkinter import * 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): homecoming "<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 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()

you create method moving, never phone call - it's never executed. want phone call in in repeat. this:

def repeat(): s1 = snake(xs, xy, dx, dy, cx, cy) s1.moving () print("tik", dx, dy) print (s1) root.after(500, repeat)

but warned variables alter within s1, , not outside - if you're creating every phone call of repeat, you'll discard info s1.x (and snake won't move)

python class tkinter

No comments:

Post a Comment