用python写一段贪吃蛇的代码
时间: 2023-03-14 07:18:13 浏览: 193
Python本科毕业设计项目源代码用pygame模块设计并运行贪吃蛇小游戏.zip
5星 · 资源好评率100%
我可以为你提供一段Python贪吃蛇的代码:import pygame
import time
import randompygame.init()# 创建窗口
width = 600
height = 600
win = pygame.display.set_mode((width,height))
pygame.display.set_caption('贪吃蛇')# 定义一个 Block 类
class Block:
def __init__(self,x,y,width,height,color):
self.x = x
self.y = y
self.width = width
self.height = height
self.color = color# 定义一个 Snake 类
class Snake:
def __init__(self,body):
self.body = body
self.dir = 'RIGHT'# 画出蛇的身体
def draw(self,win):
for block in self.body:
pygame.draw.rect(win, block.color, (block.x, block.y, block.width, block.height))# 增加蛇的身体
def add_block(self):
last_block = self.body[-1]
x = last_block.x
y = last_block.y if self.dir == 'RIGHT':
x += last_block.width
elif self.dir == 'LEFT':
x -= last_block.width
elif self.dir == 'UP':
y -= last_block.height
elif self.dir == 'DOWN':
y += last_block.height self.body.append(Block(x,y,20,20,(0,255,0)))# 蛇转向
def move(self, dir):
self.dir = dir# 判断是否吃到食物
def eat(self,food):
head_block = self.body[0] if head_block.x == food.x and head_block.y == food.y:
self.add_block()
return True
else:
return False# 判断是否撞到自己
def hit_self(self):
head_block = self.body[0]
return head_block in self.body[1:]# 开始游戏
def start_game(): # 初始化
pygame.init()
run = True
clock = pygame.time.Clock() # 初始化蛇
snake = Snake([Block(300,300,20,20,(0,255,0))]) # 初始化食物
food = Block(random.randrange(20,580,20),random.randrange(20,580,20),20,20,(255,0,0)) # 游戏主循环
while run:
clock.tick(10) # 键盘监听
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False # 改变蛇的方向
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
snake.move('LEFT')
if keys[pygame.K_RIGHT]:
snake.move('RIGHT')
if keys[pygame.K_UP]:
snake.move('UP')
if keys[pygame.K_DOWN]:
snake.move('DOWN') # 填充屏幕
win.fill((0,0,0)) # 画出蛇
snake.draw(win) # 画出食物
pygame.draw.rect(win, food.color, (food.x, food.y, food.width, food.height)) # 蛇移动
snake.add_block()
snake.body.pop(0) # 检测是否吃到食物
if snake.eat(food):
food = Block(random.randrange(20,580,20),random.randrange(20,580,20),20,20,(255,0,0)) # 检测是否撞到自己
if snake.hit_self():
run = False # 更新画面
pygame.display.update() # 游戏结束
pygame.quit()start_game()
阅读全文