用ptython写贪吃蛇
时间: 2023-03-03 12:13:10 浏览: 66
当然可以用Python编写贪吃蛇游戏!下面是一个简单的代码示例,可以让你开始编写自己的贪吃蛇游戏:
```python
import pygame
import random
# 初始化游戏
pygame.init()
# 设置屏幕尺寸
screen_width = 500
screen_height = 500
screen = pygame.display.set_mode((screen_width, screen_height))
# 设置游戏标题
pygame.display.set_caption("贪吃蛇")
# 设置游戏变量
snake_position = [100, 50]
snake_body = [[100, 50], [90, 50], [80, 50]]
food_position = [random.randrange(1, 50) * 10, random.randrange(1, 50) * 10]
food_spawn = True
direction = "RIGHT"
change_to = direction
score = 0
# 游戏循环
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
# 按键事件处理
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
change_to = "RIGHT"
elif event.key == pygame.K_LEFT:
change_to = "LEFT"
elif event.key == pygame.K_UP:
change_to = "UP"
elif event.key == pygame.K_DOWN:
change_to = "DOWN"
# 方向处理
if change_to == "RIGHT" and direction != "LEFT":
direction = "RIGHT"
elif change_to == "LEFT" and direction != "RIGHT":
direction = "LEFT"
elif change_to == "UP" and direction != "DOWN":
direction = "UP"
elif change_to == "DOWN" and direction != "UP":
direction = "DOWN"
# 蛇移动
if direction == "RIGHT":
snake_position[0] += 10
elif direction == "LEFT":
snake_position[0] -= 10
elif direction == "UP":
snake_position[1] -= 10
elif direction == "DOWN":
snake_position[1] += 10
# 蛇身更新
snake_body.insert(0, list(snake_position))
if snake_position == food_position:
food_spawn = False
score += 10
else:
snake_body.pop()
# 食物出现
if not food_spawn:
food_position = [random.randrange(1, 50) * 10, random.randrange(1, 50) * 10]
food_spawn = True
# 重绘屏幕
screen.fill((0, 0, 0))
for position in snake_body:
pygame.draw.rect(screen, (255, 255, 255), pygame.Rect(
position[0], position[1], 10, 10))
pygame.draw.rect(screen, (255, 0, 0), pygame.Rect(
food_position[0], food_position[1], 10, 10))
# 游戏结束判断
if snake_position[0] < 0 or snake_position[0] > screen_width-10:
pygame.quit()
quit()
if snake_position[1] < 0 or snake_position[1] > screen_height-10:
pygame.quit()
quit()
for block in snake_body[1:]:
if snake