• 【Python游戏】Python基于pygame实现的人机大战的斗兽棋小游戏 | 附源码


    前言

    有粉丝说要我出一期Python版本的斗兽棋,今天宠粉狂魔的我不就来啦!!
    虽然是一个简单的小游戏,但是对于新手小伙伴来说还是有一定的小难度的哟!要是不理解都可以找到小编的哈!!

    相关文件

    关注小编,私信小编领取哟!
    当然别忘了一件三连哟~~

    公众号:Python日志
    可以关注小编公众号,会不定时的发布一下Python小技巧,还有很多资源可以免费领取哟!!
    源码领取:加Python学习交流群:494958217 可以领取哟

    开发工具

    Python版本:3.7.8
    相关模块:
    pygame模块;
    sys模块;
    os模块;
    以及一些python自带的模块。

    环境搭建

    安装Python并添加到环境变量,pip安装需要的相关模块即可。

    效果展示

    游戏开始环节
    在这里插入图片描述
    游戏中
    在这里插入图片描述
    赢得游戏
    在这里插入图片描述

    部分代码展示

    模块导入

    import os
    import sys
    from typing import Tuple
    
    import pygame
    
    
    import settings
    from board import Board
    from strategies import get_random_move, get_eat_move,get_best_move,get_best_move2
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    监听用户键鼠事件

        while True:
            
            if board.not_eat >= 20:
                return (0, 0)
            if board.game_over():
                return board.get_result()
    
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    terminate()
                if event.type == pygame.MOUSEBUTTONUP:
                    if board.turn == 'red':
                        x,y = event.pos[0],event.pos[1]
                        board.collect_coordinates_and_make_move(x,y)
            
            window_surface.fill(settings.WHITE)
            # 绘制棋盘
            board.draw_board(window_surface,stretched_images)
            # 绘制轮到谁出牌的提示
            color = board.get_turn_color()
            text = '你的回合' if board.turn == 'red' else "对方回合"
            write_text(big_font,
                    text,
                    color,
                    window_rect.centerx,
                    window_rect.centery+250,
                    window_surface)
            
            pygame.display.update()
            
            if board.turn == 'blue':
                valid_moves = board.get_valid_moves()
                if valid_moves:
                    pygame.time.delay(400)
                    move = get_best_move(valid_moves, board)
                    board.make_computer_move(move, window_surface)
    
            
            main_clock.tick(settings.FPS)
        
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40

    主函数

    if __name__ == "__main__":
        # 初始化
        pygame.init()
        main_clock = pygame.time.Clock()
    
        # 加载各种图片并且保存到一个字典里面
        icon_image = pygame.image.load(os.path.join(settings.IMAGE_DIR,'bitbug_favicon.ico'))
        back_image = pygame.image.load(os.path.join(settings.IMAGE_DIR,'问号.jpg'))
        back_stretched_image = pygame.transform.scale(back_image,(settings.CELL_SIZE,settings.CELL_SIZE))
        stretched_images = {'back':back_stretched_image}
        for color in ('red','blue'):
            for animal in settings.ANIMALS:
                filename = f'{color}_{animal}'
                original_image = pygame.image.load(os.path.join(settings.IMAGE_DIR,filename+'.jpg'))
                stretched_image = pygame.transform.scale(original_image,(settings.CELL_SIZE,settings.CELL_SIZE))
                stretched_images[filename] = stretched_image
    
        # 创建窗口
        pygame.display.set_icon(icon_image)
        window_surface = pygame.display.set_mode((settings.WINDOW_WIDTH,settings.WINDOW_HEIGHT))
        window_rect = window_surface.get_rect()
        pygame.display.set_caption('斗兽棋 Python学习交流群:494958217  源码领取加群哟')
        
        # 创建字体
        big_font = pygame.font.Font(os.path.join(settings.FONT_DIR,'msyh.ttf'),48)
        small_font = pygame.font.Font(os.path.join(settings.FONT_DIR,'msyh.ttf'),24)
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27

    棋盘类

    class Board:
        '''棋盘类'''
        def __init__(self) -> None:
            # 用于存放16颗棋子
            pieces: List[Piece] = []
            # 添加红方的8颗棋子
            for name in settings.ANIMALS:
                pieces.append(Piece(name,'red'))
            # 添加蓝方的8颗棋子
            for name in settings.ANIMALS:
                pieces.append(Piece(name,'blue'))
            # 随机打乱棋子的顺序
            random.shuffle(pieces)
            # 用于存放棋盘上的16个格子
            # 这些格子是4行4列
            self._container: List[List[Cell]] = []
            # 把16颗棋子放到16个格子上
            i = 0
            for row in range(4):
                row_of_board = []
                for col in range(4):
                    row_of_board.append(
                        Cell(pieces[i], 
                             settings.LEFT_OF_BOARD + col*settings.CELL_SIZE,
                             settings.TOP_OF_BOARD + row*settings.CELL_SIZE,
                             settings.CELL_SIZE)
                        )
                    i += 1
                self._container.append(row_of_board)
            self._turn = random.choice(['red','blue'])
            # 保存的用户第一次点击的坐标
            self.user_coordinates = None
            # 10次没有互相吃,就平局
            self.not_eat = 0
        
        @property
        def turn(self) -> str:
            return self._turn
        
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39

    棋子类

    class Piece:
        '''棋子类'''
        def __init__(self,name: str, color: Tuple[int,int,int]) -> None:
            # 动物的名字
            self.name = name
            # 动物的颜色,用它来区分是哪一队的棋子
            self.color = color
            # 动物的权重
            self.score = SCORES[name]
    
            # 设置动物的天敌和食物
            # 大象和老鼠比较特殊,其他都是按照列表里的顺序排列的
            if name == 'elephant':
                self.enemy = {'mouse'}
                self.food = { a for a in ANIMALS[1:-1]}
            elif name == 'mouse':
                self.enemy = {a for a in ANIMALS[1:-1]}
                self.food = {'elephant'}
            else:
                index = ANIMALS.index(name)
                self.enemy = {a for a in ANIMALS[:index]}
                self.food = {a for a in ANIMALS[index+1:]}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22

    总结

    游戏最终结果如何其实不是很重要,重要的是一个学习的过程,只有自己弄懂了这个过程,学起来才会有动力,本游戏的一些主要的代码我已经写出来了,还有部分代码我就没有展示了,需要源码的小伙伴可以看相关文件哟!!
    源码都是可以给大家作参考的哟!!!!
    希望大家多多支持小编,这样小编才能够给大家带来更多知识分享哟!!

  • 相关阅读:
    基于Springboot的在线动漫信息平台
    Android 线程池源码详解(一)
    mac如何在item2中展示git分支
    Go-Excelize API源码阅读(三十五)——SetSheetCol
    15 -python之文件操作
    领域驱动模型设计与微服务架构落地-从项目去剖析领域驱动
    代码随想录 Leetcode435. 无重叠区间
    【Vue3】使用mitt实现任意组件通信
    MySQL 8.0 新特性
    通讯录的实现
  • 原文地址:https://blog.csdn.net/Gtieguo/article/details/126034689