展开菜单
首页 精品内容 本月促销 装机必备 Windows PDF教程 macOS软件 IOS软件 Android AI 专题
全部分类

当前位置:

首页 > 编程开发 > 如何使用Python和Pygame实现走四棋游戏

如何使用Python和Pygame实现走四棋游戏

一、游戏解说“走四儿”大部分活跃在山东济南、聊城、菏泽等地,是一种棋类游戏,特别适合儿童试玩。在一个4×4的棋盘上,双方各有4子,分别摆放在棋盘两个最上面的两端线的四个位置上。下图就是“走四儿”开局的样子。二、游戏规则“走四儿”的游戏规则是:1.双方轮流走,每一步只能在上下左右中的一个无子的方向上走一个格,不能斜走。如果一方无法移动,则由另一方走。2.当甲方的一个子移动到一条线上之后,这条线上只有甲方的两个子和乙方的一个子,且甲方的这两子相连,乙方的子与甲方那两子中的一个子相连,那么乙方的这个

本文目录

    一、游戏解说

    “走四儿”大部分活跃在山东济南、聊城、菏泽等地,是一种棋类游戏,特别适合儿童试玩。

    在一个4×4的棋盘上,双方各有4子,分别摆放在棋盘两个最上面的两端线的四个位置上。下图

    就是“走四儿”开局的样子。

    如何使用Python和Pygame实现走四棋游戏

    二、游戏规则

    “走四儿”的游戏规则是:

    1.双方轮流走,每一步只能在上下左右中的一个无子的方向上走一个格,不能斜走。如果一方无法移动,则由另一方走。

    2.当甲方的一个子移动到一条线上之后,这条线上只有甲方的两个子和乙方的一个子,且甲方的这两子相连,乙方的子与甲方那两子中的一个子相连,那么乙方的这个子就被吃掉。

    下图是可以吃子的样式例举:

    如何使用Python和Pygame实现走四棋游戏

    3.少于2个子的一方为输者。双方都无法胜对方就可以认为是和棋。

    三、环境安装

     1)素材(图片) 

    如何使用Python和Pygame实现走四棋游戏

     2)运行环境 小编使用的环境:Python3、Pycharm社区版、Pygame、 numpy模块部分自带就不一一 展示啦。 

    模块安装:pip install -i https://pypi.douban.com/simple/+模块名

    四、代码展示

    import pygame as pg
    from pygame.locals import *
    import sys
    import time
    import numpy as np
    
    pg.init()
    size = width, height = 600, 400
    screen = pg.display.set_mode(size)
    f_clock = pg.time.Clock()
    fps = 30
    pg.display.set_caption("走四棋儿")
    background = pg.image.load("background.png").convert_alpha()
    glb_pos = [[(90, 40), (190, 40), (290, 40), (390, 40)],
               [(90, 140), (190, 140), (290, 140), (390, 140)],
               [(90, 240), (190, 240), (290, 240), (390, 240)],
               [(90, 340), (190, 340), (290, 340), (390, 340)]]
    
    
    class ChessPieces():
        def __init__(self, img_name):
            self.name = img_name
            self.id = None
            if self.name == 'heart':
                self.id = 2
            elif self.name == 'spade':
                self.id = 3
            self.img = pg.image.load(img_name + ".png").convert_alpha()
            self.rect = self.img.get_rect()
            self.pos_x, self.pos_y = 0, 0
            self.alive_state = True
    
        def get_rect(self):
            return (self.rect[0], self.rect[1])
    
        def get_pos(self):
            return (self.pos_x, self.pos_y)
    
        def update(self):
            if self.alive_state == True:
                self.rect[0] = glb_pos[self.pos_y][self.pos_x][0]
                self.rect[1] = glb_pos[self.pos_y][self.pos_x][1]
                screen.blit(self.img, self.rect)
    
    
    class Pointer():
        def __init__(self):
            self.img = pg.image.load("pointer.png").convert_alpha()
            self.rect = self.img.get_rect()
            self.show = False
            self.selecting_item = False
    
        def point_to(self, Heart_Blade_class):
            if Heart_Blade_class.alive_state:
                self.pointing_to_item = Heart_Blade_class
                self.item_pos = Heart_Blade_class.get_rect()
                self.rect[0], self.rect[1] = self.item_pos[0], self.item_pos[1] - 24
    
        def update(self):
            screen.blit(self.img, self.rect)
    
    
    class GlobalSituation():
        def __init__(self):
            self.glb_situation = np.array([[2, 2, 2, 2],
                                           [0, 0, 0, 0],
                                           [0, 0, 0, 0],
                                           [3, 3, 3, 3]], dtype=np.uint8)
            self.spade_turn = None
    
        def refresh_situation(self):
            self.glb_situation = np.zeros([4, 4], np.uint8)
            for i in range(4):
                if heart[i].alive_state:
                    self.glb_situation[heart[i].pos_y, heart[i].pos_x] = heart[i].id
            for i in range(4):
                if spade[i].alive_state:
                    self.glb_situation[spade[i].pos_y, spade[i].pos_x] = spade[i].id
            for i in range(4):
                print(self.glb_situation[i][:])
            print('=' * 12)
            if self.spade_turn != None:
                self.spade_turn = not self.spade_turn
    
        def check_situation(self, moved_item):
            curr_pos_x, curr_pos_y = moved_item.get_pos()
            curr_pos_col = self.glb_situation[:, curr_pos_x]
            curr_pos_raw = self.glb_situation[curr_pos_y, :]
            enemy_die = False
            if moved_item.id == 2:
                if np.sum(curr_pos_col) == 7:
                    if (curr_pos_col == np.array([0, 2, 2, 3])).all():
                        enemy_die = True
                        self.glb_situation[3, curr_pos_x] = 0
                        for spade_i in spade:
                            if spade_i.alive_state and spade_i.pos_x == curr_pos_x and spade_i.pos_y == 3:
                                spade_i.alive_state = False
                    elif (curr_pos_col == np.array([2, 2, 3, 0])).all():
                        enemy_die = True
                        self.glb_situation[2, curr_pos_x] = 0
                        for spade_i in spade:
                            if spade_i.alive_state and spade_i.pos_x == curr_pos_x and spade_i.pos_y == 2:
                                spade_i.alive_state = False
                    elif (curr_pos_col == np.array([0, 3, 2, 2])).all():
                        enemy_die = True
                        self.glb_situation[1, curr_pos_x] = 0
                        for spade_i in spade:
                            if spade_i.alive_state and spade_i.pos_x == curr_pos_x and spade_i.pos_y == 1:
                                spade_i.alive_state = False
                    elif (curr_pos_col == np.array([3, 2, 2, 0])).all():
                        enemy_die = True
                        self.glb_situation[0, curr_pos_x] = 0
                        for spade_i in spade:
                            if spade_i.alive_state and spade_i.pos_x == curr_pos_x and spade_i.pos_y == 0:
                                spade_i.alive_state = False
                if np.sum(curr_pos_raw) == 7:
                    if (curr_pos_raw == np.array([0, 2, 2, 3])).all():
                        enemy_die = True
                        self.glb_situation[curr_pos_y, 3] = 0
                        for spade_i in spade:
                            if spade_i.alive_state and spade_i.pos_x == 3 and spade_i.pos_y == curr_pos_y:
                                spade_i.alive_state = False
                    elif (curr_pos_raw == np.array([2, 2, 3, 0])).all():
                        enemy_die = True
                        self.glb_situation[curr_pos_y, 2] = 0
                        for spade_i in spade:
                            if spade_i.alive_state and spade_i.pos_x == 2 and spade_i.pos_y == curr_pos_y:
                                spade_i.alive_state = False
                    elif (curr_pos_raw == np.array([0, 3, 2, 2])).all():
                        enemy_die = True
                        self.glb_situation[curr_pos_y, 1] = 0
                        for spade_i in spade:
                            if spade_i.alive_state and spade_i.pos_x == 1 and spade_i.pos_y == curr_pos_y:
                                spade_i.alive_state = False
                    elif (curr_pos_raw == np.array([3, 2, 2, 0])).all():
                        enemy_die = True
                        self.glb_situation[curr_pos_y, 0] = 0
                        for spade_i in spade:
                            if spade_i.alive_state and spade_i.pos_x == 0 and spade_i.pos_y == curr_pos_y:
                                spade_i.alive_state = False
            elif moved_item.id == 3:
                if np.sum(curr_pos_col) == 8:
                    if (curr_pos_col == np.array([0, 3, 3, 2])).all():
                        enemy_die = True
                        self.glb_situation[3, curr_pos_x] = 0
                        for heart_i in heart:
                            if heart_i.alive_state and heart_i.pos_x == curr_pos_x and heart_i.pos_y == 3:
                                heart_i.alive_state = False
                    elif (curr_pos_col == np.array([3, 3, 2, 0])).all():
                        enemy_die = True
                        self.glb_situation[2, curr_pos_x] = 0
                        for heart_i in heart:
                            if heart_i.alive_state and heart_i.pos_x == curr_pos_x and heart_i.pos_y == 2:
                                heart_i.alive_state = False
                    elif (curr_pos_col == np.array([0, 2, 3, 3])).all():
                        enemy_die = True
                        self.glb_situation[1, curr_pos_x] = 0
                        for heart_i in heart:
                            if heart_i.alive_state and heart_i.pos_x == curr_pos_x and heart_i.pos_y == 1:
                                heart_i.alive_state = False
                    elif (curr_pos_col == np.array([2, 3, 3, 0])).all():
                        enemy_die = True
                        self.glb_situation[0, curr_pos_x] = 0
                        for heart_i in heart:
                            if heart_i.alive_state and heart_i.pos_x == curr_pos_x and heart_i.pos_y == 0:
                                heart_i.alive_state = False
                if np.sum(curr_pos_raw) == 8:
                    if (curr_pos_raw == np.array([0, 3, 3, 2])).all():
                        enemy_die = True
                        self.glb_situation[curr_pos_y, 3] = 0
                        for heart_i in heart:
                            if heart_i.alive_state and heart_i.pos_x == 3 and heart_i.pos_y == curr_pos_y:
                                heart_i.alive_state = False
                    elif (curr_pos_raw == np.array([3, 3, 2, 0])).all():
                        enemy_die = True
                        self.glb_situation[curr_pos_y, 2] = 0
                        for heart_i in heart:
                            if heart_i.alive_state and heart_i.pos_x == 2 and heart_i.pos_y == curr_pos_y:
                                heart_i.alive_state = False
                    elif (curr_pos_raw == np.array([0, 2, 3, 3])).all():
                        enemy_die = True
                        self.glb_situation[curr_pos_y, 1] = 0
                        for heart_i in heart:
                            if heart_i.alive_state and heart_i.pos_x == 1 and heart_i.pos_y == curr_pos_y:
                                heart_i.alive_state = False
                    elif (curr_pos_raw == np.array([2, 3, 3, 0])).all():
                        enemy_die = True
                        self.glb_situation[curr_pos_y, 0] = 0
                        for heart_i in heart:
                            if heart_i.alive_state and heart_i.pos_x == 0 and heart_i.pos_y == curr_pos_y:
                                heart_i.alive_state = False
            if enemy_die == True:
                self.glb_situation = np.zeros([4, 4], np.uint8)
                for i in range(4):
                    if heart[i].alive_state:
                        self.glb_situation[heart[i].pos_y, heart[i].pos_x] = heart[i].id
                for i in range(4):
                    if spade[i].alive_state:
                        self.glb_situation[spade[i].pos_y, spade[i].pos_x] = spade[i].id
                for i in range(4):
                    print(self.glb_situation[i][:])
                print('=' * 12)
    
        def check_game_over(self):
            heart_alive_num, spade_alive_num = 0, 0
            for heart_i in heart:
                if heart_i.alive_state:
                    heart_alive_num += 1
            for spade_i in spade:
                if spade_i.alive_state:
                    spade_alive_num += 1
            if heart_alive_num <= 1:
                print('Spades win!')
                GlobalSituation.__init__(self)
                Pointer.__init__(self)
                chess_pieces_init()
            if spade_alive_num <= 1:
                print('Hearts win!')
                GlobalSituation.__init__(self)
                Pointer.__init__(self)
                chess_pieces_init()
    
    
    heart, spade = [None] * 4, [None] * 4
    for i in range(4):
        heart[i] = ChessPieces('heart')
        spade[i] = ChessPieces('spade')
    
    
    def chess_pieces_init():
        for i in range(4):
            heart[i].pos_y, heart[i].pos_x = 0, i
            spade[i].pos_y, spade[i].pos_x = 3, i
            heart[i].alive_state = True
            spade[i].alive_state = True
    
    chess_pieces_init()
    pointer = Pointer()
    situation = GlobalSituation()
    
    
    def check_click_item(c_x, c_y):
        selected_item = None
        if situation.spade_turn==None:
            for heart_i in heart:
                if heart_i.alive_state and heart_i.rect.collidepoint(c_x, c_y):
                    situation.spade_turn = False
                    selected_item = heart_i
    
            for spade_i in spade:
                if spade_i.alive_state and spade_i.rect.collidepoint(c_x, c_y):
                    situation.spade_turn = True
                    selected_item = spade_i
    
        else:
            if situation.spade_turn:
                for spade_i in spade:
                    if spade_i.alive_state and spade_i.rect.collidepoint(c_x, c_y):
                        selected_item = spade_i
            else:
                for heart_i in heart:
                    if heart_i.alive_state and heart_i.rect.collidepoint(c_x, c_y):
                        selected_item = heart_i
        return selected_item
    
    
    def move_to_dst_pos(selected_item, c_x, c_y):
        update_situation = False
        enemy_exist = False
        if selected_item.name == 'heart':
            for spade_i in spade:
                if spade_i.rect.collidepoint(c_x, c_y) and spade_i.alive_state:
                    enemy_exist = True
        elif selected_item.name == 'spade':
            for heart_i in heart:
                if heart_i.rect.collidepoint(c_x, c_y) and heart_i.alive_state:
                    enemy_exist = True
        if enemy_exist == False:
            delta_y, delta_x = c_y - selected_item.rect[1], c_x - selected_item.rect[0]
            if 80 <= abs(delta_x) <= 120 and abs(delta_y) <= 20:
                if delta_x < 0:
                    if selected_item.pos_x > 0:
                        selected_item.pos_x -= 1
                else:
                    if selected_item.pos_x < 3:
                        selected_item.pos_x += 1
                update_situation = True
            if 80 <= abs(delta_y) <= 120 and abs(delta_x) <= 20:
                if delta_y < 0:
                    if selected_item.pos_y > 0:
                        selected_item.pos_y -= 1
                else:
                    if selected_item.pos_y < 3:
                        selected_item.pos_y += 1
                update_situation = True
        return update_situation
    
    
    while True:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                sys.exit()
            elif event.type == pg.MOUSEBUTTONDOWN:
                cursor_x, cursor_y = pg.mouse.get_pos()
                clicked_item = check_click_item(cursor_x, cursor_y)
                if clicked_item != None:
                    pointer.selecting_item = True
                    pointer.point_to(clicked_item)
                else:
                    if pointer.selecting_item:
                        update_situation_flag = move_to_dst_pos(pointer.pointing_to_item, cursor_x, cursor_y)
                        if update_situation_flag:
                            situation.refresh_situation()
                            situation.check_situation(pointer.pointing_to_item)
                            situation.check_game_over()
                    pointer.selecting_item = False
        screen.blit(background, (0, 0))
        for heart_i in heart:
            heart_i.update()
        for spade_i in spade:
            spade_i.update()
        if pointer.selecting_item:
            pointer.update()
        f_clock.tick(fps)
        pg.display.update()

    五、效果展示

    如何使用Python和Pygame实现走四棋游戏

    本站声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系bd@zhengruan.com
    作者最新文章
    编程开发 Python Pygame
    相关文章 更多
    精品专题 更多
    装机必备

    正软商城装机必备专区,精选办公、浏览器、安全防护、影音播放、压缩解压、设计创作和系统工具等电脑常用正版软件,帮助用户快速完成新电脑软件配置。

    Windows

    正软商城Windows软件专区,汇集适用于Windows电脑的办公、设计、安全防护、影音播放、开发工具和系统优化软件,提供软件介绍、系统要求、正版授权及购买下载服务。

    PDF教程

    正软商城PDF教程频道提供PDF编辑、转换、合并、拆分、压缩及格式处理方法,同时介绍常用PDF软件和工具的使用技巧。

    macOS软件

    正软商城macOS软件专区,精选适用于Mac电脑的办公、设计、影音、效率、开发和系统工具,提供软件功能介绍、macOS兼容版本、正版授权及购买下载服务。

    IOS软件

    正软商城iOS软件专区,精选适用于iPhone和iPad的办公、学习、影音、设计、效率及AI应用,提供功能介绍、适用设备、系统要求和正版获取方式等信息。

    AI

    正软商城AI软件专区,汇集AI写作、AI绘画、AI视频、AI办公、AI编程、AI翻译、智能客服和数据分析等人工智能工具,提供功能介绍、适用平台、收费方式及正版购买信息。

    Mac软件 更多
    Aperty macOS版
    Aperty macOS版

    Aperty 是 Skylum 推出的 AI 人像修图软件,支持自然肤质修饰、瑕疵处理、面部与身体调整、预设及批量同步。

    火山引擎 网页版
    火山引擎 网页版

    火山引擎是字节跳动旗下企业级云与AI服务平台。聚焦大模型核心能力,依托字节自研豆包多模态大模型,凭借火山方舟一站式平台,提供模型精调、推理部署、智能应用搭建等全链路服务,结合高性能AI算力,助力各行业快速落地大模型数字化与智能化应用。

    立刻MV 网页版
    立刻MV 网页版

    立刻MV 面向音乐人、内容创作者和品牌团队,帮助用户低成本完成歌曲 MV、歌词视频、AI 分镜、图生视频与最终合成。

    蛙蛙写作 网页版
    蛙蛙写作 网页版

    蛙蛙写作 AI 创作工具,覆盖小说、剧本、文案,一键生成文稿,打通文字转视频全流程,高效解决创作难题。

    讯飞智作 网页版
    讯飞智作 网页版

    讯飞智作是一款基于语音合成技术、虚拟人驱动技术与数字人形象声音构建能力的 AI 数字人音视频创作平台。

    超级简历WonderCV 网页版
    超级简历WonderCV 网页版

    超级简历WonderCV是面向应届生和AI小白的智能求职平台,覆盖简历、面试与职业规划。

    音述AI 网页版
    音述AI 网页版

    音述AI,是一个以“用声音述说故事”为核心的 AI 音乐创作与声音分享社区。

    AionClaw macOS版
    AionClaw macOS版

    AionClaw 是可在桌面端运行的任务型 AI 助手,通过数字专家与技能市场组合办公、创作、数据和开发能力。

    Loomy macOS版
    Loomy macOS版

    Loomy 是科大讯飞推出的桌面 AI 助手,可通过对话、任务与工作目录协助处理办公、内容创作和资料整理。

    AirBuddy 3 macOS版
    AirBuddy 3 macOS版

    AirBuddy 3 是面向 macOS 的蓝牙外设增强工具,可集中查看 AirPods、Beats 与苹果设备电量,提供快速连接、播放控制、电量提醒、桌面小组件和多台 Mac 外设接力等功能。

    AirServer macOS版
    AirServer macOS版

    AirServer macOS版可把 Mac 转换为无线投屏接收端,通过 AirPlay 或 Google Cast 接收手机、平板和电脑画面,并支持多设备同时连接、高清镜像及会话录制,适合家庭娱乐、课堂教学、会议演示和应用展示。

    AnyDesk macOS版
    AnyDesk macOS版

    AnyDesk macOS版是一款适用于远程办公、设备维护和客户支持的远程桌面工具,可连接并操作异地计算机,支持文件传输、无人值守访问、会话权限控制及跨平台协作。

    WINDOWS 更多
    讯飞绘文 网页版
    讯飞绘文 网页版

    讯飞绘文网页版是科大讯飞推出的AI图文创作与内容运营工具,覆盖热点选题、文章生成、稿件校对、智能配图、排版发布和数据复盘等环节,适合自媒体创作者及内容团队在线使用。

    Maya(Autodesk Maya) Windows版
    Maya(Autodesk Maya) Windows版

    Autodesk Maya 是面向影视、电视、动画和游戏行业的专业三维制作软件,集多边形与 NURBS 建模、角色绑定、关键帧和动作捕捉动画、Bifrost 特效模拟、材质开发及 Arnold 渲染于一体,

    Aperty Windows版
    Aperty Windows版

    Aperty 是 Skylum 推出的 AI 人像修图软件,支持自然肤质修饰、瑕疵处理、面部与身体调整、预设及批量同步。

    火山引擎 网页版
    火山引擎 网页版

    火山引擎是字节跳动旗下企业级云与AI服务平台。聚焦大模型核心能力,依托字节自研豆包多模态大模型,凭借火山方舟一站式平台,提供模型精调、推理部署、智能应用搭建等全链路服务,结合高性能AI算力,助力各行业快速落地大模型数字化与智能化应用。

    立刻MV 网页版
    立刻MV 网页版

    立刻MV 面向音乐人、内容创作者和品牌团队,帮助用户低成本完成歌曲 MV、歌词视频、AI 分镜、图生视频与最终合成。

    蛙蛙写作 网页版
    蛙蛙写作 网页版

    蛙蛙写作 AI 创作工具,覆盖小说、剧本、文案,一键生成文稿,打通文字转视频全流程,高效解决创作难题。

    讯飞智作 网页版
    讯飞智作 网页版

    讯飞智作是一款基于语音合成技术、虚拟人驱动技术与数字人形象声音构建能力的 AI 数字人音视频创作平台。

    超级简历WonderCV 网页版
    超级简历WonderCV 网页版

    超级简历WonderCV是面向应届生和AI小白的智能求职平台,覆盖简历、面试与职业规划。

    音述AI 网页版
    音述AI 网页版

    音述AI,是一个以“用声音述说故事”为核心的 AI 音乐创作与声音分享社区。

    AionClaw Windows版
    AionClaw Windows版

    AionClaw 是可在桌面端运行的任务型 AI 助手,通过数字专家与技能市场组合办公、创作、数据和开发能力。

    Loomy Windows版
    Loomy Windows版

    Loomy 是科大讯飞推出的桌面 AI 助手,可通过对话、任务与工作目录协助处理办公、内容创作和资料整理。

    AirServer Windows版
    AirServer Windows版

    AirServer Windows版可把电脑变成AirPlay、Google Cast和Miracast无线投屏接收端,适合会议演示、课堂教学及家庭大屏分享。发送设备通常无需另装客户端,并可同时接收和智能排列多个镜像会话。