贪吃蛇python代码
时间: 2023-07-09 10:47:42 浏览: 87
贪吃蛇Python代码
以下是一个简单的贪吃蛇Python代码示例:
```python
import pygame
import random
# 初始化 Pygame 库
pygame.init()
# 定义常量
SCREEN_WIDTH = 600
SCREEN_HEIGHT = 600
BLOCK_SIZE = 20
FONT_SIZE = 30
FPS = 10
# 定义颜色
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
# 设置屏幕
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("贪吃蛇")
# 定义字体
font = pygame.font.SysFont(None, FONT_SIZE)
# 定义蛇的类
class Snake:
def __init__(self):
self.x = SCREEN_WIDTH // 2
self.y = SCREEN_HEIGHT // 2
self.direction = "right"
self.body = [(self.x, self.y), (self.x - BLOCK_SIZE, self.y), (self.x - BLOCK_SIZE * 2, self.y)]
# 移动蛇
def move(self):
if self.direction == "right":
self.x += BLOCK_SIZE
elif self.direction == "left":
self.x -= BLOCK_SIZE
elif self.direction == "up":
self.y -= BLOCK_SIZE
elif self.direction == "down":
self.y += BLOCK_SIZE
self.body.insert(0, (self.x, self.y))
self.body.pop()
# 改变蛇的方向
def change_direction(self, direction):
if (direction == "right" and self.direction != "left") or \
(direction == "left" and self.direction != "right") or \
(direction == "up" and self.direction != "down") or \
(direction == "down" and self.direction != "up"):
self.direction = direction
# 检测蛇是否撞墙或者撞到自己
def check_collision(self):
if self.x < 0 or self.x >= SCREEN_WIDTH or \
self.y < 0 or self.y >= SCREEN_HEIGHT or \
(self.x, self.y) in self.body[1:]:
return True
return False
# 检测蛇是否吃到食物
def check_food(self, food):
if self.x == food.x and self.y == food.y:
self.body.insert(0, (self.x, self.y))
return True
return False
# 绘制蛇
def draw(self):
for x, y in self.body:
pygame.draw.rect(screen, GREEN, [x, y, BLOCK_SIZE, BLOCK_SIZE])
# 定义食物的类
class Food:
def __init__(self):
self.x = random.randint(0, SCREEN_WIDTH // BLOCK_SIZE - 1) * BLOCK_SIZE
self.y = random.randint(0, SCREEN_HEIGHT // BLOCK_SIZE - 1) * BLOCK_SIZE
# 绘制食物
def draw(self):
pygame.draw.rect(screen, RED, [self.x, self.y, BLOCK_SIZE, BLOCK_SIZE])
# 创建蛇和食物对象
snake = Snake()
food = Food()
# 设置游戏时钟
clock = pygame.time.Clock()
# 游戏循环
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:
snake.change_direction("right")
elif event.key == pygame.K_LEFT:
snake.change_direction("left")
elif event.key == pygame.K_UP:
snake.change_direction("up")
elif event.key == pygame.K_DOWN:
snake.change_direction("down")
# 移动蛇
snake.move()
# 检测蛇是否吃到食物
if snake.check_food(food):
food = Food()
# 绘制背景
screen.fill(BLACK)
# 绘制蛇和食物
snake.draw()
food.draw()
# 检测蛇是否撞墙或者撞到自己
if snake.check_collision():
text = font.render("GAME OVER", True, WHITE)
screen.blit(text, ((SCREEN_WIDTH - text.get_width()) // 2, (SCREEN_HEIGHT - text.get_height()) // 2))
pygame.display.update()
pygame.time.wait(2000)
pygame.quit()
quit()
# 更新屏幕
pygame.display.update()
# 控制帧率
clock.tick(FPS)
```
以上代码仅供参考,还有很多细节需要完善。
阅读全文