贪吃蛇的Python代码
时间: 2023-05-27 22:07:48 浏览: 73
以下是一个简单的贪吃蛇游戏的Python代码:
```
import pygame
import random
# 初始化pygame
pygame.init()
# 设置游戏窗口的宽度和高度
window_width = 800
window_height = 600
# 创建游戏窗口
game_window = pygame.display.set_mode((window_width, window_height))
# 设置游戏标题
pygame.display.set_caption('Snake Game')
# 设置游戏的帧率
clock = pygame.time.Clock()
# 定义颜色
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
green = (0, 255, 0)
# 设置贪吃蛇的初始位置和大小
snake_block_size = 10
snake_speed = 15
# 定义游戏字体
font_style = pygame.font.SysFont(None, 50)
# 定义显示分数的函数
def display_score(score):
score_text = font_style.render('Score: ' + str(score), True, green)
game_window.blit(score_text, [0, 0])
# 定义绘制贪吃蛇的函数
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
# 定义贪吃蛇的位置列表和长度
snake_list = []
length_of_snake = 1
# 定义食物的位置
foodx = round(random.randrange(0, window_width - snake_block_size) / 10.0) * 10.0
foody = round(random.randrange(0, window_height - snake_block_size) / 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/3, window_height/3])
display_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_over = True
game_close = False
if event.key == pygame.K_c:
game_loop()
# 处理游戏事件
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 -= snake_block_size
elif event.key == pygame.K_RIGHT:
x1 += snake_block_size
elif event.key == pygame.K_UP:
y1 -= snake_block_size
elif event.key == pygame.K_DOWN:
y1 += snake_block_size
# 判断是否撞墙
if x1 >= window_width or x1 < 0 or y1 >= window_height or y1 < 0:
game_close = True
# 更新贪吃蛇的位置
x1 += 0
y1 += 0
# 绘制游戏窗口
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)
display_score(length_of_snake - 1)
pygame.display.update()
# 判断是否吃到了食物,更新食物位置
if x1 == foodx and y1 == foody:
foodx = round(random.randrange(0, window_width - snake_block_size) / 10.0) * 10.0
foody = round(random.randrange(0, window_height - snake_block_size) / 10.0) * 10.0
length_of_snake += 1
# 控制游戏帧率
clock.tick(snake_speed)
# 退出pygame
pygame.quit()
# 运行游戏循环
game_loop()
```
此代码只是一个简单的贪吃蛇游戏,可以根据需要进行修改和改进。
阅读全文