请用python代码编写一个贪吃蛇游戏
时间: 2024-05-15 12:16:23 浏览: 133
抱歉,作为AI语言模型,我无法在此环境中运行代码。不过,以下是一个基本的贪吃蛇游戏的Python代码,供您参考:
``` python
import pygame
import random
# 初始化 pygame
pygame.init()
# 设置游戏窗口大小和标题
WIDTH, HEIGHT = 640, 480
pygame.display.set_caption("Greedy Snake")
screen = pygame.display.set_mode((WIDTH, HEIGHT))
# 定义颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
# 设置字体
font = pygame.font.SysFont(None, 30)
# 定义贪吃蛇类
class Snake:
def __init__(self, x, y):
self.x = x
self.y = y
self.dx = 10
self.dy = 0
self.body = [(self.x, self.y), (self.x - 10, self.y), (self.x - 20, self.y)]
self.length = 3
# 移动贪吃蛇
def move(self):
self.x += self.dx
self.y += self.dy
self.body.insert(0, (self.x, self.y))
if len(self.body) > self.length:
self.body.pop()
# 检查是否撞到自己或墙壁
def check_death(self):
if self.x < 0 or self.x > WIDTH or self.y < 0 or self.y > HEIGHT:
return True
for i in range(1, len(self.body)):
if self.body[i] == self.body[0]:
return True
return False
# 绘制贪吃蛇
def draw(self):
for x, y in self.body:
pygame.draw.rect(screen, GREEN, (x, y, 10, 10))
# 定义食物类
class Food:
def __init__(self):
self.x = random.randint(0, WIDTH - 10)
self.y = random.randint(0, HEIGHT - 10)
# 绘制食物
def draw(self):
pygame.draw.rect(screen, RED, (self.x, self.y, 10, 10))
# 创建贪吃蛇和食物
snake = Snake(WIDTH/2, HEIGHT/2)
food = Food()
# 游戏循环
clock = pygame.time.Clock()
score = 0
running = True
while running:
clock.tick(20) # 控制帧率
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
snake.dx = -10
snake.dy = 0
elif event.key == pygame.K_RIGHT:
snake.dx = 10
snake.dy = 0
elif event.key == pygame.K_UP:
snake.dx = 0
snake.dy = -10
elif event.key == pygame.K_DOWN:
snake.dx = 0
snake.dy = 10
# 移动贪吃蛇
snake.move()
# 检查是否撞到自己或墙壁
if snake.check_death():
running = False
# 检查是否吃到食物
if snake.body[0][0] == food.x and snake.body[0][1] == food.y:
snake.length += 1
score += 10
food = Food()
# 绘制游戏界面
screen.fill(BLACK)
snake.draw()
food.draw()
text = font.render("Score: " + str(score), True, WHITE)
screen.blit(text, (10, 10))
pygame.display.update()
# 退出 pygame
pygame.quit()
```
阅读全文