欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

x01.xiangqi: 走动棋子

程序员文章站 2022-03-20 19:23:12
采用 pygame 写的象棋程序,目前只完成绘制棋盘与走动棋子,还没考虑规则等问题。 1. 代码: """ x01.xiangqi (c) 2019 by x01""" import os, sys, pygame from pygame.locals import * BaseDir = os.p ......

采用 pygame 写的象棋程序,目前只完成绘制棋盘与走动棋子,还没考虑规则等问题。

1. 代码:

""" x01.xiangqi (c) 2019 by x01"""

import os, sys, pygame 
from pygame.locals import *

basedir = os.path.dirname(os.path.abspath(__file__))
imagepath = basedir + '/res/'

boardwidth = 520
boardheight = 576
boardedge = 8
piecesize = 56

# piece type
king = 0
advisor = 1
bishop = 2
knight = 3
rook = 4
cannon = 5
pawn = 6
selected = 7

# piece types
types = [
    20, 19, 18, 17, 16, 17, 18, 19, 20, 
    0,  0,  0,  0,  0,  0,  0,  0,  0, 
    0, 21,  0,  0,  0,  0,  0, 21,  0, 
    22,  0, 22,  0, 22,  0, 22,  0, 22,
    0,  0,  0,  0,  0,  0,  0,  0,  0, 
    0,  0,  0,  0,  0,  0,  0,  0,  0, 
    14,  0, 14,  0, 14,  0, 14,  0, 14,
    0, 13,  0,  0,  0,  0,  0, 13,  0, 
    0,  0,  0,  0,  0,  0,  0,  0,  0, 
    12, 11, 10,  9,  8,  9, 10, 11, 12
]

class piece(object):
    def __init__(self, player, ptype, name, pos):
        self.player = player 
        self.ptype = ptype 
        self.name = name 
        self.pos = pos 

pieces = [
    # black
    piece(0, king, "bk.bmp", (4,0)), 
    piece(0, advisor, "ba.bmp", (3,0)),piece(0, advisor, "ba.bmp", (5,0)), 
    piece(0, bishop, "bb.bmp", (2,0)), piece(0, bishop, "bb.bmp", (6,0)),
    piece(0, knight, "bn.bmp", (1,0)), piece(0, knight, "bn.bmp", (7,0)),
    piece(0, rook, "br.bmp", (0,0)), piece(0, rook, "br.bmp", (8,0)),
    piece(0, cannon, "bc.bmp", (1,2)), piece(0, cannon, "bc.bmp", (7,2)), 
    piece(0, pawn, "bp.bmp", (0,3)), piece(0, pawn, "bp.bmp", (2,3)),
    piece(0, pawn, "bp.bmp", (4,3)),piece(0, pawn, "bp.bmp", (6,3)),piece(0, pawn, "bp.bmp", (8,3)),
    
    # red
    piece(1, king, "rk.bmp", (4,9)), 
    piece(1, advisor, "ra.bmp", (3,9)),piece(1, advisor, "ra.bmp", (5,9)), 
    piece(1, bishop, "rb.bmp", (2,9)), piece(1, bishop, "rb.bmp", (6,9)),
    piece(1, knight, "rn.bmp", (1,9)), piece(1, knight, "rn.bmp", (7,9)),
    piece(1, rook, "rr.bmp", (0,9)), piece(1, rook, "rr.bmp", (8,9)),
    piece(1, cannon, "rc.bmp", (1,7)), piece(1, cannon, "rc.bmp", (7,7)), 
    piece(1, pawn, "rp.bmp", (0,6)), piece(1, pawn, "rp.bmp", (2,6)),
    piece(1, pawn, "rp.bmp", (4,6)),piece(1, pawn, "rp.bmp", (6,6)),piece(1, pawn, "rp.bmp", (8,6)),

    # selected
    piece(2, selected, 'selected.bmp', (0,0))
]

# type index
def index(pos):
    col,row = pos[0], pos[1]
    return row * 9 + col

def draw(surface, name, xy, ispiece=true):
    img = pygame.image.load(imagepath + name).convert()
    if ispiece:
        img.set_colorkey((0,255,0))
    surface.blit(img, xy)

def draw_pieces(surface):
    for p in pieces[:-1]:
        x = p.pos[0] * piecesize + boardedge
        y = p.pos[1] * piecesize + boardedge
        draw(surface, p.name, (x,y))

