用python写贪吃蛇小游戏代码
时间: 2023-03-30 13:02:52 浏览: 99
很高兴回答你的问题。以下是一个简单的 Python 贪吃蛇小游戏代码:
```python
import pygame
import random
# 初始化 Pygame
pygame.init()
# 游戏窗口大小
WINDOW_WIDTH = 800
WINDOW_HEIGHT = 600
# 定义颜色
BLACK = (, , )
WHITE = (255, 255, 255)
GREEN = (, 255, )
RED = (255, , )
# 创建游戏窗口
window = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
pygame.display.set_caption('贪吃蛇')
# 定义蛇的初始位置和大小
snake_x = 100
snake_y = 100
snake_width = 20
snake_height = 20
# 定义蛇的移动速度
snake_speed = 20
# 定义食物的初始位置和大小
food_x = random.randint(, WINDOW_WIDTH - snake_width)
food_y = random.randint(, WINDOW_HEIGHT - snake_height)
food_width = 20
food_height = 20
# 定义蛇的初始长度和方向
snake_length = 1
snake_direction = 'right'
# 定义字体
font = pygame.font.SysFont(None, 30)
# 定义游戏结束函数
def game_over():
message = font.render('游戏结束!', True, RED)
message_rect = message.get_rect()
message_rect.center = (WINDOW_WIDTH / 2, WINDOW_HEIGHT / 2)
window.blit(message, message_rect)
pygame.display.update()
pygame.time.delay(200)
pygame.quit()
quit()
# 游戏循环
while True:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
snake_direction = 'left'
elif event.key == pygame.K_RIGHT:
snake_direction = 'right'
elif event.key == pygame.K_UP:
snake_direction = 'up'
elif event.key == pygame.K_DOWN:
snake_direction = 'down'
# 移动蛇
if snake_direction == 'left':
snake_x -= snake_speed
elif snake_direction == 'right':
snake_x += snake_speed
elif snake_direction == 'up':
snake_y -= snake_speed
elif snake_direction == 'down':
snake_y += snake_speed
# 判断是否吃到食物
if snake_x < food_x + food_width and snake_x + snake_width > food_x and snake_y < food_y + food_height and snake_y + snake_height > food_y:
food_x = random.randint(, WINDOW_WIDTH - snake_width)
food_y = random.randint(, WINDOW_HEIGHT - snake_height)
snake_length += 1
# 绘制游戏界面
window.fill(WHITE)
pygame.draw.rect(window, GREEN, [food_x, food_y, food_width, food_height])
snake_head = []
snake_head.append(snake_x)
snake_head.append(snake_y)
snake_list = []
snake_list.append(snake_head)
if len(snake_list) > snake_length:
del snake_list[]
for segment in snake_list:
pygame.draw.rect(window, BLACK, [segment[], segment[1], snake_width, snake_height])
pygame.display.update()
# 判断游戏是否结束
if snake_x < or snake_x > WINDOW_WIDTH - snake_width or snake_y < or snake_y > WINDOW_HEIGHT - snake_height:
game_over()
for segment in snake_list[:-1]:
if segment == snake_head:
game_over()
```
希望这个代码对你有帮助!
阅读全文