用python制作一个贪吃蛇游戏代码
时间: 2024-09-16 11:05:40 浏览: 128
制作一个简单的Python贪吃蛇游戏需要一些基本的游戏设计知识和Python图形库,比如`pygame`。下面是一个基础的框架示例:
```python
import pygame
import random
# 初始化Pygame
pygame.init()
# 设置窗口大小
screen_width = 400
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("贪吃蛇")
# 定义颜色
white = (255, 255, 255)
black = (0, 0, 0)
# 蛇的初始设置
snake_pos = [(screen_width // 2, screen_height // 2), (screen_width // 2 - 10, screen_height // 2)]
snake_body = [[screen_width // 2, screen_height // 2], [screen_width // 2 - 20, screen_height // 2]]
food_pos = (random.randint(0, screen_width - 10), random.randint(0, screen_height - 10))
# 游戏主循环
running = True
while running:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP and snake_pos[0][1] > 0:
snake_pos[0] = (snake_pos[0][0], snake_pos[0][1] - 10)
elif event.key == pygame.K_DOWN and snake_pos[0][1] < screen_height - 10:
snake_pos[0] = (snake_pos[0][0], snake_pos[0][1] + 10)
elif event.key == pygame.K_LEFT and snake_pos[0][0] > 0:
snake_pos[0] = (snake_pos[0][0] - 10, snake_pos[0][1])
elif event.key == pygame.K_RIGHT and snake_pos[0][0] < screen_width - 10:
snake_pos[0] = (snake_pos[0][0] + 10, snake_pos[0][1])
# 绘制元素
screen.fill(black)
for pos in snake_body:
pygame.draw.rect(screen, white, [pos[0], pos[1], 10, 10])
pygame.draw.rect(screen, red, [food_pos[0], food_pos[1], 10, 10])
# 判断蛇是否吃到食物
if snake_pos[0] == food_pos:
food_pos = (random.randint(0, screen_width - 10), random.randint(0, screen_height - 10))
snake_body.append(snake_pos[0])
if len(snake_body) > 10:
snake_body.pop(0)
# 更新屏幕
pygame.display.flip()
# 结束游戏
pygame.quit()
```
注意:这个例子只是一个基础版本,实际的游戏会更复杂,包括碰撞检测、蛇的增长以及分数管理等。此外,上述代码也没有包含游戏结束的条件,通常当蛇头撞到墙或自身身体时游戏就会结束。
阅读全文