用Python3写一个中国象棋游戏

一:目的

就是为了熟悉Python语法

二:效果

用Python3写一个中国象棋游戏

三:使用方式

1.用Python3运行里面的main.py即可;

2.wdsa和上右下左键控制光标移动;空格键选中棋子,再按则是相当于移动棋子,如果在原地再按空格键取消选中;

3.按q结束游戏,或者吃了主帅后结束游戏

四:源码

https://github.com/silentdoer/chinese_chess_python3

支持Linux和Windows(我这边用ubuntu18.04和Win10 Powershell测试的,如果是其他终端不能保证布局会像GIF中的那样整齐,但是功能肯定是没问题的)

五:源码介绍

1.首先需要一个能够实时获取按键的工具方法/工具类,否则每次按完上下左右等功能按键后都要按Enter键太不方便,代码如下:

class Getch():
    """ 用来实现不需要按enter键读取输入字符 """

    def __init__(self):
        import platform
        system_name = platform.system()
        if system_name == 'Windows':
            self.impl = GetchWindows()
        else:  # 默认是Linux(目前就支持Windows和Linux即可)
            self.impl = GetchUnix()

    def __call__(self): return self.impl()


class GetchUnix:
    def __init__(self):
        pass

    def __call__(self):
        # 不要用import sys, tty这种逗号的方式导入
        import sys
        import tty
        import termios
        fd = sys.stdin.fileno()
        old_settings = termios.tcgetattr(fd)
        try:
            tty.setraw(sys.stdin.fileno())
            ch = sys.stdin.read(1)
        finally:
            termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
        return ch


class GetchWindows:
    def __init__(self):
        pass

    def __call__(self):
        import msvcrt
        return msvcrt.getch()

通过getch()就能实时获取按下的按键

2.通过一个公共模块来实现清屏和打印颜色文本的操作,代码如下:

def printc(new_line, content, forecolor='', backcolor=''):
    if forecolor != '':
        forecolor = ';' + forecolor
    if backcolor != '':
        backcolor = ';' + backcolor

    flag = ''
    if new_line:
        flag = '
'
    print('