Python写一个贪吃蛇
时间: 2024-01-06 09:03:09 浏览: 64
Python编写一个贪吃蛇游戏
好的,下面是一个简单的贪吃蛇的Python代码,希望能帮到你:
```python
import pygame
import random
# 初始化pygame
pygame.init()
# 游戏区域大小
width = 500
height = 500
# 创建游戏窗口
screen = pygame.display.set_mode((width, height))
# 设置游戏标题
pygame.display.set_caption("贪吃蛇")
# 定义贪吃蛇移动的速度
speed = 10
# 定义贪吃蛇的颜色
snake_color = (0, 255, 0)
# 定义食物的颜色
food_color = (255, 0, 0)
# 定义贪吃蛇的初始位置和长度
snake = [(250, 250), (240, 250), (230, 250)]
snake_length = len(snake)
# 定义食物的位置
food_x = random.randint(0, (width - 10) // 10) * 10
food_y = random.randint(0, (height - 10) // 10) * 10
# 定义贪吃蛇的初始方向
direction = "right"
# 定义游戏结束的变量
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 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"
# 移动贪吃蛇
head = snake[0]
if direction == "right":
new_head = (head[0] + speed, head[1])
elif direction == "left":
new_head = (head[0] - speed, head[1])
elif direction == "up":
new_head = (head[0], head[1] - speed)
elif direction == "down":
new_head = (head[0], head[1] + speed)
snake.insert(0, new_head)
if len(snake) > snake_length:
snake.pop()
# 判断是否吃到食物
if head[0] == food_x and head[1] == food_y:
food_x = random.randint(0, (width - 10) // 10) * 10
food_y = random.randint(0, (height - 10) // 10) * 10
snake_length += 1
# 绘制游戏界面
screen.fill((0, 0, 0))
for pos in snake:
pygame.draw.rect(screen, snake_color, pygame.Rect(pos[0], pos[1], 10, 10))
pygame.draw.rect(screen, food_color, pygame.Rect(food_x, food_y, 10, 10))
pygame.display.update()
# 判断游戏是否结束
if head[0] < 0 or head[0] >= width or head[1] < 0 or head[1] >= height:
game_over = True
for pos in snake[1:]:
if head[0] == pos[0] and head[1] == pos[1]:
game_over = True
# 退出pygame
pygame.quit()
```
这个游戏比较简单,贪吃蛇的移动速度和游戏界面大小可以根据实际需要调整。
阅读全文