python语言写贪吃蛇_python语言实现贪吃蛇游戏

本文实例为大家分享了python实现贪吃蛇游戏的具体代码,供大家参考,具体内容如下

新手自学python(简易贪吃蛇代码)

环境python3.7

刚刚大学毕业进入工作岗位,发现同事基本都会写py脚本,于是自学了一下,并写了一个简单的贪吃蛇代码,我觉得写的还是比较容易看懂,适合新手接触python。

# -*- coding: utf-8 -*-

import tkinter as tk

# 使用Tkinter前需要先导入

import tkinter.messagebox

import pickle

import random

import time

# 第1步,实例化object,建立窗口window

window = tk.Tk()

# 第2步,给窗口的可视化起名字

window.title('Greedy snake')

# 第3步,设定窗口的大小(长 * 宽)

# window.geometry('1004x504') # 这里的乘是小x

# 第5步,创建一个主frame,长在主window窗口上

frame = tk.Frame(window, bg = 'blue', bd = 2, relief = tk.FLAT)

frame.pack(side = 'left')

#当前框架被选中,意思是键盘触发,只对这个框架有效

frame.focus_set()

Labellist = [] #存放所有方块的label

Blocklist = [] #存放背景方块的值 1:被占用 0:空闲

Snakelist = [] #存放snake的坐标

height = 15

width = 20

#snack前进方向

left = 0

right = 1

up = 2

down =3

pause = 0

start = 1

class App(tk.Frame):

def __init__(self,master):

self.window = master

tk.Frame.__init__(self)

master.bind('',self.Up)

master.bind('',self.Left)

master.bind('',self.Right)

master.bind('',self.Down)

