python 贪吃蛇代码
时间: 2023-11-04 10:00:37 浏览: 101
python贪吃蛇代码
我很高兴为您提供 Python 贪吃蛇代码。以下是一个简单的示例代码:
```python
import pygame
import random
# 初始化游戏
pygame.init()
# 设置游戏窗口的尺寸
window_width = 800
window_height = 600
window = pygame.display.set_mode((window_width, window_height))
pygame.display.set_caption("贪吃蛇")
# 定义颜色
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
# 定义蛇的初始位置和大小
snake_block_size = 10
snake_speed = 30
snake_x = window_width / 2
snake_y = window_height / 2
snake_x_change = 0
snake_y_change = 0
snake_list = []
snake_length = 1
# 定义食物的初始位置
food_size = 10
food_x = round(random.randrange(0, window_width - food_size) / 10.0) * 10.0
food_y = round(random.randrange(0, window_height - food_size) / 10.0) * 10.0
# 定义蛇的移动函数
def move_snake(x, y, snake_list):
for snake in snake_list:
pygame.draw.rect(window, black, [snake[0], snake[1], snake_block_size, snake_block_size])
# 定义游戏结束的函数
def game_over():
game_over_font = pygame.font.SysFont(None, 72)
game_over_text = game_over_font.render("游戏结束", True, red)
window.blit(game_over_text, [window_width / 2 - game_over_text.get_width() / 2, window_height / 2 - game_over_text.get_height() / 2])
pygame.display.flip()
pygame.time.wait(2000)
pygame.quit()
# 游戏主循环
game_over_flag = False
clock = pygame.time.Clock()
while not game_over_flag:
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over_flag = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
snake_x_change = -snake_block_size
snake_y_change = 0
elif event.key == pygame.K_RIGHT:
snake_x_change = snake_block_size
snake_y_change = 0
elif event.key == pygame.K_UP:
snake_y_change = -snake_block_size
snake_x_change = 0
elif event.key == pygame.K_DOWN:
snake_y_change = snake_block_size
snake_x_change = 0
if snake_x >= window_width or snake_x < 0 or snake_y >= window_height or snake_y < 0:
game_over_flag = True
snake_x += snake_x_change
snake_y += snake_y_change
window.fill(white)
pygame.draw.rect(window, red, [food_x, food_y, food_size, food_size])
snake_head = []
snake_head.append(snake_x)
snake_head.append(snake_y)
snake_list.append(snake_head)
if len(snake_list) > snake_length:
del snake_list[0]
for snake in snake_list[:-1]:
if snake == snake_head:
game_over_flag = True
move_snake(snake_x_change, snake_y_change, snake_list)
pygame.display.update()
if snake_x == food_x and snake_y == food_y:
food_x = round(random.randrange(0, window_width - food_size) / 10.0) * 10.0
food_y = round(random.randrange(0, window_height - food_size) / 10.0) * 10.0
snake_length += 1
clock.tick(snake_speed)
game_over()
```
阅读全文