Python的贪吃蛇代码
时间: 2024-04-10 21:25:32 浏览: 180
Python的贪吃蛇代码是一种经典的游戏实现,它可以通过控制蛇的移动来吃食物并增长身体长度。以下是一个简单的Python贪吃蛇代码示例:
```python
import pygame
import random
# 初始化游戏
pygame.init()
# 定义颜色
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
# 设置屏幕大小和标题
screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("贪吃蛇游戏")
# 定义蛇的初始位置和速度
snake_x = screen_width // 2
snake_y = screen_height // 2
snake_speed = 10
# 定义蛇的初始长度和身体
snake_length = 1
snake_body = [[snake_x, snake_y]]
# 定义食物的初始位置
food_x = random.randint(0, screen_width - 10)
food_y = random.randint(0, screen_height - 10)
# 定义游戏结束标志
game_over = False
# 游戏主循环
while not game_over:
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
# 获取键盘输入,控制蛇的移动方向
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
snake_x -= snake_speed
if keys[pygame.K_RIGHT]:
snake_x += snake_speed
if keys[pygame.K_UP]:
snake_y -= snake_speed
if keys[pygame.K_DOWN]:
snake_y += snake_speed
# 更新蛇的身体
snake_head = [snake_x, snake_y]
snake_body.append(snake_head)
if len(snake_body) > snake_length:
del snake_body
# 判断蛇是否吃到食物
if snake_x == food_x and snake_y == food_y:
food_x = random.randint(0, screen_width - 10)
food_y = random.randint(0, screen_height - 10)
snake_length += 1
# 绘制游戏界面
screen.fill(BLACK)
for body_part in snake_body:
pygame.draw.rect(screen, GREEN, (body_part, body_part, 10, 10))
pygame.draw.rect(screen, RED, (food_x, food_y, 10, 10))
pygame.display.update()
# 退出游戏
pygame.quit()
```
这段代码使用了Pygame库来实现游戏界面的绘制和键盘输入的监听。通过控制蛇的移动和判断是否吃到食物,来实现贪吃蛇游戏的基本逻辑。
阅读全文