Python版贪吃蛇游戏(开源)

我将整个贪吃蛇游戏的代码分割成了几个部分进行讲解,内容较长,建议细心观看!(注:全程没几个文字,不喜勿喷)

结尾会有完整版源码!

1.导入模块

游戏游戏,肯定得有游戏模块pygame,随后便是random模块了,代码如下:

import pygame
import random

导入好模块后下面就是基础设置了

一、基础设置部分

1.屏幕高度与宽度的设置

这个就不用多说了吧,懂得都懂

SCREEN_HEIGHT = 480
SCREEN_WIDTH = 600

 

2.小方格的大小与颜色的定义

GRID_SIZE = 20
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GREEN = (0, 255, 0)

初始化pygame

pyame.init()

创建屏幕

screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("贪吃蛇游戏")

创建游戏时钟

clock = pygame.time.Clock()

二、贪吃蛇类

1.贪吃蛇主体

class Snake:
    def __init__(self):
        self.positions = [(100, 100)]
        self.direction = (1, 0)

    def move(self):
        cur = self.positions[0]
        x, y = cur
        dx, dy = self.direction
        new = ((x + dx * GRID_SIZE) % SCREEN_WIDTH, (y + dy * GRID_SIZE) % SCREEN_HEIGHT)
        if new in self.positions[1:]:
            return False
        else:
            self.positions.insert(0, new)
            if new[0] == food_pos[0] and new[1] == food_pos[1]:
                return True
            else:
                self.positions.pop()
                return True

    def change_direction(self, direction):
        if (direction[0] * -1, direction[1] * -1)!= self.direction:
            self.direction = direction

2.食物类