master.bind('

',self.Pause)

master.bind('',self.Start)

master.bind('',self.Restart)

self.Init_snake() #初始化界面方法

self.time = 1000

self.Onetime()

def Up(self, event):

if self.Istart:

self.direction = up

def Down(self, event):

if self.Istart:

self.direction = down

def Left(self, event):

if self.Istart:

self.direction = left

def Right(self, event):

if self.Istart:

self.direction = right

def Init_snake(self):

del Labellist[:]

del Blocklist[:]

del Snakelist[:]

#初始化背景方块

LabelRowList = []

BlockRowlist = []

c = r = 0

for k in range(width*height):

LN=tk.Label(frame,text = ' ', bg = 'black', fg = 'white', relief = tk.FLAT, bd = 4)

LN.grid(row=r,column=c,sticky=tk.N+tk.E+tk.S+tk.W)

LabelRowList.append(LN)

BlockRowlist.append(0)

c=c+1

if c>=20:

r=r+1

c=0

Labellist.append(LabelRowList)

Blocklist.append(BlockRowlist)

LabelRowList = []

BlockRowlist = []

#初始化snake

self.Istart = 0

self.direction = left

self.direction_last = left

self.overflag = 0

#snake head的初始位置

self.x = 7

self.y = 8

#snake tail的初始位置

self.x_tail = 7

self.y_tail = 10

Snakelist.append((7,8))

Snakelist.append((7,9))

Snakelist.append((7,10))

self.snakelen = len(Snakelist)

Blocklist[self.x][self.y] = 1

Blocklist[self.x][self.y+1] = 1

Blocklist[self.x][self.y+2] = 1

Labellist[self.x][self.y].config(bg = 'green', relief = tk.RAISED)

Labellist[self.x][self.y+1].config(bg = 'white', relief = tk.RAISED)

Labellist[self.x][self.y+2].config(bg = 'white', relief = tk.RAISED)

#初始化food

self.food_x = random.randint(0,14)

self.food_y = random.randint(0,19)

while Blocklist[self.food_x][self.food_y] == 1:

self.food_x = random.randint(0,14)

self.food_y = random.randint(0,19)

Blocklist[self.food_x][self.food_y] = 1

Labellist[self.food_x][self.food_y].config(bg = 'red', relief = tk.RIDGE)

def Pause(self, event):

self.Istart = pause

def Start(self, event):

self.Istart = start

def Restart(self, event):

self.Init_snake()

def Onetime(self): #每1000ms做一次界面刷新

if self.Istart and self.overflag == 0:

if (self.direction_last == down and self.direction == up )or(self.direction_last == up and self.direction == down )or(self.direction_last ==left and self.direction == right )or(self.direction_last ==right and self.direction == left ):

self.direction = self.direction_last

self.direction_last = self.direction

x0 = self.x

y0 = self.y

if self.direction == left:

if x0 == self.food_x and y0-1 == self.food_y:

Labellist[x0][y0-1].config(bg = 'green', relief = tk.RAISED)

Labellist[x0][y0].config(bg = 'white', relief = tk.RAISED)

self.food_x = random.randint(0,14)

self.food_y = random.randint(0,19)

while Blocklist[self.food_x][self.food_y] == 1:

self.food_x = random.randint(0,14)

self.food_y = random.randint(0,19)

Blocklist[self.food_x][self.food_y] = 1

Labellist[self.food_x][self.food_y].config(bg = 'red', relief = tk.RIDGE)

self.snakelen += 1

Snakelist.insert(0,(x0,y0-1))

self.x = x0

self.y = y0 - 1

elif (x0>=0 and x0=0 and y0-1

Blocklist[self.x_tail][self.y_tail] = 0

Labellist[self.x_tail][self.y_tail].config(bg = 'black', relief = tk.FLAT)

Blocklist[x0][y0-1] = 1

Labellist[x0][y0-1].config(bg = 'green', relief = tk.RAISED)

Labellist[x0][y0].config(bg = 'white', relief = tk.RAISED)

del Snakelist[self.snakelen - 1]

Snakelist.insert(0,(x0,y0-1))

self.x = x0

self.y = y0 - 1

self.x_tail = Snakelist[self.snakelen - 1][0]

self.y_tail = Snakelist[self.snakelen - 1][1]

else:

tk.messagebox.showinfo(title = 'snake', message = 'game over!!!')

self.overflag = 1

elif self.direction == up:

if x0-1 == self.food_x and y0 == self.food_y:

Labellist[x0-1][y0].config(bg = 'green', relief = tk.RAISED)

Labellist[x0][y0].config(bg = 'white', relief = tk.RAISED)

self.food_x = random.randint(0,14)

self.food_y = random.randint(0,19)

while Blocklist[self.food_x][self.food_y] == 1:

self.food_x = random.randint(0,14)

self.food_y = random.randint(0,19)

Blocklist[self.food_x][self.food_y] = 1

Labellist[self.food_x][self.food_y].config(bg = 'red', relief = tk.RIDGE)

self.snakelen += 1

Snakelist.insert(0,(x0-1,y0))

self.x = x0 - 1

self.y = y0

elif (x0-1 >=0 and x0-1=0 and y0

Blocklist[self.x_tail][self.y_tail] = 0

Labellist[self.x_tail][self.y_tail].config(bg = 'black', relief = tk.FLAT)

Blocklist[x0-1][y0] = 1

Labellist[x0-1][y0].config(bg = 'green', relief = tk.RAISED)

Labellist[x0][y0].config(bg = 'white', relief = tk.RAISED)

del Snakelist[self.snakelen - 1]

Snakelist.insert(0,(x0 - 1,y0))

self.x = x0 - 1

self.y = y0

self.x_tail = Snakelist[self.snakelen - 1][0]

self.y_tail = Snakelist[self.snakelen - 1][1]

else:

tk.messagebox.showinfo(title = 'snake', message = 'game over!!!')

self.overflag = 1

elif self.direction == down:

if x0+1 == self.food_x and y0 == self.food_y:

Labellist[x0+1][y0].config(bg = 'green', relief = tk.RAISED)

Labellist[x0][y0].config(bg = 'white', relief = tk.RAISED)

self.food_x = random.randint(0,14)

self.food_y = random.randint(0,19)

while Blocklist[self.food_x][self.food_y] == 1:

self.food_x = random.randint(0,14)

self.food_y = random.randint(0,19)

Blocklist[self.food_x][self.food_y] = 1

Labellist[self.food_x][self.food_y].config(bg = 'red', relief = tk.RIDGE)

self.snakelen += 1

Snakelist.insert(0,(x0+1,y0))

self.x = x0 + 1

self.y = y0

elif (x0+1 >=0 and x0+1 =0 and y0

Blocklist[self.x_tail][self.y_tail] = 0

Labellist[self.x_tail][self.y_tail].config(bg = 'black', relief = tk.FLAT)

Blocklist[x0+1][y0] = 1

Labellist[x0+1][y0].config(bg = 'green', relief = tk.RAISED)

Labellist[x0][y0].config(bg = 'white', relief = tk.RAISED)

del Snakelist[self.snakelen - 1]

Snakelist.insert(0,(x0 + 1,y0))

self.x = x0 + 1

self.y = y0

self.x_tail = Snakelist[self.snakelen - 1][0]

self.y_tail = Snakelist[self.snakelen - 1][1]

else:

tk.messagebox.showinfo(title = 'snake', message = 'game over!!!')

self.overflag = 1

elif self.direction == right:

if x0 == self.food_x and y0+1 == self.food_y:

Labellist[x0][y0+1].config(bg = 'green', relief = tk.RAISED)

Labellist[x0][y0].config(bg = 'white', relief = tk.RAISED)

self.food_x = random.randint(0,14)

self.food_y = random.randint(0,19)

while Blocklist[self.food_x][self.food_y] == 1:

self.food_x = random.randint(0,14)

self.food_y = random.randint(0,19)

Blocklist[self.food_x][self.food_y] = 1

Labellist[self.food_x][self.food_y].config(bg = 'red', relief = tk.RIDGE)

self.snakelen += 1

Snakelist.insert(0,(x0,y0 + 1))

self.x = x0

self.y = y0 + 1

elif (x0>=0 and x0=0 and y0+1

Blocklist[self.x_tail][self.y_tail] = 0

Labellist[self.x_tail][self.y_tail].config(bg = 'black', relief = tk.FLAT)

Blocklist[x0][y0+1] = 1

Labellist[x0][y0+1].config(bg = 'green', relief = tk.RAISED)

Labellist[x0][y0].config(bg = 'white', relief = tk.RAISED)

del Snakelist[self.snakelen - 1]

Snakelist.insert(0,(x0,y0 + 1))

self.x = x0

self.y = y0 + 1

self.x_tail = Snakelist[self.snakelen - 1][0]

self.y_tail = Snakelist[self.snakelen - 1][1]

else:

tk.messagebox.showinfo(title = 'snake', message = 'game over!!!')

self.overflag = 1

self.after(self.time,self.Onetime)

def Start_Stop():

app.Istart = 1 - app.Istart

def Restart():

app.Restart(0)

#主菜单

mainmenu = tk.Menu(window)

window['menu'] = mainmenu

#二级菜单:game

gamemenu=tk.Menu(mainmenu)

mainmenu.add_cascade(label='游戏',menu=gamemenu)

gamemenu.add_command(label = '开始/暂停',command=Start_Stop)

gamemenu.add_command(label = '重置',command=Restart)

gamemenu.add_command(label = '退出',command=window.quit)

app = App(window)

window.mainloop()

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

本文标题: python语言实现贪吃蛇游戏

本文地址: http://www.cppcns.com/jiaoben/python/363976.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面是一个简单的贪吃蛇小游戏的Python代码。这个游戏使用了Pygame库来实现图形化显示。 ```python import pygame import random # 初始化pygame pygame.init() # 定义游戏窗口大小 window_width = 800 window_height = 600 # 创建游戏窗口 window = pygame.display.set_mode((window_width, window_height)) # 设置游戏标题 pygame.display.set_caption('贪吃蛇小游戏') # 定义颜色 white = (255, 255, 255) black = (0, 0, 0) red = (255, 0, 0) green = (0, 255, 0) blue = (0, 0, 255) # 定义蛇的初始位置和大小 snake_x = window_width // 2 snake_y = window_height // 2 snake_w = 20 snake_h = 20 # 定义蛇的移动速度 snake_speed = 5 # 定义食物的初始位置和大小 food_x = random.randint(0, window_width - snake_w) food_y = random.randint(0, window_height - snake_h) food_w = 20 food_h = 20 # 定义蛇的初始移动方向 snake_direction = 'right' # 定义游戏结束标志 game_over = False # 定义游戏循环 while not game_over: # 处理事件 for event in pygame.event.get(): if event.type == pygame.QUIT: game_over = True elif event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT and snake_direction != 'right': snake_direction = 'left' elif event.key == pygame.K_RIGHT and snake_direction != 'left': snake_direction = 'right' elif event.key == pygame.K_UP and snake_direction != 'down': snake_direction = 'up' elif event.key == pygame.K_DOWN and snake_direction != 'up': snake_direction = 'down' # 移动蛇的位置 if snake_direction == 'left': snake_x -= snake_speed elif snake_direction == 'right': snake_x += snake_speed elif snake_direction == 'up': snake_y -= snake_speed elif snake_direction == 'down': snake_y += snake_speed # 判断蛇是否撞墙 if snake_x < 0 or snake_x > window_width - snake_w or snake_y < 0 or snake_y > window_height - snake_h: game_over = True # 判断蛇是否吃到了食物 if snake_x < food_x + food_w and snake_x + snake_w > food_x and snake_y < food_y + food_h and snake_y + snake_h > food_y: food_x = random.randint(0, window_width - snake_w) food_y = random.randint(0, window_height - snake_h) # 绘制游戏界面 window.fill(white) pygame.draw.rect(window, red, [food_x, food_y, food_w, food_h]) pygame.draw.rect(window, green, [snake_x, snake_y, snake_w, snake_h]) pygame.display.update() # 控制游戏帧率 clock = pygame.time.Clock() clock.tick(30) # 退出pygame pygame.quit() ``` 这个代码中,我们使用了Pygame库来初始化游戏、创建游戏窗口、处理事件、绘制游戏界面等。我们定义了蛇的初始位置、大小和移动速度,以及食物的初始位置和大小。在游戏循环中,我们根据蛇的移动方向来更新蛇的位置,同时判断蛇是否撞墙或者吃到了食物。最后,我们通过Pygame库来绘制游戏界面,并控制游戏帧率。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值