请使用python制作一个贪吃蛇游戏
时间: 2024-02-13 10:02:45 浏览: 84
python制作的贪吃蛇小游戏程序+代码
好的,下面是一个简单的Python贪吃蛇游戏代码:
```python
import pygame
import random
# 初始化pygame
pygame.init()
# 游戏窗口大小和标题
win_width = 800
win_height = 600
win = pygame.display.set_mode((win_width, win_height))
pygame.display.set_caption("贪吃蛇游戏")
# 定义颜色
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
# 定义贪吃蛇的属性
snake_block_size = 10
snake_speed = 15
# 定义字体
font_style = pygame.font.SysFont(None, 50)
# 定义函数:显示得分
def show_score(score):
score_font = font_style.render("得分:" + str(score), True, black)
win.blit(score_font, [0, 0])
# 定义函数:绘制贪吃蛇
def draw_snake(snake_block_size, snake_list):
for x in snake_list:
pygame.draw.rect(win, black, [x[0], x[1], snake_block_size, snake_block_size])
# 定义主函数
def main():
# 初始位置
x1 = win_width / 2
y1 = win_height / 2
x1_change = 0
y1_change = 0
# 初始长度
snake_List = []
Length_of_snake = 1
# 随机生成食物位置
foodx = round(random.randrange(0, win_width - snake_block_size) / 10.0) * 10.0
foody = round(random.randrange(0, win_height - snake_block_size) / 10.0) * 10.0
# 游戏循环标志
game_over = False
# 得分
score = 0
# 游戏循环
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_size
y1_change = 0
elif event.key == pygame.K_RIGHT:
x1_change = snake_block_size
y1_change = 0
elif event.key == pygame.K_UP:
y1_change = -snake_block_size
x1_change = 0
elif event.key == pygame.K_DOWN:
y1_change = snake_block_size
x1_change = 0
# 判断是否撞墙
if x1 >= win_width or x1 < 0 or y1 >= win_height or y1 < 0:
game_over = True
# 更新贪吃蛇的位置
x1 += x1_change
y1 += y1_change
# 绘制背景
win.fill(white)
# 绘制食物
pygame.draw.rect(win, red, [foodx, foody, snake_block_size, snake_block_size])
# 贪吃蛇吃到食物,长度+1
if x1 == foodx and y1 == foody:
foodx = round(random.randrange(0, win_width - snake_block_size) / 10.0) * 10.0
foody = round(random.randrange(0, win_height - snake_block_size) / 10.0) * 10.0
Length_of_snake += 1
score += 10
# 绘制贪吃蛇
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 = True
draw_snake(snake_block_size, snake_List)
# 显示得分
show_score(score)
# 刷新游戏界面
pygame.display.update()
# 控制游戏速度
clock = pygame.time.Clock()
clock.tick(snake_speed)
# 退出游戏
pygame.quit()
quit()
# 运行主函数
main()
```
这是一个简单的贪吃蛇游戏,包括了基本的运动、吃食物、增加长度、死亡等功能。你可以根据自己的需求进行修改和扩展。
阅读全文