📜  蛇案例 (1)

📅  最后修改于: 2023-12-03 15:27:52.621000             🧑  作者: Mango

蛇案例介绍

简介

蛇游戏是一款经典的小游戏,玩法简单,操作容易上手,深受众多玩家的喜爱。玩家要控制一条小蛇在有限的区域内移动,吃食物增加长度,同时要避免碰到障碍物或撞到自身身体,否则游戏结束。

实现思路

蛇游戏的实现思路分为以下几步:

  1. 游戏初始化:初始化地图、蛇、食物等信息。

  2. 蛇移动:根据用户的操作,蛇头向相应的方向移动,蛇身跟随蛇头移动。

  3. 碰撞检测:判断蛇头是否撞到墙壁或自身,以及是否吃到食物。

  4. 游戏结束:如果蛇头撞到墙壁或自身,或者吃到了禁止食用的特殊食物,游戏结束。

代码实现

以下是一个简单的蛇游戏的代码实现,主要包括游戏初始化、蛇的移动、碰撞检测和游戏结束等逻辑。

# 蛇游戏实现
import pygame
import random

# 初始化pygame
pygame.init()

# 设置游戏窗口大小
win_width = 800
win_height = 600
win = pygame.display.set_mode((win_width, win_height))
pygame.display.set_caption("Snake Game")

# 设置颜色
black = (0, 0, 0)
white = (255, 255, 255)
red = (255, 0, 0)
green = (0, 255, 0)

# 设置游戏参数
cell_size = 20
snake_speed = 15

# 定义蛇类
class Snake:
    def __init__(self, start_x, start_y):
        self.snake_size = 1
        self.snake_pos = [[start_x, start_y]]
        self.snake_dir = "RIGHT"
    
    def move(self):
        if self.snake_dir == "UP":
            new_pos = [self.snake_pos[0][0], self.snake_pos[0][1] - cell_size]
        elif self.snake_dir == "DOWN":
            new_pos = [self.snake_pos[0][0], self.snake_pos[0][1] + cell_size]
        elif self.snake_dir == "LEFT":
            new_pos = [self.snake_pos[0][0] - cell_size, self.snake_pos[0][1]]
        elif self.snake_dir == "RIGHT":
            new_pos = [self.snake_pos[0][0] + cell_size, self.snake_pos[0][1]]
        
        self.snake_pos.insert(0, new_pos)
        if len(self.snake_pos) > self.snake_size:
            self.snake_pos.pop()

    def change_dir(self, new_dir):
        if new_dir == "UP" and self.snake_dir != "DOWN":
            self.snake_dir = "UP"
        elif new_dir == "DOWN" and self.snake_dir != "UP":
            self.snake_dir = "DOWN"
        elif new_dir == "LEFT" and self.snake_dir != "RIGHT":
            self.snake_dir = "LEFT"
        elif new_dir == "RIGHT" and self.snake_dir != "LEFT":
            self.snake_dir = "RIGHT"

# 定义食物类
class Food:
    def __init__(self):
        self.food_pos = [random.randrange(0, win_width - cell_size, cell_size), random.randrange(0, win_height - cell_size, cell_size)]

    def draw_food(self):
        pygame.draw.rect(win, red, pygame.Rect(self.food_pos[0], self.food_pos[1], cell_size, cell_size))

# 定义游戏初始化函数
def game_init():
    global snake, food
    start_x = random.randrange(0, win_width - cell_size, cell_size)
    start_y = random.randrange(0, win_height - cell_size, cell_size)
    snake = Snake(start_x, start_y)
    food = Food()

# 定义游戏结束函数
def game_over():
    font = pygame.font.SysFont("arial", 40)
    text = font.render("GAME OVER", True, red)
    win.blit(text, (win_width/2 - text.get_width()/2, win_height/2 - text.get_height()/2))
    pygame.display.update()

# 游戏循环
game_init()
clock = pygame.time.Clock()
while True:
    # 监听事件
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_UP:
                snake.change_dir("UP")
            elif event.key == pygame.K_DOWN:
                snake.change_dir("DOWN")
            elif event.key == pygame.K_LEFT:
                snake.change_dir("LEFT")
            elif event.key == pygame.K_RIGHT:
                snake.change_dir("RIGHT")
    
    # 蛇移动
    snake.move()

    # 碰撞检测
    if snake.snake_pos[0][0] < 0 or snake.snake_pos[0][0] > win_width - cell_size or \
        snake.snake_pos[0][1] < 0 or snake.snake_pos[0][1] > win_height - cell_size or \
        snake.snake_pos[0] in snake.snake_pos[1:]:
        game_over()

    if snake.snake_pos[0] == food.food_pos:
        snake.snake_size += 1
        food = Food()

    win.fill(white)
    snake_head = pygame.draw.rect(win, green, pygame.Rect(snake.snake_pos[0][0], snake.snake_pos[0][1], cell_size, cell_size))
    for pos in snake.snake_pos[1:]:
        pygame.draw.rect(win, black, pygame.Rect(pos[0], pos[1], cell_size, cell_size))
    food.draw_food()
    pygame.display.update()

    # 设置游戏帧数
    clock.tick(snake_speed)

以上代码是一个简单的蛇游戏实现,包括了游戏初始化、蛇的移动、碰撞检测和游戏结束等逻辑。可以根据需要进行修改和扩展,增加游戏难度或增加一些特殊道具等元素,让游戏更加有趣。