python编程贪吃蛇
时间: 2023-10-02 14:08:12 浏览: 88
Python贪吃蛇游戏编写代码
对于Python编程中的贪吃蛇游戏,你可以使用Pygame库来实现。下面是一个简单的示例代码:
```python
import pygame
import random
# 初始化游戏
pygame.init()
# 定义窗口大小和颜色
win_width = 800
win_height = 600
win_color = (0, 0, 0)
# 创建窗口
win = pygame.display.set_mode((win_width, win_height))
pygame.display.set_caption("Greedy Snake")
# 定义贪吃蛇的颜色、大小和速度
snake_color = (0, 255, 0)
snake_size = 20
snake_speed = 10
# 蛇的初始位置和移动方向
snake_x = win_width // 2
snake_y = win_height // 2
snake_dx = 0
snake_dy = 0
# 食物的颜色和初始位置
food_color = (255, 0, 0)
food_size = 20
food_x = random.randint(0, win_width - food_size)
food_y = random.randint(0, win_height - food_size)
# 蛇的身体列表,初始长度为1
snake_body = []
snake_length = 1
# 游戏结束标志
game_over = False
# 游戏主循环
while not game_over:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
# 获取键盘输入,控制蛇的移动方向
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
snake_dx = -snake_speed
snake_dy = 0
elif keys[pygame.K_RIGHT]:
snake_dx = snake_speed
snake_dy = 0
elif keys[pygame.K_UP]:
snake_dx = 0
snake_dy = -snake_speed
elif keys[pygame.K_DOWN]:
snake_dx = 0
snake_dy = snake_speed
# 更新蛇的位置
snake_x += snake_dx
snake_y += snake_dy
# 检测蛇是否吃到食物
if snake_x < food_x + food_size and snake_x + snake_size > food_x and \
snake_y < food_y + food_size and snake_y + snake_size > food_y:
food_x = random.randint(0, win_width - food_size)
food_y = random.randint(0, win_height - food_size)
snake_length += 1
# 渲染游戏界面
win.fill(win_color)
pygame.draw.rect(win, food_color, (food_x, food_y, food_size, food_size))
# 更新蛇的身体列表
snake_body.append((snake_x, snake_y))
if len(snake_body) > snake_length:
del snake_body[0]
# 检测蛇是否碰到自己或边界,游戏结束
if (snake_x, snake_y) in snake_body[:-1] or \
snake_x < 0 or snake_x >= win_width or \
snake_y < 0 or snake_y >= win_height:
game_over = True
# 绘制蛇的身体
for body_part in snake_body:
pygame.draw.rect(win, snake_color, (body_part[0], body_part[1], snake_size, snake_size))
# 更新屏幕显示
pygame.display.flip()
# 退出游戏
pygame.quit()
```
你可以将以上代码保存为一个Python文件,然后运行它,即可开始玩贪吃蛇游戏。在游戏界面中,蛇的目标是吃到食物,每吃到一个食物,蛇的长度增加。当蛇碰到自己的身体或边界时,游戏结束。祝你编程愉快!
阅读全文