AI 部分由 C++ 重写,效率高了不少。
好像不是很聪明,谁都打不过 qwq。
把 C++ 文件和 python 文件放在同一个目录下。
C++ 编译指令:g++ -static -shared -o chesslib.dll chesslib.cpp -s -Ofast -Wl,-stack=2147483647 -std=c++14
python 需要 pygame 模块,在命令行里输入 pip install pygame 下载一个就行了。
如果 python 加载 dll 时报错就换一个编译器吧。
原来的代码有变量爆 int 了,稍微修了一下。
chesslib.cpp
#include <array>
#include <chrono>
#include <random>
#include <vector>
#include <algorithm>
using namespace std;
mt19937 rnd(random_device{}());
using ui=unsigned;
constexpr int chief=0,bodyguard=1,elephant=2,horse=3,chariot=4,cannon=5,soldier=6;
constexpr int maximumHistoricalMoves=256;
constexpr int maximumSearchDepth=64;
constexpr int checkmateScore=10000;
constexpr int perpetualCheckNegativeScore=checkmateScore-100;
constexpr int scoreBoundaryVictoryAndDefeat=checkmateScore-200;
constexpr int scoreDuringDrawNegative=20;
constexpr int priorityScore=3;
constexpr int randomScore=7;
constexpr int emptyStepCutForceBorder=400;
constexpr int emptyStepCutDepth=2;
constexpr int maximumPermutationTableSize=1048576;
constexpr int AlphaPermutationTableEntry=1;
constexpr int BetaPermutationTableEntry=2;
constexpr int PVPermutationTableEntry=3;
constexpr array<int,256> isOnChessboardList{
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,1,1,1,1,1,1,1,1,1,0,0,0,0,
0,0,0,1,1,1,1,1,1,1,1,1,0,0,0,0,
0,0,0,1,1,1,1,1,1,1,1,1,0,0,0,0,
0,0,0,1,1,1,1,1,1,1,1,1,0,0,0,0,
0,0,0,1,1,1,1,1,1,1,1,1,0,0,0,0,
0,0,0,1,1,1,1,1,1,1,1,1,0,0,0,0,
0,0,0,1,1,1,1,1,1,1,1,1,0,0,0,0,
0,0,0,1,1,1,1,1,1,1,1,1,0,0,0,0,
0,0,0,1,1,1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,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0
};
constexpr array<int,4> chiefStep={-16, -1, 1, 16};
constexpr array<int,4> bodyguardStep={-17, -15, 15, 17};
constexpr array<array<int,2>,4> horseLegUseChiefStep={{{-33, -31},{-18, 14},{-14, 18},{31, 33}}};
constexpr array<array<int,2>,4> horseLegUseBodyguardStep={{{-33, -18},{-31, -14},{14, 31},{18, 33}}};
// Initialize chessboard
constexpr array<int,256> initialChessboard{
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0,20,19,18,17,16,17,18,19,20, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0,21, 0, 0, 0, 0, 0,21, 0, 0, 0, 0, 0,
0, 0, 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, 0, 0,
0, 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, 0, 0, 0,
0, 0, 0, 0,13, 0, 0, 0, 0, 0,13, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0,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0, 0,
0, 0, 0, 93, 92, 94, 95, 92, 95, 94, 92, 93, 0, 0, 0, 0,
0, 0, 0, 85, 90, 92, 93, 78, 93, 92, 90, 85, 0, 0, 0, 0,
0, 0, 0, 88, 85, 90, 88, 90, 88, 90, 85, 88, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
},{ //车
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0,206,208,207,213,214,213,207,208,206, 0, 0, 0, 0,
0, 0, 0,206,212,209,216,233,216,209,212,206, 0, 0, 0, 0,
0, 0, 0,206,208,207,214,216,214,207,208,206, 0, 0, 0, 0,
0, 0, 0,206,213,213,216,216,216,213,213,206, 0, 0, 0, 0,
0, 0, 0,208,211,211,214,215,214,211,211,208, 0, 0, 0, 0,
0, 0, 0,208,212,212,214,215,214,212,212,208, 0, 0, 0, 0,
0, 0, 0,204,209,204,212,214,212,204,209,204, 0, 0, 0, 0,
0, 0, 0,198,208,204,212,212,212,204,208,198, 0, 0, 0, 0,
0, 0, 0,200,208,206,212,200,212,206,208,200, 0, 0, 0, 0,
0, 0, 0,194,206,204,212,200,212,204,206,194, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
},{ //炮
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0,100,100, 96, 91, 90, 91, 96,100,100, 0, 0, 0, 0,
0, 0, 0, 98, 98, 96, 92, 89, 92, 96, 98, 98, 0, 0, 0, 0,
0, 0, 0, 97, 97, 96, 91, 92, 91, 96, 97, 97, 0, 0, 0, 0,
0, 0, 0, 96, 99, 99, 98,100, 98, 99, 99, 96, 0, 0, 0, 0,
0, 0, 0, 96, 96, 96, 96,100, 96, 96, 96, 96, 0, 0, 0, 0,
0, 0, 0, 95, 96, 99, 96,100, 96, 99, 96, 95, 0, 0, 0, 0,
0, 0, 0, 96, 96, 96, 96, 96, 96, 96, 96, 96, 0, 0, 0, 0,
0, 0, 0, 97, 96,100, 99,101, 99,100, 96, 97, 0, 0, 0, 0,
0, 0, 0, 96, 97, 98, 98, 98, 98, 98, 97, 96, 0, 0, 0, 0,
0, 0, 0, 96, 96, 97, 99, 99, 99, 97, 96, 96, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
},{ //兵(卒)
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 9, 9, 9, 11, 13, 11, 9, 9, 9, 0, 0, 0, 0,
0, 0, 0, 19, 24, 34, 42, 44, 42, 34, 24, 19, 0, 0, 0, 0,
0, 0, 0, 19, 24, 32, 37, 37, 37, 32, 24, 19, 0, 0, 0, 0,
0, 0, 0, 19, 23, 27, 29, 30, 29, 27, 23, 19, 0, 0, 0, 0,
0, 0, 0, 14, 18, 20, 27, 29, 27, 20, 18, 14, 0, 0, 0, 0,
0, 0, 0, 7, 0, 13, 0, 16, 0, 13, 0, 7, 0, 0, 0, 0,
0, 0, 0, 7, 0, 7, 0, 15, 0, 7, 0, 7, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
}}};
constexpr inline bool isOnChessboard(int pos){
return isOnChessboardList[pos]!=0;
}
constexpr inline bool isInGrid(int pos){
return isInGridList[pos]!=0;
}
constexpr inline int getx(int pos){
return pos&15;
}
constexpr inline int gety(int pos){
return pos>>4;
}
constexpr inline int posToGrid(int x,int y){
return x+(y<<4);
}
constexpr inline int mousePosToGrid(int x,int y){
return (x+3)+((y+3)<<4);
}
constexpr inline int flipGrid(int pos){
return 254-pos;
}
constexpr inline int forwardPos(int pos,int turn){
return pos-16+(turn<<5);
}
constexpr inline bool checkChief(int start,int end){
return stepMatchWalkingMethodList[end-start+256]==1;
}
constexpr inline bool checkBodyguard(int start,int end){
return stepMatchWalkingMethodList[end-start+256]==2;
}
constexpr inline bool checkElephant(int start,int end){
return stepMatchWalkingMethodList[end-start+256]==3;
}
constexpr inline int elephantEye(int start,int end){
return (start+end)>>1;
}
constexpr inline int horseLeg(int start,int end){
return start+horseLameLegList[end-start+256];
}
constexpr inline bool notCrossedRiver(int pos,int turn){
return (pos&0x80)!=(turn<<7);
}
constexpr inline bool crossedRiver(int pos,int turn){
return (pos&0x80)==(turn<<7);
}
constexpr inline bool onTheSameSide(int start,int end){
return ((start^end)&0x80)==0;
}
constexpr inline bool onTheSameLine(int start,int end){
return ((start^end)&0xf0)==0;
}
constexpr inline bool onTheSameColumn(int start,int end){
return ((start^end)&0x0f)==0;
}
constexpr inline int getRedBlackMark(int turn){
return 8+(turn<<3);
}
constexpr inline int getOpponentRedBlackMark(int turn){
return 16-(turn<<3);
}
constexpr inline int getStart(int method){
return method&255;
}
constexpr inline int getEnd(int method){
return method>>8;
}
constexpr inline int getMethod(int start,int end){
return start+(end<<8);
}
constexpr inline int revMethod(int method){
return getMethod(getEnd(method),getStart(method));
}
class RC4CipherStreamGenerator{
private:
array<ui,256> s;
int x,y;
public:
RC4CipherStreamGenerator():x(0),y(0){
for (int i=0;i<256;++i) s[i]=i;
}
void initCSG(){
x=y=0;
int j=0;
for (int i=0;i<256;++i){
j=(j+s[i])&255;
swap(s[i],s[j]);
}
}
ui generateNextByte(){
x=(x+1)&255;
y=(y+s[x])&255;
swap(s[x],s[y]);
return s[(s[x]+s[y])&255];
}
ui generateNext4Bytes(){
ui uc0=generateNextByte();
ui uc1=generateNextByte();
ui uc2=generateNextByte();
ui uc3=generateNextByte();
return uc0+(uc1<<8)+(uc2<<16)+(uc3<<24);
}
};
class ZobristStructure{
public:
ui duplicateSituationCheckCode;
ui permutationTableCheckCode;
void fillWithZeros(){
duplicateSituationCheckCode=permutationTableCheckCode=0;
}
ZobristStructure(){
fillWithZeros();
}
void fillWithCipherStream(RC4CipherStreamGenerator &generator){
duplicateSituationCheckCode=generator.generateNext4Bytes();
permutationTableCheckCode=generator.generateNext4Bytes();
}
void XOROperation(const ZobristStructure &checkcode){
duplicateSituationCheckCode^=checkcode.duplicateSituationCheckCode;
permutationTableCheckCode^=checkcode.permutationTableCheckCode;
}
};
class ZobristTable{
public:
static ZobristStructure ZobristPlayer;
static array<array<ZobristStructure,256>,14> desktop;
};
ZobristStructure ZobristTable::ZobristPlayer;
array<array<ZobristStructure,256>,14> ZobristTable::desktop{};
void initZobristTable(){
RC4CipherStreamGenerator RC4Generator;
RC4Generator.initCSG();
ZobristTable::ZobristPlayer.fillWithCipherStream(RC4Generator);
for (int i=0;i<14;++i){
for (int j=0;j<256;++j){
ZobristTable::desktop[i][j].fillWithCipherStream(RC4Generator);
}
}
}
class HistoricalRouteInformation{
public:
int bestMove;
int previousStepEating;
int checkmate;
ui duplicateSituationCheckCode;
HistoricalRouteInformation():bestMove(0),previousStepEating(0),checkmate(0),duplicateSituationCheckCode(0){}
void setHistoricalRoute(int _thisMove,int _previousStepEating,int _checkmate,ui _duplicateSituationCheckCode){
bestMove=_thisMove;
previousStepEating=_previousStepEating;
checkmate=_checkmate;
duplicateSituationCheckCode=_duplicateSituationCheckCode;
}
};
class SituationStructure{
public:
int turn;
array<int,256> chessboard;
int redForce,blackForce;
int distanceToRoot,historicalMovementsNumber;
array<HistoricalRouteInformation,maximumHistoricalMoves> historicalRoutingInformationTable;
ZobristStructure checkCode;
SituationStructure(){
turn=redForce=blackForce=distanceToRoot=historicalMovementsNumber=0;
chessboard.fill(0);
historicalRoutingInformationTable.fill(HistoricalRouteInformation());
checkCode.fillWithZeros();
}
void clear(){
turn=redForce=blackForce=distanceToRoot=0;
chessboard.fill(0);
checkCode.fillWithZeros();
}
void initHistoricalRoutingInformation(){
historicalRoutingInformationTable[0].setHistoricalRoute(0,0,isCheckmated(),checkCode.duplicateSituationCheckCode);
historicalMovementsNumber=1;
}
void initChessboard(){
clear();
for (int i=0;i<256;++i){
int j=initialChessboard[i];
if (j!=0) fallChess(i,j);
}
initHistoricalRoutingInformation();
}
void swapPlayer(){
turn=1-turn;
checkCode.XOROperation(ZobristTable::ZobristPlayer);
}
void fallChess(int pos,int i){
chessboard[pos]=i;
if (i<16){
redForce+=forcePositionValue[i-8][pos];
checkCode.XOROperation(ZobristTable::desktop[i-8][pos]);
}else{
blackForce+=forcePositionValue[i-16][flipGrid(pos)];
checkCode.XOROperation(ZobristTable::desktop[i-9][pos]);
}
}
void takeChess(int pos,int i){
chessboard[pos]=0;
if (i<16){
redForce-=forcePositionValue[i-8][pos];
checkCode.XOROperation(ZobristTable::desktop[i-8][pos]);
}else{
blackForce-=forcePositionValue[i-16][flipGrid(pos)];
checkCode.XOROperation(ZobristTable::desktop[i-9][pos]);
}
}
int situationAssessment(){
return (redForce-blackForce)*(turn==0?1:-1)+priorityScore;
}
bool isCheckmatedByHistoryTable(){
return historicalRoutingInformationTable[historicalMovementsNumber-1].checkmate;
}
bool eatPreviousStep(){
return historicalRoutingInformationTable[historicalMovementsNumber-1].previousStepEating!=0;
}
int moveChess(int method){
int start=getStart(method),end=getEnd(method);
int tag=chessboard[end];
if (tag!=0) takeChess(end,tag);
int i=chessboard[start];
takeChess(start,i);
fallChess(end,i);
return tag;
}
void revokeMoveChess(int method,int tag){
int start=getStart(method),end=getEnd(method);
int i=chessboard[end];
takeChess(end,i);
fallChess(start,i);
if (tag!=0) fallChess(end,tag);
}
bool makeAMove(int method,bool force=false){
ui code=checkCode.duplicateSituationCheckCode;
int eaten=moveChess(method);
if (isCheckmated()){
if (!force) revokeMoveChess(method,eaten);
return false;
}
swapPlayer();
historicalRoutingInformationTable[historicalMovementsNumber].setHistoricalRoute(method,eaten,isCheckmated(),code);
historicalMovementsNumber++;
distanceToRoot++;
return true;
}
void revokeMakeAMove(){
distanceToRoot--;
historicalMovementsNumber--;
swapPlayer();
auto tmp=historicalRoutingInformationTable[historicalMovementsNumber];
revokeMoveChess(tmp.bestMove,tmp.previousStepEating);
}
void emptyMove(){
ui code=checkCode.duplicateSituationCheckCode;
swapPlayer();
historicalRoutingInformationTable[historicalMovementsNumber].setHistoricalRoute(0,0,false,code);
historicalMovementsNumber++;
distanceToRoot++;
}
void revokeEmptyMove(){
distanceToRoot--;
historicalMovementsNumber--;
swapPlayer();
}
vector<int> generateAllRoutes(bool eatOnly=false){
vector<int> generates;
int MyMark=getRedBlackMark(turn);
int OpponentMark=getOpponentRedBlackMark(turn);
for (int start=0;start<256;++start){
int startChess=chessboard[start];
if ((startChess&MyMark)==0) continue;
int chess=startChess-MyMark;
if (chess==chief){
for (int i=0;i<4;++i){
int end=start+chiefStep[i];
if (!isInGrid(end)) continue;
int endChess=chessboard[end];
if (eatOnly?(endChess&OpponentMark)!=0:(endChess&MyMark)==0){
generates.push_back(getMethod(start,end));
}
}
}else if (chess==bodyguard){
for (int i=0;i<4;++i){
int end=start+bodyguardStep[i];
if (!isInGrid(end)) continue;
int endChess=chessboard[end];
if (eatOnly?(endChess&OpponentMark)!=0:(endChess&MyMark)==0){
generates.push_back(getMethod(start,end));
}
}
}else if (chess==elephant){
for (int i=0;i<4;++i){
int end=start+bodyguardStep[i];
if (!(isOnChessboard(end) and !crossedRiver(end,turn) and chessboard[end]==0)) continue;
end+=bodyguardStep[i];// Move two steps to the final position
int endChess=chessboard[end];
if (eatOnly?(endChess&OpponentMark)!=0:(endChess&MyMark)==0){
generates.push_back(getMethod(start,end));
}
}
}else if (chess==horse){
for (int i=0;i<4;++i){
int end=start+chiefStep[i];
if (chessboard[end]!=0) continue; // Check if the horse is blocked
for (int j=0;j<2;++j){
end=start+horseLegUseChiefStep[i][j];
if (!isOnChessboard(end)) continue;
int endChess=chessboard[end];
if (eatOnly?(endChess&OpponentMark)!=0:(endChess&MyMark)==0){
generates.push_back(getMethod(start,end));
}
}
}
}else if (chess==chariot){
for (int i=0;i<4;++i){
int offset=chiefStep[i];
int end=start+offset;
while (isOnChessboard(end)){
int endChess=chessboard[end];
if (endChess==0){
if (!eatOnly) generates.push_back(getMethod(start,end));
}else{
if ((endChess&OpponentMark)!=0) generates.push_back(getMethod(start,end));
break;
}
end+=offset;
}
}
}else if (chess==cannon){
for (int i=0;i<4;++i){
int offset=chiefStep[i];
int end=start+offset;
while (isOnChessboard(end)){
int endChess=chessboard[end];
if (endChess==0){
if (!eatOnly) generates.push_back(getMethod(start,end));
}else{
break;
}
end+=offset;
}
end+=offset;
while (isOnChessboard(end)){
int endChess=chessboard[end];
if (endChess!=0){
if ((endChess&OpponentMark)!=0) generates.push_back(getMethod(start,end));
break;
}
end+=offset;
}
}
}else if (chess==soldier){
int end=forwardPos(start,turn);
if (isOnChessboard(end)){
int endChess=chessboard[end];
if (eatOnly?(endChess&OpponentMark)!=0:(endChess&MyMark)==0){
generates.push_back(getMethod(start,end));
}
}
if (crossedRiver(start,turn)){
for (int offset=-1;offset<=1;offset+=2){
end=start+offset;
if (isOnChessboard(end)){
int endChess=chessboard[end];
if (eatOnly?(endChess&OpponentMark)!=0:(endChess&MyMark)==0){
generates.push_back(getMethod(start,end));
}
}
}
}
}
}
return generates;
}
bool moveAllow(int method){
int start=getStart(method);
int startChess=chessboard[start];
int MyMark=getRedBlackMark(turn);
if ((startChess&MyMark)==0) return false;
int end=getEnd(method);
int endChess=chessboard[end];
if ((endChess&MyMark)!=0) return false;
int chess=startChess-MyMark;
if (chess==chief){
return isInGrid(end) and checkChief(start,end);
}else if (chess==bodyguard){
return isInGrid(end) and checkBodyguard(start,end);
}else if (chess==elephant){
return onTheSameSide(start,end) and checkElephant(start,end) and chessboard[elephantEye(start,end)]==0;
}else if (chess==horse){
int obstacleOffset=horseLeg(start,end);
return obstacleOffset!=start and chessboard[obstacleOffset]==0;
}else if (chess==chariot or chess==cannon){
int offset;
if (onTheSameLine(start,end)){
offset=(end<start)?-1:1;
}else if (onTheSameColumn(start,end)){
offset=(end<start)?-16:16;
}else{
return false;
}
int obstacleOffset=start+offset;
while (obstacleOffset!=end and chessboard[obstacleOffset]==0){
obstacleOffset+=offset;
}
if (obstacleOffset==end){
return endChess==0 or startChess-MyMark==chariot;
}else if (endChess!=0 and startChess-MyMark==cannon){
obstacleOffset+=offset;
while (obstacleOffset!=end and chessboard[obstacleOffset]==0){
obstacleOffset+=offset;
}
return obstacleOffset==end;
}else{
return false;
}
}else if (chess==soldier){
if (crossedRiver(end,turn) and (end==start-1 or end==start+1)) return true;
return end==forwardPos(start,turn);
}else{
return false;
}
}
bool isCheckmated(){
int MyMark=getRedBlackMark(turn);
int OpponentMark=getOpponentRedBlackMark(turn);
for (int start=0;start<256;++start){
if (chessboard[start]!=MyMark+chief) continue;
if (chessboard[forwardPos(start,turn)]==OpponentMark+soldier) return true;
for (int offset=-1;offset<=1;offset+=2){
if (chessboard[start+offset]==OpponentMark+soldier) return true;
}
for (int i=0;i<4;++i){
if (chessboard[start+bodyguardStep[i]]!=0) continue;
for (int j=0;j<2;++j){
int endChess=chessboard[start+horseLegUseBodyguardStep[i][j]];
if (endChess==OpponentMark+horse) return true;
}
}
for (int i=0;i<4;++i){
int offset=chiefStep[i];
int end=start+offset;
while (isOnChessboard(end)){
int endChess=chessboard[end];
if (endChess!=0){
if (endChess==OpponentMark+chariot or endChess==OpponentMark+chief) return true;
break;
}
end+=offset;
}
end+=offset;
while (isOnChessboard(end)){
int endChess=chessboard[end];
if (endChess!=0){
if (endChess==OpponentMark+cannon) return true;
break;
}
end+=offset;
}
}
}
return false;
}
bool isKilled(){
auto allRoutes=generateAllRoutes();
for (auto& route:allRoutes){
int eaten=moveChess(route);
if (!isCheckmated()){
revokeMoveChess(route,eaten);
return false;
}else{
revokeMoveChess(route,eaten);
}
}
return true;
}
int drawChessScore(){
return (distanceToRoot&1)==0?-scoreDuringDrawNegative:scoreDuringDrawNegative;
}
int detectDuplicateSituation(int repetitions=1){
bool checkMySide=false;
bool thisSidePerpetualCheck=true;
bool opponentPerpetualCheck=true;
int chessIndexValue=historicalMovementsNumber-1;
while (historicalRoutingInformationTable[chessIndexValue].bestMove!=0 and
historicalRoutingInformationTable[chessIndexValue].previousStepEating==0){
if (checkMySide){
thisSidePerpetualCheck=thisSidePerpetualCheck and historicalRoutingInformationTable[chessIndexValue].checkmate;
if (historicalRoutingInformationTable[chessIndexValue].duplicateSituationCheckCode==checkCode.duplicateSituationCheckCode){
repetitions--;
if (repetitions==0){
return 1+(thisSidePerpetualCheck?2:0)+(opponentPerpetualCheck?4:0);
}
}
}else{
opponentPerpetualCheck=opponentPerpetualCheck and historicalRoutingInformationTable[chessIndexValue].checkmate;
}
checkMySide=!checkMySide;
chessIndexValue--;
}
return 0;
}
int duplicateSituationScore(int duplicateStatusCode){
int score=(duplicateStatusCode&2)==0?0:(distanceToRoot-perpetualCheckNegativeScore)+(duplicateStatusCode&4)==0?0:(perpetualCheckNegativeScore-distanceToRoot);
return (score==0)?drawChessScore():score;
}
bool allowEmptyStepCut(){
return (turn==0?redForce:blackForce)>emptyStepCutForceBorder;
}
};
SituationStructure currChessGame;
class PermutationTableStructure{
public:
int depth,sign,score,bestMove;
ui permutationTableCheckCode;
PermutationTableStructure(){
depth=sign=score=bestMove=permutationTableCheckCode=0;
}
};
class SearchRelatedVariables{
public:
static int chessByComputer;
static array<int,65536> historyTable;
static array<array<int,2>,maximumSearchDepth> killerMethodTable;
static array<PermutationTableStructure,maximumPermutationTableSize> permutationTable;
};
int SearchRelatedVariables::chessByComputer=0;
array<int,65536> SearchRelatedVariables::historyTable{};
array<array<int,2>,maximumSearchDepth> SearchRelatedVariables::killerMethodTable{};
array<PermutationTableStructure,maximumPermutationTableSize> SearchRelatedVariables::permutationTable{};
int extractPermutationTableEntry(int vlAlpha,int vlBeta,int dep,int& method){
PermutationTableStructure entry=SearchRelatedVariables::permutationTable[currChessGame.checkCode.duplicateSituationCheckCode&(maximumPermutationTableSize-1)];
if (entry.permutationTableCheckCode!=currChessGame.checkCode.permutationTableCheckCode){
method=0;
return -checkmateScore;
}
method=entry.bestMove;
bool killFlag=false;
if (entry.score>scoreBoundaryVictoryAndDefeat){
if (entry.score<perpetualCheckNegativeScore){
return -checkmateScore;
}
entry.score-=currChessGame.distanceToRoot;
killFlag=true;
}else if (entry.score<-scoreBoundaryVictoryAndDefeat){
if (entry.score>-perpetualCheckNegativeScore){
return -checkmateScore;
}
entry.score+=currChessGame.distanceToRoot;
killFlag=true;
}
if (entry.depth>=dep or killFlag){
if (entry.sign==BetaPermutationTableEntry){
return entry.score>=vlBeta?entry.score:-checkmateScore;
}else if (entry.sign==AlphaPermutationTableEntry){
return entry.score<=vlAlpha?entry.score:-checkmateScore;
}
return entry.score;
}
return -checkmateScore;
}
void savePermutationTableEntry(int sign,int vl,int dep,int method){
PermutationTableStructure entry=SearchRelatedVariables::permutationTable[currChessGame.checkCode.duplicateSituationCheckCode&(maximumPermutationTableSize-1)];
if (entry.depth>dep) return;
entry.sign=sign;
entry.depth=dep;
if (vl>scoreBoundaryVictoryAndDefeat){
if (method==0 and vl<=perpetualCheckNegativeScore) return;
entry.score=vl+currChessGame.distanceToRoot;
}else if (vl<-scoreBoundaryVictoryAndDefeat){
if (method==0 and vl>=-perpetualCheckNegativeScore) return;
entry.score=vl-currChessGame.distanceToRoot;
}else{
entry.score=vl;
}
entry.bestMove=method;
entry.permutationTableCheckCode=currChessGame.checkCode.duplicateSituationCheckCode;
SearchRelatedVariables::permutationTable[currChessGame.checkCode.duplicateSituationCheckCode&(maximumPermutationTableSize-1)]=entry;
}
inline int getMvvLva(int method){
return (MvvLvaForceValue[currChessGame.chessboard[getEnd(method)]]<<3)-MvvLvaForceValue[currChessGame.chessboard[getStart(method)]];
}
class RoutingSortStructure{
public:
int permutationTableMethod;
int killer1,killer2;
int stage;
int adoptedWalkingMethod;
vector<int> allRoutes;
RoutingSortStructure(){
permutationTableMethod=killer1=killer2=stage=adoptedWalkingMethod=0;
allRoutes.clear();
}
void init(int mvHash){
permutationTableMethod=mvHash;
killer1=SearchRelatedVariables::killerMethodTable[currChessGame.distanceToRoot][0];
killer2=SearchRelatedVariables::killerMethodTable[currChessGame.distanceToRoot][1];
stage=0;
adoptedWalkingMethod=0;
}
int getNextMove(){
if (stage==0){
stage=1;
if (permutationTableMethod!=0) return permutationTableMethod;
}
if (stage==1){
stage=2;
if (killer1!=permutationTableMethod and killer1!=0 and currChessGame.moveAllow(killer1)) return killer1;
}
if (stage==2){
stage=3;
if (killer2!=permutationTableMethod and killer2!=0 and currChessGame.moveAllow(killer2)) return killer2;
}
if (stage==3){
stage=4;
allRoutes=currChessGame.generateAllRoutes();
sort(allRoutes.begin(),allRoutes.end(),[](int x,int y){return SearchRelatedVariables::historyTable[x]>SearchRelatedVariables::historyTable[y];});
adoptedWalkingMethod=0;
}
if (stage==4){
while (adoptedWalkingMethod<int(allRoutes.size())){
int method=allRoutes[adoptedWalkingMethod];
adoptedWalkingMethod++;
if (method!=permutationTableMethod and method!=killer1 and method!=killer2) return method;
}
}
return 0;
}
};
void dealBestWay(int method,int dep){
SearchRelatedVariables::historyTable[method]+=dep*dep;
array<int,2>& lpmvKillers=SearchRelatedVariables::killerMethodTable[currChessGame.distanceToRoot];
if (lpmvKillers[0]!=method){
lpmvKillers[1]=lpmvKillers[0];
lpmvKillers[0]=method;
}
}
int staticSearch(int vlAlpha,int vlBeta){
int vl=currChessGame.detectDuplicateSituation();
if (vl!=0) return currChessGame.duplicateSituationScore(vl);
if (currChessGame.distanceToRoot==maximumSearchDepth) return currChessGame.situationAssessment();
int maxn=-checkmateScore;
vector<int> allRoutes;
if (currChessGame.isCheckmatedByHistoryTable()){
allRoutes=currChessGame.generateAllRoutes();
sort(allRoutes.begin(),allRoutes.end(),[](int x,int y){return SearchRelatedVariables::historyTable[x]>SearchRelatedVariables::historyTable[y];});
}else{
vl=currChessGame.situationAssessment();
if (vl>maxn){
maxn=vl;
if (vl>=vlBeta) return vl;
if (vl>vlAlpha) vlAlpha=vl;
}
allRoutes=currChessGame.generateAllRoutes(true);
sort(allRoutes.begin(),allRoutes.end(),[](int x,int y){return getMvvLva(x)>getMvvLva(y);});
}
for (int i:allRoutes){
if (currChessGame.makeAMove(i)){
vl=-staticSearch(-vlBeta,-vlAlpha);
currChessGame.revokeMakeAMove();
if (vl>maxn){
maxn=vl;
if (vl>=vlBeta) return vl;
if (vl>vlAlpha) vlAlpha=vl;
}
}
}
return (maxn==-checkmateScore)?(currChessGame.distanceToRoot-checkmateScore):maxn;
}
int beyondBoundaryAlphaBeta(int vlAlpha,int vlBeta,int dep,bool notEmptyStepCut=false){
int permutationTableMethod=0;
RoutingSortStructure routingSort;
if (dep<=0) return staticSearch(vlAlpha,vlBeta);
int vl=currChessGame.detectDuplicateSituation();
if (vl!=0) return currChessGame.duplicateSituationScore(vl);
if (currChessGame.distanceToRoot>=maximumSearchDepth) return currChessGame.situationAssessment();
vl=extractPermutationTableEntry(vlAlpha,vlBeta,dep,permutationTableMethod);
if (vl>-checkmateScore) return vl;
if (!notEmptyStepCut and !currChessGame.isCheckmatedByHistoryTable() and currChessGame.allowEmptyStepCut()){
currChessGame.emptyMove();
vl=-beyondBoundaryAlphaBeta(-vlBeta,1-vlBeta,dep-emptyStepCutDepth-1,true);
currChessGame.revokeEmptyMove();
if (vl>=vlBeta) return vl;
}
int permutationTableEntrySign=AlphaPermutationTableEntry;
int maxn=-checkmateScore;
int bestMove=0;
routingSort.init(permutationTableMethod);
int method=routingSort.getNextMove();
while (method!=0){
if (currChessGame.makeAMove(method)){
int newdep=dep-1;
if (currChessGame.isCheckmated()) newdep=dep;
if (maxn==-checkmateScore){
vl=-beyondBoundaryAlphaBeta(-vlBeta,-vlAlpha,newdep);
}else{
vl=-beyondBoundaryAlphaBeta(-vlAlpha-1,-vlAlpha,newdep);
if (vlAlpha<vl and vl<vlBeta){
vl=-beyondBoundaryAlphaBeta(-vlBeta,vlAlpha,newdep);
}
}
currChessGame.revokeMakeAMove();
if (vl>maxn){
maxn=vl;
if (vl>=vlBeta){
permutationTableEntrySign=BetaPermutationTableEntry;
bestMove=method;
break;
}
if (vl>vlAlpha){
permutationTableEntrySign=PVPermutationTableEntry;
bestMove=method;
vlAlpha=vl;
}
}
}
method=routingSort.getNextMove();
}
if (maxn==-checkmateScore) return currChessGame.distanceToRoot-checkmateScore;
savePermutationTableEntry(permutationTableEntrySign,maxn,dep,bestMove);
if (bestMove!=0) dealBestWay(bestMove,dep);
return maxn;
}
int rootNodeAlphaBeta(int dep){
RoutingSortStructure routingSort;
int maxn=-checkmateScore;
routingSort.init(SearchRelatedVariables::chessByComputer);
int method=routingSort.getNextMove();
while (method!=0){
if (currChessGame.makeAMove(method)){
int newdep=dep-1,vl=0;
if (currChessGame.isCheckmatedByHistoryTable()) newdep=dep;
if (maxn==-checkmateScore){
vl=-beyondBoundaryAlphaBeta(-checkmateScore,checkmateScore,newdep,true);
}else{
vl=-beyondBoundaryAlphaBeta(-maxn-1,-maxn,newdep);
if (vl>maxn){
vl=-beyondBoundaryAlphaBeta(-checkmateScore,-maxn,newdep,true);
}
}
currChessGame.revokeMakeAMove();
if (vl>maxn){
maxn=vl;
SearchRelatedVariables::chessByComputer=method;
if (-scoreBoundaryVictoryAndDefeat<maxn and maxn<scoreBoundaryVictoryAndDefeat){
maxn+=(rnd()&randomScore)-(rnd()&randomScore);
}
}
}
method=routingSort.getNextMove();
}
savePermutationTableEntry(PVPermutationTableEntry,maxn,dep,SearchRelatedVariables::chessByComputer);
dealBestWay(SearchRelatedVariables::chessByComputer,dep);
return maxn;
}
int moveResult=0;
void IDDFS(int maxdep=maximumSearchDepth,double maxtime=1){
SearchRelatedVariables::historyTable.fill(0);
SearchRelatedVariables::killerMethodTable.fill(array<int,2>{0,0});
SearchRelatedVariables::permutationTable.fill(PermutationTableStructure());
currChessGame.distanceToRoot=0;
int vl=0;
vector<int> allRoutes=currChessGame.generateAllRoutes();
for (int i:allRoutes){
if (currChessGame.makeAMove(i)){
currChessGame.revokeMakeAMove();
SearchRelatedVariables::chessByComputer=i;
vl++;
}
}
if (vl==1) return;
clock_t t=clock();
int i=1;
for (;i<=maxdep;i++){
// cout<<i<<' ';
vl=rootNodeAlphaBeta(i);
if (vl>scoreBoundaryVictoryAndDefeat or vl<-scoreBoundaryVictoryAndDefeat) break;
if (maxtime>0 and (double(clock()-t)/CLOCKS_PER_SEC)>maxtime) break;
}
// cout<<"\n搜索深度:"<<i<<" 耗时:"<<double(clock()-t)/CLOCKS_PER_SEC<<"s"<<endl;
}
vector<array<int,2>> stepSave;
void save(int method,int eaten){
stepSave.push_back({method,eaten});
}
extern "C"{
int computerResponse(){
IDDFS();
int tmp=currChessGame.chessboard[getEnd(SearchRelatedVariables::chessByComputer)];
currChessGame.makeAMove(SearchRelatedVariables::chessByComputer);
// cout<<SearchRelatedVariables::chessByComputer<<"*\n";
save(SearchRelatedVariables::chessByComputer,tmp);
int vl=currChessGame.detectDuplicateSituation(3);
if (currChessGame.isKilled()){
return -1;
}else if (vl>0){
vl=currChessGame.duplicateSituationScore(vl);
return (vl<-scoreBoundaryVictoryAndDefeat)?-2:2;
}else if (currChessGame.historicalMovementsNumber>200){
return 3;
}else{
if (currChessGame.eatPreviousStep()) currChessGame.initHistoricalRoutingInformation();
}
return SearchRelatedVariables::chessByComputer;
}
bool playerMoveAllow(int method){
if (currChessGame.moveAllow(method)){
int tmp=currChessGame.chessboard[getEnd(method)];
if (currChessGame.makeAMove(method)) save(method,tmp);
return true;
}else{
return false;
}
}
int playerMove(int method){
int vl=currChessGame.detectDuplicateSituation(3);
if (currChessGame.isKilled()){
return 1;
}else if (vl>0){
vl=currChessGame.duplicateSituationScore(vl);
return (vl>scoreBoundaryVictoryAndDefeat)?-2:2;
}else if (currChessGame.historicalMovementsNumber>100){
return 3;
}else{
if (currChessGame.eatPreviousStep()) currChessGame.initHistoricalRoutingInformation();
return computerResponse();
}
}
void startNewGame(){
initZobristTable();
currChessGame.initChessboard();
}
int getchessboard(int x){
return currChessGame.chessboard[x];
}
void hq(){
if (stepSave.size()>1){
for (int _=0;_<2;_++){
currChessGame.fallChess(getStart(stepSave.back()[0]),currChessGame.chessboard[getEnd(stepSave.back()[0])]);
currChessGame.takeChess(getEnd(stepSave.back()[0]),currChessGame.chessboard[getEnd(stepSave.back()[0])]);
if (stepSave.back()[1]) currChessGame.fallChess(getEnd(stepSave.back()[0]),stepSave.back()[1]);
stepSave.pop_back();
}
}
}
void takeChess(int pos,int i){
currChessGame.takeChess(pos,i);
}
void fallChess(int pos,int i){
currChessGame.fallChess(pos,i);
}
void clear(){
currChessGame.clear();
}
}
int main(){
// startNewGame();
// cout<<playerMove(42922);
return 0;
}main.py
import sys
import copy
import time
import ctypes
import random
import threading
import pygame
chesslib=ctypes.CDLL("./chesslib.dll")
chief=0
bodyguard=1
elephant=2
horse=3
chariot=4
cannon=5
soldier=6
isOnChessboardList=(
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,1,1,1,1,1,1,1,1,1,0,0,0,0,
0,0,0,1,1,1,1,1,1,1,1,1,0,0,0,0,
0,0,0,1,1,1,1,1,1,1,1,1,0,0,0,0,
0,0,0,1,1,1,1,1,1,1,1,1,0,0,0,0,
0,0,0,1,1,1,1,1,1,1,1,1,0,0,0,0,
0,0,0,1,1,1,1,1,1,1,1,1,0,0,0,0,
0,0,0,1,1,1,1,1,1,1,1,1,0,0,0,0,
0,0,0,1,1,1,1,1,1,1,1,1,0,0,0,0,
0,0,0,1,1,1,1,1,1,1,1,1,0,0,0,0,
0,0,0,1,1,1,1,1,1,1,1,1,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
)
def isOnChessboard(pos):
return isOnChessboardList[pos]!=0
def getx(pos):
return pos&15
def gety(pos):
return pos>>4
def mousePosToGrid(x,y):
return (x+3)+((y+3)<<4)
def playerMethodTComputer(method):
startx,starty,endx,endy=method
return ((startx+3)+((starty+3)<<4))+(((endx+3)+((endy+3)<<4))<<8)
cx=cy=0
cfx=cfy=ctx=cty=-15
state=0
win=False
show=0
font=None
surf=None
surfx=0
computerRunning=False
currmap=[0 for i in range(256)]
moveResult=0
def showSubtitles(s):
global show,surf,surfx
if len(s)<=0:
show=0
return
else:
show=1
siz=min(100,600//len(s))
font=pygame.font.SysFont("SimHei",siz)
surf=font.render(s,1,(255,0,0))
surfx=350-len(s)*siz/2
def gameOver(c):
global win
win=True
showSubtitles(c)
def getChess(chess):
if chess==12:
return "車",(255,0,0)
elif chess==11:
return "馬",(255,0,0)
elif chess==10:
return "相",(255,0,0)
elif chess==9:
return "仕",(255,0,0)
elif chess==8:
return "帥",(255,0,0)
elif chess==13:
return "炮",(255,0,0)
elif chess==14:
return "兵",(255,0,0)
elif chess==20:
return "車",(0,0,0)
elif chess==19:
return "馬",(0,0,0)
elif chess==18:
return "相",(0,0,0)
elif chess==17:
return "仕",(0,0,0)
elif chess==16:
return "将",(0,0,0)
elif chess==21:
return "炮",(0,0,0)
elif chess==22:
return "卒",(0,0,0)
else:
return None,None
def createMap(update=True):
global show
screen.fill((255,200,55))
for i in range(10):
pygame.draw.line(screen,(0,0,0),(100,50+50*i),(500,50+50*i))
for i in range(9):
pygame.draw.line(screen,(0,0,0),(100+50*i,50),(100+50*i,250))
for i in range(9):
pygame.draw.line(screen,(0,0,0),(100+50*i,300),(100+50*i,500))
pygame.draw.line(screen,(0,0,0),(100,250),(100,300))
pygame.draw.line(screen,(0,0,0),(500,250),(500,300))
pygame.draw.line(screen,(0,0,0),(250,50),(350,150))
pygame.draw.line(screen,(0,0,0),(350,50),(250,150))
pygame.draw.line(screen,(0,0,0),(250,400),(350,500))
pygame.draw.line(screen,(0,0,0),(350,400),(250,500))
chs=chf.render("楚河",1,(0,0,0))
screen.blit(chs,(150,250))
hjs=hjf.render("汉界",1,(0,0,0))
screen.blit(hjs,(350,250))
if cx>=0 and cy>=0:
color=(255,0,0) if computerRunning else (0,255,0)
pygame.draw.circle(screen,color,(100+50*cx,50+50*cy),5,0)
curr=currmap
for pos in range(256):
if isOnChessboard(pos) and curr[pos]!=0:
i,j=gety(pos)-3,getx(pos)-3
chess=curr[pos]
name,color=getChess(chess)
if name is not None:
qzs=qzf.render(name,1,color)
screen.blit(qzs,(85+50*j,35+50*i))
pygame.draw.circle(screen,color,(100+50*j,50+50*i),20,1)
if show:
screen.blit(surf,(surfx,225))
if update:
pygame.display.update()
def setupCreateMap():
createMap(False)
pf=pygame.font.SysFont("SimHei",40)
ps=pf.render("设置完成后点击esc退出设置模式",1,(0,0,0))
screen.blit(ps,(50,550))
if cx<0 and cy<0:
#print(cx,cy)
pygame.draw.circle(screen,(0,255,0),(585+60*(-cx-1),50+50*(-cy-1)),5,0)
for chess in range(8,15):
qzf=pygame.font.SysFont("SimHei",30)
name,color=getChess(chess)
qzs=qzf.render(name,1,color)
screen.blit(qzs,(570,35+50*(chess-8)))
pygame.draw.circle(screen,color,(585,50+50*(chess-8)),20,1)
for chess in range(16,23):
qzf=pygame.font.SysFont("SimHei",30)
name,color=getChess(chess)
qzs=qzf.render(name,1,color)
screen.blit(qzs,(630,35+50*(chess-16)))
pygame.draw.circle(screen,color,(645,50+50*(chess-16)),20,1)
qzf=pygame.font.SysFont("SimHei",30)
qzs=qzf.render("X",1,(255,0,0))
screen.blit(qzs,(578,385))
pygame.draw.circle(screen,(255,0,0),(585,400),20,1)
qzf=pygame.font.SysFont("SimHei",30)
qzs=qzf.render("清",1,(0,0,0))
screen.blit(qzs,(630,385))
pygame.draw.circle(screen,(0,0,0),(645,400),20,1)
pygame.display.update()
def getSelectedChess(x,y):
if x==-1 and y==-8:
return 0
if x==-1:
return -y+7
elif x==-2:
return -y+15
def flushChessboard():
global currmap
for i in range(256):
if isOnChessboard(i):
currmap[i]=chesslib.getchessboard(i)
def setup():
global size,screen,cx,cy,cfx,cfy,ctx,cty,state,chf,hjf,qzf
pygame.init()
chf=pygame.font.SysFont("SimHei",50)
hjf=pygame.font.SysFont("SimHei",50)
qzf=pygame.font.SysFont("SimHei",30)
size=700,620
screen=pygame.display.set_mode(size)
while True:
clock.tick(60)
for event in pygame.event.get():
if event.type==pygame.QUIT:
pygame.quit()
sys.exit()
if event.type==pygame.KEYDOWN:
if event.key==pygame.K_ESCAPE:
size=600,600
screen=pygame.display.set_mode(size)
return
mx,my=pygame.mouse.get_pos()
#print(mx,my)
if 90<mx<510 and 40<my<510:
cx=int(round(mx/50,0))-2
cy=int(round(my/50,0))-1
elif 560<mx<670 and 30<my<420:
cx=-((mx-560)//60+1)
cy=-((my-30)//50+1)
if pygame.mouse.get_pressed()[0]:
#print(cx,cy,cfx,cfy,ctx,cty)
if cx!=cfx or cy!=cfy:
if cx<0 and cy<0:
cfx,cfy=cx,cy
state=1
elif state==1:
ctx,cty=cx,cy
state=2
if state==1:
if cfx==-2 and cfy==-8:
chesslib.clear()
cfx=cfy=ctx=cty=-15
state=0
elif state==2:
#print(getSelectedChess(cfx,cfy))
pos,chess=mousePosToGrid(ctx,cty),getSelectedChess(cfx,cfy)
if chess==0:
tmp=chesslib.getchessboard(pos)
if tmp!=0:
chesslib.takeChess(pos,tmp)
else:
chesslib.fallChess(pos,chess)
flushChessboard()
ctx=cty=-15
state=1
setupCreateMap()
def playerMove(method):
global computerRunning,moveResult
computerRunning=True
if chesslib.playerMoveAllow(method):
flushChessboard()
moveResult=chesslib.playerMove(method)
print(moveResult)
flushChessboard()
computerRunning=False
def startNewGame():
global win,moveResult
moveResult=0
win=False
showSubtitles("")
chesslib.startNewGame()
flushChessboard()
def main():
global cx,cy,cfx,cfy,ctx,cty,state,win
setup()
while True:
clock.tick(60)
for event in pygame.event.get():
if event.type==pygame.QUIT:
pygame.quit()
sys.exit()
if not win and not computerRunning:
if event.type==pygame.KEYDOWN:
if event.key==ord("z"):
chesslib.hq()
flushChessboard()
else:
if event.type==pygame.KEYDOWN:
if event.key==ord("n"):
startNewGame()
if not win:
mx,my=pygame.mouse.get_pos()
if 90<mx<510 and 40<my<510:
cx=int(round(mx/50,0))-2
cy=int(round(my/50,0))-1
if not computerRunning:
if moveResult!=0:
if moveResult==1:
gameOver("你赢了!")
elif moveResult==2:
gameOver("电脑长打作负,你赢了!")
elif moveResult==3:
gameOver("超过自然限着作和")
elif moveResult==-1:
gameOver("你输了!")
elif moveResult==-2:
gameOver("长打作负,你输了!")
if pygame.mouse.get_pressed()[0]:
if cx!=cfx or cy!=cfy:
if 8<=chesslib.getchessboard(mousePosToGrid(cx,cy))<=14:
cfx,cfy=cx,cy
state=1
elif state==1:
ctx,cty=cx,cy
state=2
if state==2:
tmp=playerMethodTComputer((cfx,cfy,ctx,cty))
cfx=cfy=ctx=cty=-15
state=0
print(tmp)
thr=threading.Thread(target=playerMove,args=(tmp,))
thr.start()
createMap()
def AIvsAI():
global computerRunning
setup()
step=0
while True:
clock.tick(60)
for event in pygame.event.get():
if event.type==pygame.QUIT:
pygame.quit()
sys.exit()
if not computerRunning:
step+=1
print("step:",step)
computerRunning=True
thr=threading.Thread(target=computerResponse)
thr.start()
createMap()
if __name__=="__main__":
clock=pygame.time.Clock()
pygame.display.set_caption("象棋")
startNewGame()
#playerMove(42922)
main()
#AIvsAI()