python实现贪吃蛇
时间: 2023-07-17 17:04:04 浏览: 50
好的,以下是一个简单的 Python 贪吃蛇游戏实现代码,希望能帮到你:
```python
import pygame
import random
# 初始化 pygame
pygame.init()
# 游戏窗口大小
win_width = 500
win_height = 500
# 创建游戏窗口
win = pygame.display.set_mode((win_width, win_height))
pygame.display.set_caption("贪吃蛇")
# 定义颜色
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
green = (0, 255, 0)
blue = (0, 0, 255)
# 蛇的大小
snake_size = 10
# 蛇移动的速度
snake_speed = 15
# 创建蛇类
class Snake:
def __init__(self, x, y):
self.x = x
self.y = y
self.width = snake_size
self.height = snake_size
self.direction = "right"
self.body = []
self.length = 1
def draw(self):
for block in self.body:
pygame.draw.rect(win, green, (block[0], block[1], self.width, self.height))
def move(self):
if self.direction == "right":
self.x += snake_size
elif self.direction == "left":
self.x -= snake_size
elif self.direction == "up":
self.y -= snake_size
elif self.direction == "down":
self.y += snake_size
self.body.insert(0, [self.x, self.y])
if len(self.body) > self.length:
self.body.pop()
def change_direction(self, direction):
if direction == "right" and self.direction != "left":
self.direction = "right"
elif direction == "left" and self.direction != "right":
self.direction = "left"
elif direction == "up" and self.direction != "down":
self.direction = "up"
elif direction == "down" and self.direction != "up":
self.direction = "down"
def check_collision(self):
if self.x >= win_width or self.x < 0 or self.y >= win_height or self.y < 0:
return True
for block in self.body[1:]:
if self.x == block[0] and self.y == block[1]:
return True
return False
def eat_food(self, food):
if self.x == food.x and self.y == food.y:
self.length += 1
return True
return False
# 创建食物类
class Food:
def __init__(self):
self.width = snake_size
self.height = snake_size
self.x = random.randrange(0, win_width - self.width, snake_size)
self.y = random.randrange(0, win_height - self.height, snake_size)
def draw(self):
pygame.draw.rect(win, red, (self.x, self.y, self.width, self.height))
# 创建游戏循环
def game_loop():
# 创建蛇和食物
snake = Snake(win_width//2, win_height//2)
food = Food()
# 创建游戏计时器
clock = pygame.time.Clock()
# 游戏结束标志
game_over = False
while not game_over:
# 设置游戏速度
clock.tick(snake_speed)
# 监听事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
if 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_collision():
game_over = True
# 绘制蛇和食物
win.fill(black)
snake.draw()
food.draw()
pygame.display.update()
# 蛇吃到食物
if snake.eat_food(food):
food = Food()
# 退出 pygame
pygame.quit()
# 启动游戏
game_loop()
```
希望这份代码对你有所帮助!