用Python实现贪吃蛇游戏
时间: 2024-03-06 10:43:21 浏览: 75
以下是用Python实现贪吃蛇游戏的一个简单示例:
```python
import pygame
import time
# 初始化游戏
pygame.init()
# 定义颜色
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
# 设置游戏窗口的宽度和高度
window_width = 800
window_height = 600
# 创建游戏窗口
game_window = pygame.display.set_mode((window_width, window_height))
pygame.display.set_caption('贪吃蛇游戏')
# 设置游戏速度
clock = pygame.time.Clock()
snake_block_size = 20
snake_speed = 15
# 定义字体
font_style = pygame.font.SysFont(None, 50)
score_font = pygame.font.SysFont(None, 35)
# 定义显示分数的函数
def show_score(score):
score_text = score_font.render("Score: " + str(score), True, black)
game_window.blit(score_text, [10, 10])
# 定义绘制蛇的函数
def draw_snake(snake_block_size, snake_list):
for x in snake_list:
pygame.draw.rect(game_window, black, [x[0], x[1], snake_block_size, snake_block_size])
# 定义游戏主循环
def game_loop():
game_over = False
game_close = False
# 初始化蛇的位置和长度
x1 = window_width / 2
y1 = window_height / 2
x1_change = 0
y1_change = 0
snake_list = []
length_of_snake = 1
# 随机生成食物的位置
foodx = round((window_width / 2) / 10.0) * 10.0
foody = round((window_height / 2) / 10.0) * 10.0
while not game_over:
while game_close == True:
game_window.fill(white)
game_over_text = font_style.render("Game Over", True, red)
game_window.blit(game_over_text, [window_width / 2 - 100, window_height / 2 - 50])
show_score(length_of_snake - 1)
pygame.display.update()
# 游戏结束后,按下空格键重新开始游戏,按下q键退出游戏
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
game_loop()
if event.key == pygame.K_q:
game_over = True
game_close = False
# 控制蛇的移动
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 >= window_width or x1 < 0 or y1 >= window_height or y1 < 0:
game_close = True
# 更新蛇的位置
x1 += x1_change
y1 += y1_change
game_window.fill(white)
pygame.draw.rect(game_window, red, [foodx, foody, snake_block_size, snake_block_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_close = True
# 绘制蛇和食物
draw_snake(snake_block_size, snake_list)
show_score(length_of_snake - 1)
pygame.display.update()
# 判断蛇是否吃到食物,如果吃到则生成新的食物
if x1 == foodx and y1 == foody:
foodx = round((window_width / 2) / 10.0) * 10.0
foody = round((window_height / 2) / 10.0) * 10.0
length_of_snake += 1
# 控制游戏速度
clock.tick(snake_speed)
pygame.quit()
# 开始游戏
game_loop()
```
阅读全文