def run():
    pygame.init()
    screen = pygame.display.set_mode((boardwidth, boardheight),0,32)
    pygame.display.set_caption('x01.xiangqi')
    draw(screen, 'board.bmp', (0,0), false)
    draw_pieces(screen)
    
    prevpiece = none 
    player = 1
    clock = pygame.time.clock()
    while true:
        for event in pygame.event.get():
            if event.type == quit:
                sys.exit()
            if event.type == keydown:
                if event.key == k_escape:
                    sys.exit()
            if event.type == mousebuttondown:
                x,y = pygame.mouse.get_pos()
                x,y = ((x // piecesize) * piecesize + boardedge, (y//piecesize)*piecesize + boardedge)
                pos = (x//piecesize, y//piecesize)
                
                draw(screen,'board.bmp',(0,0),false)
                draw_pieces(screen)    
                pieces[-1].pos = pos
                draw(screen, pieces[-1].name, (x,y))

                for p in pieces[:-1]:
                    if p.pos == pos:
                        prevpiece = p
                        break
                
                if types[index(pos)] == 0 and prevpiece != none:
                    if player != prevpiece.player:
                        continue
                    player = 1 - player
                    if prevpiece.player == 0:
                        types[index(pos)] = prevpiece.ptype + 16
                    elif prevpiece.player == 1:
                        types[index(pos)] = prevpiece.ptype + 8
                    types[index(prevpiece.pos)] = 0
                    for p in pieces[:-1]:
                        if p.pos == prevpiece.pos:
                            p.pos = pos 
                            break
                    prevpiece = none 
                    
                    draw(screen,'board.bmp',(0,0),false)
                    draw_pieces(screen)        
                    draw(screen, pieces[-1].name, (x,y))

        clock.tick(40)
        pygame.display.update()
        

if __name__ == '__main__':
    run()

2. 效果图:

                   x01.xiangqi: 走动棋子

3. 下载链接:(x01.lab => py => xiangqi)

附: md 批量转换到 pdf 文件

  a) 需安装 pandoc, 拷贝 template.tex 到 /usr/share/pandoc/data/templates/ 目录中。

  b) 需安装中文字体。

  c) 需安装 xelatex.

  d) 代码 md2pdfs.py 及模板 template.tex 如下:

from pathlib import path
import os

def md2pdfs(currdir='.'):
    dir = os.path.abspath(currdir)
    files = os.listdir(dir) 
    for f in files:
        path = os.path.join(dir, f)
        if os.path.isdir(path):
            md2pdfs(path)
            dir = os.path.dirname(path)
            continue
        name = os.path.splitext(f)[0]
        ext = os.path.splitext(f)[1]
        if ext == '.md':
            mdfile = f
            pdffile = name + '.pdf'
            os.chdir(dir)
            print(os.getcwd() + '/' + f)
            cmd = "pandoc '{0}' -o '{1}' --latex-engine=xelatex -v mainfont='pingfang sc' --template=template.tex".format(mdfile, pdffile)
            os.system(cmd)
        
        

if __name__ == '__main__':
    md2pdfs()
\documentclass[12pt]{article}
\usepackage{xecjk}
\setcjkmainfont{simsun}
$if(fontfamily)$
\usepackage{$fontfamily$}
$else$
\usepackage{lmodern}
$endif$
$if(linestretch)$
\usepackage{setspace}
\setstretch{$linestretch$}
$endif$

% 图片设置
\usepackage{graphicx}
% 可以指定根目录下的image文件夹为图片文件夹
\graphicspath{{image/}}

% 页面设置
\usepackage[a4paper]{geometry}
\geometry{
    left=2.54cm,
    right=2.54cm,
    top=3.18cm,
    bottom=3.18cm,
    footskip=1.48cm,
    headsep=.5cm,
    headheight=1.5cm
}

\usepackage{amssymb,amsmath}
\usepackage{ifxetex,ifluatex}
\usepackage{fixltx2e} % provides \textsubscript
\ifnum 0\ifxetex 1\fi\ifluatex 1\fi=0 % if pdftex
  \usepackage[t1]{fontenc}
  \usepackage[utf8]{inputenc}
$if(euro)$
  \usepackage{eurosym}
$endif$
\else % if luatex or xelatex
  \ifxetex
    \usepackage{xltxtra,xunicode}
  \else
    \usepackage{fontspec}
  \fi
  \defaultfontfeatures{mapping=tex-text,scale=matchlowercase}
  \newcommand{\euro}{€}

% $if(mainfont)$
%     \setmainfont{$mainfont$}
% $endif$
% $if(sansfont)$
%     \setsansfont{$sansfont$}
% $endif$
% $if(monofont)$
%     \setmonofont[mapping=tex-ansi]{$monofont$}
% $endif$
% $if(cjkmainfont)$
%     \usepackage{xecjk}
%     \setcjkmainfont[$cjkoptions$]{$cjkmainfont$}
% $endif$


% 字体的设置,可以自行修改
% \usepackage{xecjk}
% 【推荐】第一种设置
% xelatex在编译时会自动选择思源宋体的bold部分
% 不设置monofont,因为有些字符在其他指定字符的出现变形,不如默认字体美观
% \setcjkmainfont{思源宋体 cn}
% \setcjksansfont{思源黑体 cn}
% \setmainfont{思源宋体 cn}
% \setsansfont{思源黑体 cn}
% 【列示】第二种设置
% \setcjkmainfont{思源宋体}[boldfont = 思源黑体 regular]
%\setcjkmonofont{思源黑体 light}
% \setcjksansfont{思源黑体 regular}
% \setmainfont{ibm plex serif}
% \setmonofont{ibm plex mono}
% \setsansfont{ibm plex sans}


\fi
% use upquote if available, for straight quotes in verbatim environments
\iffileexists{upquote.sty}{\usepackage{upquote}}{}
% use microtype if available
\iffileexists{microtype.sty}{%
\usepackage{microtype}
\usemicrotypeset[protrusion]{basicmath} % disable protrusion for tt fonts
}{}

