用pathon写一个贪吃蛇
时间: 2024-05-01 21:21:43 浏览: 84
python写的贪吃蛇
好的,以下是一个简单的 Python 贪吃蛇游戏的代码实现(基于 Pygame 库):
``` python
import pygame
import random
# 初始化 Pygame 库
pygame.init()
# 游戏区域大小
width = 500
height = 500
# 设置游戏窗口
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("贪吃蛇游戏")
# 定义颜色
white = (255, 255, 255)
black = (0, 0, 0)
green = (0, 255, 0)
red = (255, 0, 0)
# 定义蛇的初始位置和大小
snake_x = 250
snake_y = 250
snake_w = 10
snake_h = 10
snake_speed = 10
# 定义食物的初始位置和大小
food_x = random.randint(0, width - snake_w)
food_y = random.randint(0, height - snake_h)
food_w = 10
food_h = 10
# 定义蛇的移动方向
snake_direction = 'right'
# 定义蛇的身体
snake_body = []
snake_length = 1
# 定义字体
font = pygame.font.Font(None, 30)
# 定义游戏结束函数
def game_over():
text = font.render("游戏结束!", True, red)
screen.blit(text, (width / 2 - 80, height / 2 - 15))
pygame.display.update()
pygame.time.delay(2000)
pygame.quit()
quit()
# 游戏循环
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_UP and snake_direction != 'down':
snake_direction = 'up'
elif event.key == pygame.K_DOWN and snake_direction != 'up':
snake_direction = 'down'
elif event.key == pygame.K_LEFT and snake_direction != 'right':
snake_direction = 'left'
elif event.key == pygame.K_RIGHT and snake_direction != 'left':
snake_direction = 'right'
# 移动蛇
if snake_direction == 'up':
snake_y -= snake_speed
elif snake_direction == 'down':
snake_y += snake_speed
elif snake_direction == 'left':
snake_x -= snake_speed
elif snake_direction == 'right':
snake_x += snake_speed
# 判断是否吃到食物
if snake_x < food_x + food_w and snake_x + snake_w > food_x and snake_y < food_y + food_h and snake_y + snake_h > food_y:
food_x = random.randint(0, width - snake_w)
food_y = random.randint(0, height - snake_h)
snake_length += 1
# 更新蛇的身体
snake_head = []
snake_head.append(snake_x)
snake_head.append(snake_y)
snake_body.append(snake_head)
if len(snake_body) > snake_length:
del snake_body[0]
# 判断是否撞墙
if snake_x < 0 or snake_x > width - snake_w or snake_y < 0 or snake_y > height - snake_h:
game_over()
# 判断是否撞到自己
for block in snake_body[:-1]:
if block == snake_head:
game_over()
# 绘制游戏界面
screen.fill(white)
pygame.draw.rect(screen, green, [food_x, food_y, food_w, food_h])
for block in snake_body:
pygame.draw.rect(screen, black, [block[0], block[1], snake_w, snake_h])
pygame.display.update()
pygame.time.delay(100)
```
这个代码实现了一个简单的贪吃蛇游戏,玩家可以通过方向键控制蛇的移动方向,吃到食物后蛇的身体长度会增加,如果蛇撞墙或者撞到自己,则游戏结束。
阅读全文