用户:L0_0查看:0 回复:0 评论:0 创建时间:2021-03-13T21:13:17
【作品展示】

【作品介绍】
我使用了tkinter模块
【作品源代码】
import random
from tkinter import Tk, Menu, Label, Button, messagebox
root = Tk()
root.title('贪吃蛇')
root.resizable(width=False, height=False)
game_grid = {}
score_text = Label(root, width=133, height=2, anchor='w', text='得分: 0')
score_text.grid(columnspan=18, row=0)
for i in range(324):
b = Button(root, width=6, height=2, relief='flat', bg='white', state='disabled')
b.grid(column=i%18, row=i//18+1)
game_grid[i%18, i//18] = b
score = 0
the_best_score = 0
seth = random.choice([0, 90, 180, 270])
def start_game():
global score
global leaf_x
global leaf_y
global snake_x
global snake_y
global game_grid
for i in range(324):
game_grid[i%18, i//18]['bg'] = 'white'
score = 0
snake_x = [random.randint(0, 17)]
snake_y = [random.randint(0, 17)]
leaf_x = random.randint(0, 17)
leaf_y = random.randint(0, 17)
game_grid[leaf_x, leaf_y]['bg'] = 'green'
game_grid[snake_x[0], snake_y[0]]['bg'] = 'red'
root.after(500, body)
def place_leaf():
global leaf_x
global leaf_y
leaf_x = random.randint(0, 17)
leaf_y = random.randint(0, 17)
def body():
global score
global snake_x
global snake_y
global the_best_score
if seth == 0:
x = snake_x[-1]
x += 1
the_changing = 'x'
snake_x.append(x)
if seth == 90:
y = snake_y[-1]
y -= 1
the_changing = 'y'
snake_y.append(y)
if seth == 180:
x = snake_x[-1]
x -= 1
the_changing = 'x'
snake_x.append(x)
if seth == 270:
y = snake_y[-1]
y += 1
the_changing = 'y'
snake_y.append(y)
for i in range(324):
game_grid[i%18, i//18]['bg'] = 'white'
game_grid[leaf_x, leaf_y]['bg'] = 'green'
for i in range(score + 1):
if the_changing == 'x' or i == 0:
x = snake_x[-1 - i]
if the_changing == 'y' or i == 0:
y = snake_y[-1 - i]
try:
if game_grid[x, y]['bg'] == 'green':
score += 1
score_text['text'] = '得分:' + str(score)
place_leaf()
game_grid[x, y]['bg'] = 'red'
except:
if score > the_best_score:
the_best_score = score
messagebox.showinfo('贪吃蛇', '游戏结束,得分:' + str(score))
return
root.after(500, body)
def show_hint():
messagebox.showinfo('玩法', '按↑、↓、←,→键控制贪吃蛇改变方向,吃到树叶得1分,当贪吃蛇碰到墙壁,游戏就结束了。')
def show_the_best_score():
messagebox.showinfo('历史记录', '最高分:' + str(the_best_score))
menubar = Menu(root)
gamemenu = Menu(menubar, tearoff=0)
gamemenu.add_command(label='新游戏', command=start_game)
gamemenu.add_command(label='玩法', command=show_hint)
gamemenu.add_separator()
gamemenu.add_command(label='历史记录', command=show_the_best_score)
menubar.add_cascade(label='玩游戏', menu=gamemenu)
root.config(menu=menubar)
start_game()
def move_up(event):
global seth
seth = 90
def move_down(event):
global seth
seth = 270
def move_left(event):
global seth
seth = 180
def move_right(event):
global seth
seth = 0
root.bind('', move_up)
root.bind('', move_down)
root.bind('', move_left)
root.bind('', move_right)
root.focus_set()
root.mainloop()
【提示】
部分含有Python第三方库相关内容的作品,在海龟编辑器网页端无法运行哦!如遇到这种情况,可以打开下面的链接,下载海龟编辑器客户端:
https://python.codemao.cn