python贪吃蛇代码实现
时间: 2023-07-23 17:57:18 浏览: 213
Python贪吃蛇游戏编写代码
下面是一个简单的Python贪吃蛇游戏的代码实现:
```python
import pygame
import random
# 初始化游戏
pygame.init()
# 定义颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
# 设置屏幕尺寸
screen_width = 640
screen_height = 480
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("贪吃蛇游戏")
# 定义蛇的初始位置和速度
snake_pos = [[100, 50], [90, 50], [80, 50]]
snake_speed = [10, 0]
# 定义食物的初始位置
food_pos = [random.randrange(1, (screen_width//10)) * 10,
random.randrange(1, (screen_height//10)) * 10]
food_spawn = True
# 初始化计分
score = 0
# 游戏主循环
game_over = False
clock = pygame.time.Clock()
while not game_over:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
# 检测按键操作
keys = pygame.key.get_pressed()
for key in keys:
if keys[pygame.K_LEFT]:
snake_speed = [-10, 0]
if keys[pygame.K_RIGHT]:
snake_speed = [10, 0]
if keys[pygame.K_UP]:
snake_speed = [0, -10]
if keys[pygame.K_DOWN]:
snake_speed = [0, 10]
# 移动蛇的头部
snake_pos[0][0] += snake_speed[0]
snake_pos[0][1] += snake_speed[1]
# 检测蛇与食物的碰撞
if snake_pos[0][0] == food_pos[0] and snake_pos[0][1] == food_pos[1]:
score += 1
food_spawn = False
else:
snake_pos.pop()
# 重新生成食物
if not food_spawn:
food_pos = [random.randrange(1, (screen_width // 10)) * 10,
random.randrange(1, (screen_height // 10)) * 10]
food_spawn = True
# 绘制屏幕
screen.fill(BLACK)
for pos in snake_pos:
pygame.draw.rect(screen, GREEN, pygame.Rect(
pos[0], pos[1], 10, 10))
pygame.draw.rect(screen, RED, pygame.Rect(
food_pos[0], food_pos[1], 10, 10))
# 游戏结束判断
if snake_pos[0][0] < 0 or snake_pos[0][0] > screen_width-10:
game_over = True
if snake_pos[0][1] < 0 or snake_pos[0][1] > screen_height-10:
game_over = True
for block in snake_pos[1:]:
if snake_pos[0][0] == block[0] and snake_pos[0][1] == block[1]:
game_over = True
pygame.display.update()
# 控制游戏速度
clock.tick(30)
# 退出游戏
pygame.quit()
```
以上就是一个简单的Python贪吃蛇游戏的代码实现。你可以将代码复制到Python环境中运行,即可开始游戏。祝你玩得开心!
阅读全文