class Food:
    def __init__(self):
        self.position = (random.randint(0, SCREEN_WIDTH // GRID_SIZE - 1) * GRID_SIZE,
                         random.randint(0, SCREEN_HEIGHT // GRID_SIZE - 1) * GRID_SIZE)

    def generate_new(self):
        while True:
            new_pos = (random.randint(0, SCREEN_WIDTH // GRID_SIZE - 1) * GRID_SIZE,
                       random.randint(0, SCREEN_HEIGHT // GRID_SIZE - 1) * GRID_SIZE)
            if new_pos not in snake.positions:
                self.position = new_pos
                break

三、游戏主循环

1.主循环部分

def game_loop():
    global snake, food
    snake = Snake()
    food = Food()

    running = True
    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_UP and snake.direction!= (0, 1):
                    snake.change_direction((0, -1))
                elif event.key == pygame.K_DOWN and snake.direction!= (0, -1):
                    snake.change_direction((0, 1))
                elif event.key == pygame.K_LEFT and snake.direction!= (1, 0):
                    snake.change_direction((-1, 0))
                elif event.key == pygame.K_RIGHT and snake.direction!= (-1, 0):
                    snake.change_direction((1, 0))

        if not snake.move():
            running = False

        if snake.positions[0] == food.position:
            food.generate_new()

        screen.fill(BLACK)

        for pos in snake.positions:
            pygame.draw.rect(screen, GREEN, [pos[0], pos[1], GRID_SIZE, GRID_SIZE])

        pygame.draw.rect(screen, WHITE, [food.position[0], food.position[1], GRID_SIZE, GRID_SIZE])

        pygame.display.flip()

        clock.tick(10)

    pygame.quit()

if __name__ == "__main__":
    game_loop()

四、完整版代码

如下:

import pygame
import random
# 基础设置
# 屏幕高度
SCREEN_HEIGHT = 480
# 屏幕宽度
SCREEN_WIDTH = 600
# 小方格大小
GRID_SIZE = 20
# 颜色定义
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GREEN = (0, 255, 0)
# 初始化 pygame
pygame.init()
# 创建屏幕
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("贪吃蛇游戏")
# 游戏时钟
clock = pygame.time.Clock()
# 贪吃蛇类
class Snake:
    def __init__(self):
        self.positions = [(100, 100)]
        self.direction = (1, 0)
    def move(self):
        cur = self.positions[0]
        x, y = cur
        dx, dy = self.direction
        new = ((x + dx * GRID_SIZE) % SCREEN_WIDTH, (y + dy * GRID_SIZE) % SCREEN_HEIGHT)
        if new in self.positions[1:]:
            return False
        else:
            self.positions.insert(0, new)
            if new[0] == food_pos[0] and new[1] == food_pos[1]:
                return True
            else:
                self.positions.pop()
                return True
    def change_direction(self, direction):
        if (direction[0] * -1, direction[1] * -1)!= self.direction:
            self.direction = direction
# 食物类
class Food:
    def __init__(self):
        self.position = (random.randint(0, SCREEN_WIDTH // GRID_SIZE - 1) * GRID_SIZE,
                         random.randint(0, SCREEN_HEIGHT // GRID_SIZE - 1) * GRID_SIZE)
    def generate_new(self):
        while True:
            new_pos = (random.randint(0, SCREEN_WIDTH // GRID_SIZE - 1) * GRID_SIZE,
                       random.randint(0, SCREEN_HEIGHT // GRID_SIZE - 1) * GRID_SIZE)
            if new_pos not in snake.positions:
                self.position = new_pos
                break
# 游戏主循环
def game_loop():
    global snake, food
    snake = Snake()
    food = Food()
    running = True
    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_UP and snake.direction!= (0, 1):
                    snake.change_direction((0, -1))
                elif event.key == pygame.K_DOWN and snake.direction!= (0, -1):
                    snake.change_direction((0, 1))
                elif event.key == pygame.K_LEFT and snake.direction!= (1, 0):
                    snake.change_direction((-1, 0))
                elif event.key == pygame.K_RIGHT and snake.direction!= (-1, 0):
                    snake.change_direction((1, 0))
        if not snake.move():
            running = False
        if snake.positions[0] == food.position:
            food.generate_new()
        screen.fill(BLACK)
        for pos in snake.positions:
            pygame.draw.rect(screen, GREEN, [pos[0], pos[1], GRID_SIZE, GRID_SIZE])
        pygame.draw.rect(screen, WHITE, [food.position[0], food.position[1], GRID_SIZE, GRID_SIZE])
        pygame.display.flip()
        clock.tick(10)
    pygame.quit()
if __name__ == "__main__":
    game_loop()

Python版贪吃蛇就到这里结束了,感谢您的观看,我们下期再见! 

以下是一个简单的贪吃蛇代码示例,使用 Python 语言编写: ```python import pygame import random # 初始化 Pygame pygame.init() # 设置游戏界面尺寸、背景颜色、标题 screen = pygame.display.set_mode((600, 600)) pygame.display.set_caption('贪吃蛇') # 定义颜色 BLACK = pygame.Color(0, 0, 0) WHITE = pygame.Color(255, 255, 255) RED = pygame.Color(255, 0, 0) GREEN = pygame.Color(0, 255, 0) # 定义游戏结束函数 def game_over(): font = pygame.font.SysFont(None, 48) text = font.render('游戏结束', True, RED) text_rect = text.get_rect() text_rect.centerx = screen.get_rect().centerx text_rect.centery = screen.get_rect().centery - 24 screen.blit(text, text_rect) pygame.display.flip() pygame.time.delay(3000) pygame.quit() sys.exit() # 定义主函数 def main(): # 初始化贪吃蛇和食物 snake_positions = [(200, 200), (210, 200), (220, 200)] snake_direction = 'right' food_position = (random.randint(0, 590), random.randint(0, 590)) food_exist = True # 设置游戏帧率 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_LEFT and snake_direction != 'right': snake_direction = 'left' elif event.key == pygame.K_RIGHT and snake_direction != 'left': snake_direction = 'right' elif event.key == pygame.K_UP and snake_direction != 'down': snake_direction = 'up' elif event.key == pygame.K_DOWN and snake_direction != 'up': snake_direction = 'down' # 移动贪吃蛇 if snake_direction == 'right': new_head = (snake_positions[0][0] + 10, snake_positions[0][1]) elif snake_direction == 'left': new_head = (snake_positions[0][0] - 10, snake_positions[0][1]) elif snake_direction == 'up': new_head = (snake_positions[0][0], snake_positions[0][1] - 10) elif snake_direction == 'down': new_head = (snake_positions[0][0], snake_positions[0][1] + 10) snake_positions.insert(0, new_head) # 判断贪吃蛇是否吃到食物 if snake_positions[0] == food_position: food_exist = False else: snake_positions.pop() # 重新生成食物 if not food_exist: food_position = (random.randint(0, 590), random.randint(0, 590)) food_exist = True # 绘制游戏界面 screen.fill(BLACK) for position in snake_positions: pygame.draw.rect(screen, GREEN, pygame.Rect(position[0], position[1], 10, 10)) pygame.draw.rect(screen, WHITE, pygame.Rect(food_position[0], food_position[1], 10, 10)) # 判断贪吃蛇是否死亡 if snake_positions[0][0] < 0 or snake_positions[0][0] > 590 or snake_positions[0][1] < 0 or snake_positions[0][1] > 590: game_over() for position in snake_positions[1:]: if snake_positions[0] == position: game_over() # 更新游戏界面 pygame.display.update() # 控制游戏帧率 clock.tick(10) # 启动游戏 if __name__ == '__main__': main() ``` 这是一个基本的贪吃蛇代码示例,可以实现贪吃蛇的基本功能。当然,你可以根据自己的需要进行修改和扩展。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值