能否提供一个编写贪吃蛇游戏的Python代码示例?
时间: 2024-12-21 18:21:10 浏览: 18
当然可以。这是一个简单的Python贪吃蛇游戏的框架代码示例,它使用了基本的控制台界面和pygame库来创建游戏窗口:
```python
import pygame
import random
# 初始化pygame
pygame.init()
# 设置屏幕尺寸
screen_width = 600
screen_height = 400
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("贪吃蛇")
snake_speed = 15
snake_block_size = 10
snake_direction = "right"
snake = [[20, screen_height // 2], [snake_block_size, screen_height // 2 - snake_block_size], [snake_block_size * 2, screen_height // 2 - snake_block_size * 2]]
food = [random.randint(0, screen_width - snake_block_size), random.randint(0, screen_height - snake_block_size)]
clock = pygame.time.Clock()
game_over = False
while not game_over:
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT and snake_direction != "right":
snake_direction = "left"
elif event.key == pygame.K_RIGHT and snake_direction != "left":
snake_direction = "right"
elif event.key == pygame.K_UP and snake_direction != "down":
snake_direction = "up"
elif event.key == pygame.K_DOWN and snake_direction != "up":
snake_direction = "down"
# 更新蛇的位置
new_head = list(snake[0])
if snake_direction == "right":
new_head[0] += snake_block_size
elif snake_direction == "left":
new_head[0] -= snake_block_size
elif snake_direction == "up":
new_head[1] -= snake_block_size
elif snake_direction == "down":
new_head[1] += snake_block_size
snake.insert(0, new_head)
# 检查边界和碰撞
if snake[0][0] < 0 or snake[0][0] >= screen_width or snake[0][1] < 0 or snake[0][1] >= screen_height:
game_over = True
for body_part in snake[1:]:
if body_part == snake[0]:
game_over = True
break
# 移动食物
food_x, food_y = food
if food_x == snake[0][0] and food_y == snake[0][1]:
food = [random.randint(0, screen_width - snake_block_size), random.randint(0, screen_height - snake_block_size)]
else:
food = [food_x + random.choice([-snake_block_size, snake_block_size]), food_y + random.choice([-snake_block_size, snake_block_size])]
# 绘制屏幕
screen.fill((0, 0, 0)) # 黑色背景
for block in snake:
pygame.draw.rect(screen, (255, 0, 0), pygame.Rect(block[0], block[1], snake_block_size, snake_block_size))
pygame.draw.rect(screen, (0, 255, 0), pygame.Rect(food[0], food[1], snake_block_size, snake_block_size))
pygame.display.flip()
clock.tick(snake_speed)
# 游戏结束
pygame.quit()
```
这个代码只是一个基础版本,实际游戏中还需要处理更多细节,比如玩家得分、循环判断等。如果你想了解更多关于贪吃蛇游戏开发的知识,可以在网上查找更详细的教程或源码。
阅读全文