Python贪吃蛇代码
时间: 2023-07-10 22:16:13 浏览: 80
以下是一个简单的Python贪吃蛇游戏代码示例:
```python
import pygame
import random
# 初始化pygame
pygame.init()
# 设置游戏界面大小、背景颜色、标题
screen = pygame.display.set_mode((600, 600))
pygame.display.set_caption("贪吃蛇")
# 定义颜色
BLACK = pygame.Color(0, 0, 0)
WHITE = pygame.Color(255, 255, 255)
RED = pygame.Color(255, 0, 0)
GREEN = pygame.Color(0, 255, 0)
BLUE = pygame.Color(0, 0, 255)
# 定义游戏变量
snake_position = [100, 100] # 蛇头位置
snake_body = [[100, 100], [90, 100], [80, 100]] # 蛇身位置
food_position = [300, 300] # 食物位置
food_spawned = False # 食物是否已经生成
direction = "RIGHT" # 蛇头初始方向
# 定义游戏常量
CELL_SIZE = 10 # 单元格大小
FPS = 10 # 帧率
FONT = pygame.font.SysFont("arial", 20) # 字体
# 定义函数:生成食物
def spawn_food():
global food_position, food_spawned
food_position = [random.randrange(0, screen.get_width() - CELL_SIZE, CELL_SIZE),
random.randrange(0, screen.get_height() - CELL_SIZE, CELL_SIZE)]
food_spawned = True
# 定义函数:绘制文字
def draw_text(text, font, color, surface, x, y):
text_obj = font.render(text, True, color)
text_rect = text_obj.get_rect()
text_rect.centerx = x
text_rect.centery = y
surface.blit(text_obj, text_rect)
# 游戏主循环
game_running = True
clock = pygame.time.Clock()
while game_running:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT and direction != "RIGHT":
direction = "LEFT"
elif event.key == pygame.K_RIGHT and direction != "LEFT":
direction = "RIGHT"
elif event.key == pygame.K_UP and direction != "DOWN":
direction = "UP"
elif event.key == pygame.K_DOWN and direction != "UP":
direction = "DOWN"
# 移动蛇头
if direction == "RIGHT":
snake_position[0] += CELL_SIZE
elif direction == "LEFT":
snake_position[0] -= CELL_SIZE
elif direction == "UP":
snake_position[1] -= CELL_SIZE
elif direction == "DOWN":
snake_position[1] += CELL_SIZE
# 判断是否吃到食物
if snake_position == food_position:
food_spawned = False
snake_body.append([0, 0])
# 移动蛇身
for i in range(len(snake_body) - 1, 0, -1):
snake_body[i] = snake_body[i - 1]
snake_body[0] = list(snake_position)
# 判断是否撞墙或咬到自己
if snake_position[0] < 0 or snake_position[0] >= screen.get_width() \
or snake_position[1] < 0 or snake_position[1] >= screen.get_height() \
or snake_position in snake_body[1:]:
game_running = False
# 生成食物
if not food_spawned:
spawn_food()
# 绘制游戏界面
screen.fill(BLACK)
for pos in snake_body:
pygame.draw.rect(screen, GREEN, pygame.Rect(pos[0], pos[1], CELL_SIZE, CELL_SIZE))
pygame.draw.rect(screen, RED, pygame.Rect(food_position[0], food_position[1], CELL_SIZE, CELL_SIZE))
draw_text("Score: {}".format(len(snake_body) - 3), FONT, WHITE, screen, 50, 20)
pygame.display.update()
# 控制帧率
clock.tick(FPS)
# 退出游戏
pygame.quit()
```
这个代码演示了如何使用pygame库实现一个简单的贪吃蛇游戏,包括移动蛇头、判断是否吃到食物、移动蛇身、判断是否撞墙或咬到自己等功能。你可以在此基础上进行修改和扩展。
阅读全文