用python给我写一个贪吃蛇游戏
时间: 2023-06-14 08:04:25 浏览: 90
好的,以下是一个简单的贪吃蛇游戏的Python代码:
```python
import pygame
import random
# 定义颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
# 设置屏幕大小
SCREEN_WIDTH = 600
SCREEN_HEIGHT = 600
# 定义蛇的初始位置和大小
SNAKE_SIZE = 10
SNAKE_X = SCREEN_WIDTH / 2
SNAKE_Y = SCREEN_HEIGHT / 2
SNAKE_SPEED = 10
# 初始化pygame
pygame.init()
# 设置屏幕大小
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("贪吃蛇")
# 定义蛇的初始方向
direction = "right"
# 定义食物的位置
food_x = round(random.randrange(0, SCREEN_WIDTH - SNAKE_SIZE) / 10.0) * 10.0
food_y = round(random.randrange(0, SCREEN_HEIGHT - SNAKE_SIZE) / 10.0) * 10.0
# 初始化得分和蛇的长度
score = 0
snake_length = 1
snake_list = []
# 游戏循环
game_over = False
while not game_over:
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
# 获取键盘输入,改变蛇的方向
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
direction = "left"
elif event.key == pygame.K_RIGHT:
direction = "right"
elif event.key == pygame.K_UP:
direction = "up"
elif event.key == pygame.K_DOWN:
direction = "down"
# 根据方向移动蛇的位置
if direction == "right":
SNAKE_X += SNAKE_SPEED
elif direction == "left":
SNAKE_X -= SNAKE_SPEED
elif direction == "up":
SNAKE_Y -= SNAKE_SPEED
elif direction == "down":
SNAKE_Y += SNAKE_SPEED
# 绘制背景
screen.fill(BLACK)
# 绘制食物
pygame.draw.rect(screen, GREEN, [food_x, food_y, SNAKE_SIZE, SNAKE_SIZE])
# 绘制蛇
snake_head = []
snake_head.append(SNAKE_X)
snake_head.append(SNAKE_Y)
snake_list.append(snake_head)
if len(snake_list) > snake_length:
del snake_list[0]
for segment in snake_list[:-1]:
if segment == snake_head:
game_over = True
for segment in snake_list:
pygame.draw.rect(screen, WHITE, [segment[0], segment[1], SNAKE_SIZE, SNAKE_SIZE])
# 检查蛇是否吃到食物
if SNAKE_X == food_x and SNAKE_Y == food_y:
food_x = round(random.randrange(0, SCREEN_WIDTH - SNAKE_SIZE) / 10.0) * 10.0
food_y = round(random.randrange(0, SCREEN_HEIGHT - SNAKE_SIZE) / 10.0) * 10.0
score += 10
snake_length += 1
# 显示得分
font = pygame.font.SysFont('arial', 20)
text = font.render("得分: " + str(score), True, WHITE)
screen.blit(text, [0, 0])
# 刷新屏幕
pygame.display.update()
# 控制游戏速度
clock = pygame.time.Clock()
clock.tick(20)
# 退出游戏
pygame.quit()
```
这个游戏可能不是非常完美,但是可以作为一个简单的贪吃蛇游戏的例子。
阅读全文