python贪吃蛇代码
时间: 2023-07-22 10:07:19 浏览: 108
以下是一个简单的 Python 贪吃蛇游戏实现代码:
```python
import pygame
import random
# 初始化 Pygame
pygame.init()
# 游戏界面大小
width = 800
height = 600
# 创建游戏界面
screen = pygame.display.set_mode((width, height))
# 游戏界面标题
pygame.display.set_caption('贪吃蛇')
# 定义颜色
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
green = (0, 255, 0)
# 定义蛇的初始位置和大小
snake_block = 10
snake_speed = 15
# 初始化蛇的位置
x1 = 300
y1 = 300
# 定义蛇的移动方向
x1_change = 0
y1_change = 0
# 初始化食物的位置
foodx = round(random.randrange(0, width - snake_block) / 10.0) * 10.0
foody = round(random.randrange(0, height - snake_block) / 10.0) * 10.0
# 定义字体和文字
font_style = pygame.font.SysFont(None, 50)
def message(msg, color):
mesg = font_style.render(msg, True, color)
screen.blit(mesg, [width / 6, height / 3])
# 游戏结束函数
def game_over():
message('你输了!按 Q 退出或者按 C 重新开始', red)
pygame.display.update()
while True:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
pygame.quit()
quit()
elif event.key == pygame.K_c:
gameLoop()
# 游戏循环
def gameLoop():
global x1_change, y1_change, x1, y1, foodx, foody
# 初始化蛇的长度
snake_List = []
Length_of_snake = 1
# 游戏是否结束
game_over = False
# 游戏循环
while not game_over:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x1_change = -snake_block
y1_change = 0
elif event.key == pygame.K_RIGHT:
x1_change = snake_block
y1_change = 0
elif event.key == pygame.K_UP:
y1_change = -snake_block
x1_change = 0
elif event.key == pygame.K_DOWN:
y1_change = snake_block
x1_change = 0
# 判断蛇是否撞墙
if x1 >= width or x1 < 0 or y1 >= height or y1 < 0:
game_over()
# 更新蛇的位置
x1 += x1_change
y1 += y1_change
# 游戏界面填充白色
screen.fill(white)
# 绘制食物和蛇
pygame.draw.rect(screen, green, [foodx, foody, snake_block, snake_block])
snake_Head = []
snake_Head.append(x1)
snake_Head.append(y1)
snake_List.append(snake_Head)
if len(snake_List) > Length_of_snake:
del snake_List[0]
for x in snake_List[:-1]:
if x == snake_Head:
game_over()
for x in snake_List:
pygame.draw.rect(screen, black, [x[0], x[1], snake_block, snake_block])
pygame.display.update()
# 判断蛇是否吃到食物
if x1 == foodx and y1 == foody:
foodx = round(random.randrange(0, width - snake_block) / 10.0) * 10.0
foody = round(random.randrange(0, height - snake_block) / 10.0) * 10.0
Length_of_snake += 1
# 控制游戏速度
clock = pygame.time.Clock()
clock.tick(snake_speed)
pygame.quit()
quit()
gameLoop()
```
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)