使用python写一个贪吃蛇小游戏
时间: 2023-09-07 20:11:57 浏览: 112
好的,下面是一个简单的贪吃蛇小游戏的代码,使用Python语言编写:
```python
import pygame
import random
pygame.init()
# 游戏区域大小
width = 500
height = 500
# 定义颜色
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
green = (0, 255, 0)
# 创建游戏窗口
game_display = pygame.display.set_mode((width, height))
pygame.display.set_caption("贪吃蛇小游戏")
# 设置帧率
clock = pygame.time.Clock()
# 定义蛇的大小和速度
snake_size = 10
snake_speed = 15
# 定义字体
font_style = pygame.font.SysFont(None, 30)
# 显示得分
def show_score(score):
score_text = font_style.render("得分:" + str(score), True, white)
game_display.blit(score_text, [0, 0])
# 绘制蛇
def draw_snake(snake_size, snake_list):
for x in snake_list:
pygame.draw.rect(game_display, green, [x[0], x[1], snake_size, snake_size])
# 显示消息
def message(msg, color):
message_text = font_style.render(msg, True, color)
game_display.blit(message_text, [width / 6, height / 3])
# 游戏循环
def game_loop():
game_exit = False
game_over = False
# 初始坐标
x1 = width / 2
y1 = height / 2
# 坐标变化量
x1_change = 0
y1_change = 0
# 初始化蛇的列表
snake_list = []
length_of_snake = 1
# 定义食物的初始坐标
foodx = round(random.randrange(0, width - snake_size) / 10.0) * 10.0
foody = round(random.randrange(0, height - snake_size) / 10.0) * 10.0
while not game_exit:
while game_over == True:
game_display.fill(black)
message("游戏结束!按Q退出,按C重新开始", red)
show_score(length_of_snake - 1)
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
game_exit = True
game_over = False
elif event.key == pygame.K_c:
game_loop()
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_exit = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x1_change = -snake_size
y1_change = 0
elif event.key == pygame.K_RIGHT:
x1_change = snake_size
y1_change = 0
elif event.key == pygame.K_UP:
y1_change = -snake_size
x1_change = 0
elif event.key == pygame.K_DOWN:
y1_change = snake_size
x1_change = 0
# 判断是否出界
if x1 >= width or x1 < 0 or y1 >= height or y1 < 0:
game_over = True
# 更新坐标
x1 += x1_change
y1 += y1_change
game_display.fill(black)
# 绘制食物
pygame.draw.rect(game_display, red, [foodx, foody, snake_size, snake_size])
# 更新蛇的位置
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_size, snake_list)
# 显示得分
show_score(length_of_snake - 1)
# 更新游戏
pygame.display.update()
# 判断是否吃到食物
if x1 == foodx and y1 == foody:
foodx = round(random.randrange(0, width - snake_size) / 10.0) * 10.0
foody = round(random.randrange(0, height - snake_size) / 10.0) * 10.0
length_of_snake += 1
# 设置帧率
clock.tick(snake_speed)
pygame.quit()
quit()
game_loop()
```
你可以将以上代码复制到Python环境中运行,就可以开始游戏了!
阅读全文