|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
import tkinter as tk
import random as rd
import time
class Food:
def __init__(self, map_x_y):
falg = rd.choice([1, 2])
self.x1 = rd.choice([x for x in range(20, 481, 20)])
self.y1 = rd.choice([y for y in range(20, 481, 20)])
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([1, 2])
self.x1 = rd.choice([x for x in range(20, 481, 20)])
self.y1 = rd.choice([y for y in range(20, 481, 20)])
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 = [0, 500]
LEAGL_Y = [0, 500]
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窗口不显示出来,这是为什么呢 |
|