pathon贪吃蛇代码
时间: 2023-05-26 16:01:07 浏览: 94
A:
以下是一个简单的Python贪吃蛇代码:
```python
import pygame
import random
# 初始化pygame
pygame.init()
# 定义颜色
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
# 设置屏幕宽度和高度
WIDTH = 800
HEIGHT = 600
# 创建屏幕
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Snake Game")
# 定义贪吃蛇的初始位置和大小
BLOCK_SIZE = 20
snake_pos = [random.randint(0, WIDTH - BLOCK_SIZE), random.randint(0, HEIGHT - BLOCK_SIZE)]
snake_body = [[snake_pos[0], snake_pos[1]], [snake_pos[0] - BLOCK_SIZE, snake_pos[1]], [snake_pos[0] - (2 * BLOCK_SIZE), snake_pos[1]]]
# 定义食物的初始位置和大小
food_pos = [random.randint(0, WIDTH - BLOCK_SIZE), random.randint(0, HEIGHT - BLOCK_SIZE)]
food_spawned = True
# 定义初始移动方向和速度
direction = "RIGHT"
change_to = direction
snake_speed = 10
# 定义游戏结束函数
def game_over():
font = pygame.font.SysFont("Arial", 60)
text = font.render("GameOver!", True, WHITE)
screen.blit(text, (WIDTH/2 - text.get_width() / 2, HEIGHT/2 - text.get_height() / 2))
pygame.display.flip()
pygame.time.delay(3000)
pygame.quit()
sys.exit()
# 游戏循环
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT and direction != "LEFT":
change_to = "RIGHT"
elif event.key == pygame.K_LEFT and direction != "RIGHT":
change_to = "LEFT"
elif event.key == pygame.K_UP and direction != "DOWN":
change_to = "UP"
elif event.key == pygame.K_DOWN and direction != "UP":
change_to = "DOWN"
elif event.key == pygame.K_ESCAPE:
pygame.event.post(pygame.event.Event(pygame.QUIT))
# 判断贪吃蛇是否碰到墙壁或自身
if snake_pos[0] < 0 or snake_pos[0] > WIDTH - BLOCK_SIZE or snake_pos[1] < 0 or snake_pos[1] > HEIGHT - BLOCK_SIZE:
game_over()
for block in snake_body[1:]:
if snake_pos == block:
game_over()
# 判断是否吃到食物,重新生成食物
if snake_pos == food_pos:
food_spawned = False
else:
snake_body.pop()
# 如果没有食物,生成新食物
if not food_spawned:
food_pos = [random.randrange(0, WIDTH // BLOCK_SIZE) * BLOCK_SIZE,
random.randrange(0, HEIGHT // BLOCK_SIZE) * BLOCK_SIZE]
food_spawned = True
# 移动贪吃蛇
if change_to == "RIGHT":
snake_pos[0] += BLOCK_SIZE
elif change_to == "LEFT":
snake_pos[0] -= BLOCK_SIZE
elif change_to == "UP":
snake_pos[1] -= BLOCK_SIZE
elif change_to == "DOWN":
snake_pos[1] += BLOCK_SIZE
direction = change_to
# 增加贪吃蛇长度
snake_body.insert(0, list(snake_pos))
# 显示贪吃蛇和食物
screen.fill(BLACK)
for pos in snake_body:
pygame.draw.rect(screen, GREEN, pygame.Rect(pos[0], pos[1], BLOCK_SIZE, BLOCK_SIZE))
pygame.draw.rect(screen, RED, pygame.Rect(food_pos[0], food_pos[1], BLOCK_SIZE, BLOCK_SIZE))
pygame.display.update()
# 控制游戏速度
snake_speed = len(snake_body) // 5
fps_controller = pygame.time.Clock()
fps_controller.tick(snake_speed)
```
阅读全文