Alles funktioniert aber ich will das Event, dass startet wenn man die Leertaste drückt durch eine After Funktion ersetzen aber wenn ich schreibe
Code: Alles auswählen
self.root,after(1000, self.move)
Code: Alles auswählen
from tkinter import *
# Mir ist klar dass ein Sternchen-import nicht gut ist
class Controller(object):
def __init__(self, parent):
# class variables
self.parent = parent
# events
self.parent.bind("<w>", self.up)
self.parent.bind("<s>", self.down)
self.parent.bind("<a>", self.left)
self.parent.bind("<d>", self.right)
# direction var
# 0
# 3 X 1
# 2
#
self.direction = " "
def up(self, event):
self.direction = "up"
self.get_direction()
def right(self, event):
self.direction = "right"
self.get_direction()
def down(self, event):
self.direction = "down"
self.get_direction()
def left(self, event):
self.direction = "left"
self.get_direction()
def get_direction(self):
print(self.direction)
return self.direction
class Field(object):
def __init__(self, parent, field_len):
# class Variables
self.parent = parent
self.field_len = field_len
self.cont = Controller(self.parent)
# image
self.alpha = PhotoImage(file="pixel.gif")
# widget list
self.widget_list = []
# logic list, 1 = shown
self.pos = {"x":3, "y":3}
# create list depht of 2
for _ in range(0, self.field_len):
self.widget_list.append([0] * self.field_len)
#assign widgets to each cell of one list
for x in range(0, self.field_len):
for y in range(0, self.field_len):
self.widget_list[x][y] = Label(self.parent, image=self.alpha, bg="grey", width=10, height=10)
self.widget_list[x][y].grid(row=x, column=y, padx=0, pady=0)
self.parent.bind("<space>", self.move)
def move(self, event):
print("move !")
if self.cont.get_direction() == "up": self.pos["x"] -= 1
elif self.cont.get_direction() == "right": self.pos["y"] += 1
elif self.cont.get_direction() == "down": self.pos["x"] += 1
elif self.cont.get_direction() == "left": self.pos["y"] -= 1
else: print("fail")
# get all cells
for x in range(0, self.field_len):
for y in range(0, self.field_len):
# highlight the actual active cell
if self.pos["x"] == x and self.pos["y"] == y:
self.widget_list[x][y].config(bg="gold")
# set the color to defaut
else:
self.widget_list[x][y].config(bg="grey")
class Main(object):
def __init__(self, root, field):
# class variables
self.root = root
# setup window
self.root.title("Snake")
# create game field
self.field = field
self.root.mainloop()
if __name__ == "__main__":
root = Tk()
field = Field(root, 20)
Main(root, field)