用python写个贪吃蛇
时间: 2024-09-25 10:06:52 浏览: 26
使用Python写一个贪吃蛇游戏实例代码
编写一个简单的Python贪吃蛇游戏需要一些基本的游戏逻辑和界面处理。以下是一个基础版的贪吃蛇游戏的简要示例,使用了Python的`pygame`库来创建游戏窗口和处理事件:
```python
import pygame
import sys
# 初始化pygame
pygame.init()
# 设置窗口大小
screen_width = 400
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))
snake_speed = 10
snake_pos = [(screen_width // 2, screen_height // 2)]
snake_body = [[screen_width // 2, screen_height // 2]]
direction = 'right'
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_UP and direction != 'down':
direction = 'up'
elif event.key == pygame.K_DOWN and direction != 'up':
direction = 'down'
elif event.key == pygame.K_LEFT and direction != 'right':
direction = 'left'
elif event.key == pygame.K_RIGHT and direction != 'left':
direction = 'right'
# 移动蛇
new_head = snake_pos[-1]
if direction == 'up':
new_head = (new_head[0], new_head[1] - snake_speed)
elif direction == 'down':
new_head = (new_head[0], new_head[1] + snake_speed)
elif direction == 'left':
new_head = (new_head[0] - snake_speed, new_head[1])
else:
new_head = (new_head[0] + snake_speed, new_head[1])
snake_pos.append(new_head)
if new_head in snake_body[:-1]:
pygame.quit()
sys.exit()
snake_body.insert(0, list(snake_pos[-1]))
# 清空屏幕并绘制新位置
screen.fill((0, 0, 0))
for body_part in snake_body:
pygame.draw.rect(screen, (255, 0, 0), pygame.Rect(body_part[0], body_part[1], 10, 10))
pygame.display.flip()
# 检查是否吃到食物
food_x = random.randint(0, screen_width - 10)
food_y = random.randint(0, screen_height - 10)
if food_x == snake_pos[-1][0] and food_y == snake_pos[-1][1]:
food_pos = [food_x, food_y]
while food_pos in snake_body:
food_pos = [random.randint(0, screen_width - 10), random.randint(0, screen_height - 10)]
snake_body.append(food_pos)
```
在这个例子中,我们设置了一个循环,监听用户的键盘输入改变蛇的方向,并更新蛇的位置。当蛇碰到边界或自己时,游戏结束。这是一个非常基础的版本,实际游戏中可能还需要添加更多的细节,例如计分系统、游戏暂停等。
阅读全文