\ifxetex
  \usepackage[setpagesize=false, % page size defined by xetex
              unicode=false, % unicode breaks when used with xetex
              xetex]{hyperref}
\else
  \usepackage[unicode=true]{hyperref}
\fi
\usepackage[usenames,dvipsnames]{color}
\hypersetup{breaklinks=true,
            bookmarks=true,
            pdfauthor={$author-meta$},
            pdftitle={$title-meta$},
            colorlinks=true,
            citecolor=$if(citecolor)$$citecolor$$else$blue$endif$,
            urlcolor=$if(urlcolor)$$urlcolor$$else$blue$endif$,
            linkcolor=$if(linkcolor)$$linkcolor$$else$magenta$endif$,
            pdfborder={0 0 0}}
\urlstyle{same}  % don't use monospace font for urls
$if(lang)$
\ifxetex
  \usepackage{polyglossia}
  \setmainlanguage{$mainlang$}
  \setotherlanguages{$for(otherlang)$$otherlang$$sep$,$endfor$}
\else
  \usepackage[shorthands=off,$lang$]{babel}
\fi
$endif$
$if(natbib)$
\usepackage{natbib}
\bibliographystyle{$if(biblio-style)$$biblio-style$$else$plainnat$endif$}
$endif$
$if(biblatex)$
\usepackage{biblatex}
$for(bibliography)$
\addbibresource{$bibliography$}
$endfor$
$endif$
$if(listings)$
\usepackage{listings}
$endif$
$if(lhs)$
\lstnewenvironment{code}{\lstset{language=haskell,basicstyle=\small\ttfamily}}{}
$endif$
$if(highlighting-macros)$
$highlighting-macros$
$endif$
$if(verbatim-in-note)$
\usepackage{fancyvrb}
\verbatimfootnotes
$endif$
$if(tables)$
\usepackage{longtable,booktabs}
$endif$
$if(graphics)$
\usepackage{graphicx,grffile}
\makeatletter
\def\maxwidth{\ifdim\gin@nat@width>\linewidth\linewidth\else\gin@nat@width\fi}
\def\maxheight{\ifdim\gin@nat@height>\textheight\textheight\else\gin@nat@height\fi}
\makeatother
% scale images if necessary, so that they will not overflow the page
% margins by default, and it is still possible to overwrite the defaults
% using explicit options in \includegraphics[width, height, ...]{}
\setkeys{gin}{width=\maxwidth,height=\maxheight,keepaspectratio}
$endif$
$if(links-as-notes)$
% make links footnotes instead of hotlinks:
\renewcommand{\href}[2]{#2\footnote{\url{#1}}}
$endif$
$if(strikeout)$
\usepackage[normalem]{ulem}
% avoid problems with \sout in headers with hyperref:
\pdfstringdefdisablecommands{\renewcommand{\sout}{}}
$endif$
\setlength{\emergencystretch}{3em}  % prevent overfull lines
\providecommand{\tightlist}{%
  \setlength{\itemsep}{0pt}\setlength{\parskip}{0pt}}
$if(numbersections)$
\setcounter{secnumdepth}{5}
$else$
\setcounter{secnumdepth}{0}
$endif$
$if(verbatim-in-note)$
\verbatimfootnotes % allows verbatim text in footnotes
$endif$

$if(title)$
\title{\bfseries \huge $title$$if(subtitle)$\\\vspace{0.5cm}{\large  $subtitle$}$endif$}
$endif$
$if(author)$
\author{\large $for(author)$$author$$sep$ \and $endfor$}
$endif$
\date{{\large \today}}
$for(header-includes)$
$header-includes$
$endfor$

% redefines (sub)paragraphs to behave more like sections
\ifx\paragraph\undefined\else
\let\oldparagraph\paragraph
\renewcommand{\paragraph}[1]{\oldparagraph{#1}\mbox{}}
\fi
\ifx\subparagraph\undefined\else
\let\oldsubparagraph\subparagraph
\renewcommand{\subparagraph}[1]{\oldsubparagraph{#1}\mbox{}}
\fi

\begin{document}
$if(title)$
\maketitle
$endif$
$if(abstract)$
\begin{abstract}
$abstract$
\end{abstract}
$endif$

$for(include-before)$
$include-before$

$endfor$
$if(toc)$
{
\setcounter{tocdepth}{$toc-depth$}
\tableofcontents
}
$endif$
$if(lot)$
\listoftables
$endif$
$if(lof)$
\listoffigures
$endif$
$body$

$if(natbib)$
$if(bibliography)$
$if(biblio-title)$
$if(book-class)$
\renewcommand\bibname{$biblio-title$}
$else$
\renewcommand\refname{$biblio-title$}
$endif$
$endif$
\bibliography{$for(bibliography)$$bibliography$$sep$,$endfor$}

$endif$
$endif$
$if(biblatex)$
\printbibliography$if(biblio-title)$[title=$biblio-title$]$endif$

$endif$
$for(include-after)$
$include-after$

$endfor$
\end{document}