使用Python写一个贪吃蛇小游戏
  NOMZtDaUZEPy 2023年11月02日 55 0

Pygame 是一个 Python 库,提供了一系列方便的工具和函数来创建 2D 游戏。

首先,在代码中我们定义了一些常量,包括游戏区域的宽度和高度、蛇头和身体的大小等。然后,我们使用 Pygame 初始化了游戏,并设置了游戏区域的大小和窗口标题。

接着,我们定义了两个类:Snake(蛇)和 Food(食物)。Snake 类封装了蛇的属性和方法,包括蛇的头部和身体的位置、移动方法、改变方向方法、判断是否吃到食物方法和判断是否撞墙或自身的方法。Food 类封装了食物的属性和方法,包括食物的位置和生成方法。

import pygame
import random

# 定义颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)

# 游戏区域宽度和高度
WIDTH = 600
HEIGHT = 400

# 蛇头和身体大小
BLOCK_SIZE = 20

# 初始化 Pygame
pygame.init()

# 设置游戏区域大小
WINDOW_SIZE = (WIDTH, HEIGHT)
screen = pygame.display.set_mode(WINDOW_SIZE)

# 设置窗口标题
pygame.display.set_caption("贪吃蛇")

class Snake:
    def __init__(self):
        self.head = [WIDTH // 2, HEIGHT // 2]
        self.body = [self.head, [self.head[0] - BLOCK_SIZE, self.head[1]], [self.head[0] - 2 * BLOCK_SIZE, self.head[1]]]
        self.direction = "RIGHT"
    
    # 移动蛇
    def move(self):
        if self.direction == "RIGHT":
            new_head = [self.head[0] + BLOCK_SIZE, self.head[1]]
        elif self.direction == "LEFT":
            new_head = [self.head[0] - BLOCK_SIZE, self.head[1]]
        elif self.direction == "UP":
            new_head = [self.head[0], self.head[1] - BLOCK_SIZE]
        elif self.direction == "DOWN":
            new_head = [self.head[0], self.head[1] + BLOCK_SIZE]
            
        self.body.insert(0, new_head)
        self.head = new_head
        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 eat_food(self, food):
        return self.head == food
    
    # 判断蛇是否撞到墙或者自己
    def hit_wall_or_self(self):
        if self.head[0] < 0 or self.head[0] >= WIDTH or self.head[1] < 0 or self.head[1] >= HEIGHT:
            return True
        for i in range(1, len(self.body)):
            if self.head == self.body[i]:
                return True
        return False

class Food:
    def __init__(self):
        self.pos = [random.randrange(0, WIDTH // BLOCK_SIZE) * BLOCK_SIZE, random.randrange(0, HEIGHT // BLOCK_SIZE) * BLOCK_SIZE]
    
    # 在随机位置生成食物
    def spawn(self):
        self.pos = [random.randrange(0, WIDTH // BLOCK_SIZE) * BLOCK_SIZE, random.randrange(0, HEIGHT // BLOCK_SIZE) * BLOCK_SIZE]

# 初始化蛇和食物
snake = Snake()
food = Food()

# 游戏循环
game_over = False
clock = pygame.time.Clock()
while not game_over:
    # 处理事件
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            game_over = True
        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.hit_wall_or_self():
        game_over = True
        
    # 判断蛇是否吃到食物
    if snake.eat_food(food.pos):
        food.spawn()
        snake.body.append(snake.body[-1])
        
    # 渲染屏幕
    screen.fill(BLACK)
    
    # 绘制蛇
    for block in snake.body:
        pygame.draw.rect(screen, BLUE, [block[0], block[1], BLOCK_SIZE, BLOCK_SIZE])
    pygame.draw.rect(screen, GREEN, [snake.head[0], snake.head[1], BLOCK_SIZE, BLOCK_SIZE])
    
    # 绘制食物
    pygame.draw.rect(screen, RED, [food.pos[0], food.pos[1], BLOCK_SIZE, BLOCK_SIZE])
    
    # 更新屏幕
    pygame.display.update()
    
    # 控制游戏速度
    clock.tick(10)
    
# 退出 Pygame
pygame.quit()
【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月08日 0

暂无评论