tkinter 贪吃蛇游戏
import tkinter as tkimport random as rd
import time
class Food:
def __init__(self, map_x_y):
falg = rd.choice()
self.x1 = rd.choice()
self.y1 = rd.choice()
self.x2 = self.x1
self.y2 = self.y1
if falg == 1:
self.x2 += 10
else:
self.y2 += 10
map_x_y.create_line(self.x1, self.y1, self.x2, self.y2, fill='yellow', width=10)
class Snake:
def __init__(self,map_x_y):
falg = rd.choice()
self.x1 = rd.choice()
self.y1 = rd.choice()
self.x2 = self.x1
self.y2 = self.y1
if falg == 1:
self.x2 += 60
else:
self.y2 += 60
map_x_y.create_line(self.x1, self.y1, self.x2, self.y2, fill='yellow', width=10)
def default_move(self, direction, map_x_y):
if direction == 'x':
map_x_y.create_line(self.x1, self.y1-10, self.x2, self.y2+10, fill='yellow', width=10)
def move_w(self):
pass
def move_a(self):
pass
def move_s(self):
pass
def move_d(self):
pass
class Game:
LEAGL_X =
LEAGL_Y =
def __init__(self):
game_win = tk.Toplevel()
game_win.title('GAME')
game_win.geometry('500x500')
game_map = tk.Canvas(game_win, bg='red', width=500, height=500)
snake = Snake(game_map) # 生成蛇
food = Food(game_map)# 生存食物
game_map.focus_set()
game_map.bind(sequence='<w>', func=snake.move_w)
game_map.bind(sequence='<a>', func=snake.move_a)
game_map.bind(sequence='<d>', func=snake.move_d)
game_map.bind(sequence='<s>', func=snake.move_s)
game_map.pack()
while True:
print(1)
if snake.x1 == snake.x2:
snake.default_move('x', game_map)
else:
snake.default_move('y', game_map)
class Window:
def __init__(self):
root = tk.Tk()
root.title('GAME')
root.geometry('300x300')
tk.Button(root,text='PLAY',command=Game).pack()
root.mainloop()
window = Window()
由于我也是现学现做,依葫芦画瓢,以上代码还有很多没有完善了地方,但是出现了一个致命的问题,Toplevel窗口不显示出来,这是为什么呢 game_win = tk.Toplevel(root)# tk.Toplevel()要这么用,要把主窗口参数传入 笨鸟学飞 发表于 2020-12-2 20:22
game_win = tk.Toplevel(root)# tk.Toplevel()要这么用,要把主窗口参数传入
还是显示不出来,主窗口一直处于未响应状态 import tkinter as tk
root = tk.Tk()
root.title('GAME')
root.geometry('300x300')
game_win = tk.Toplevel(root)
tk.Button(root,text='PLAY').pack()
root.mainloop()
完全没问题啊? 笨鸟学飞 发表于 2020-12-2 20:32
完全没问题啊?
你这样的确没有问题,我的想法实在Canvas上面动态的刷新画面,但是Canvas的窗口根本就不显示,除非我把while循环去掉
页:
[1]