较为简单的五子棋游戏代码,通俗易懂,适合初学者。
今天复习c++小小的练习了一下,如果有不足或者要修改的地方,欢迎指正。
#pragma once #include<iostream> #include<Windows.h> using namespace std; class CChess { public: CChess(); ~CChess(); void drawMap(); void initiBoard(); bool judgeIfwin(); bool judgeIfmove(int x,int y); private: char game[15][15] = { 0 }; const char play1 = 'o'; const char play2 = 'x'; const char chessBoard = ' '; }; static int flag = 1; #include "stdafx.h" #include "CChess.h" CChess::CChess(){} CChess::~CChess(){} void CChess::drawMap()//初始化游戏界面 { system("cls"); for (int i = 0; i < 9; ++i) { cout << "-------------------------------------------------------------------------" << endl; for (int j = 0; j < 9; ++j) { if (game[i][j] == 0) { cout << "| \t"; } else { cout << "| " << game[i][j]<<'\t'; } } cout << "|" << endl; } cout << "-------------------------------------------------------------------------" << endl; } bool CChess::judgeIfwin() { int flag = 0; for(int i=0;i<9;i++) for(int j=0;j<9;j++) if (game[i][j] != 0) { for (int k = j + 1; k < j + 4; k++) //打横 { if (game[i][j] != game[i][j - 1]) break; else flag = 1; } for (int k = i+1; k < i + 4; k++) { if (game[i][j] != game[i-1][j ]) //打竖 break; else flag = 1; } for (int k = i + 1; k < i + 4; k++) { if (game[i][j] != game[i - 1][j-1]) //打斜 break; else flag = 1; } } if (flag !=0) return true; else return false; } bool CChess::judgeIfmove(int x,int y)//如果棋盘满了或者已经输入,则无法正常落子 { int flag = 0; for (int i = 0; i < 9; i++) for (int j = 0; j < 9; j++) if (game[i][j] == 0) { flag = 1; break; } if (game[x][y] == 0 && flag == 1) return true; else cout << "error!"; return false; } void CChess::initiBoard()//开始游戏 { drawMap(); while (1) { int x, y; if (flag%2) { cout << "player1: plz enter the position(0 0,0 1): "; cin >> x >> y; if (judgeIfmove(x,y)) game[x][y] = play1; drawMap(); } else { cout << "player2: plz enter the position(0 0,0 1): "; cin >> x >> y; if (judgeIfmove(x, y)) game[x][y] = play1; game[x][y] = play2; drawMap(); } flag++; if (flag > 9) if (judgeIfwin()) break; } cout << "game over!"; } //main.cpp #include "stdafx.h" #include"CChess.h" #include<iostream> using namespace std; int main() { CChess ches; ches.initiBoard(); return 0; }结果如下: