極簡版本:五子棋初
阿新 • • 發佈:2018-11-10
#include <iostream> #include <conio.h> void main() { const int w = 20; const int h = 20; int map[w*h]={};//0空子 1黑子 2白子 bool black = true;//true當前該黑方落子 false當前該白方落子 //游標 int px = 0; int py = 0; while (true) { system("cls"); //繪製 for (int y = 0; y < h; ++y) { for (int x = 0; x < w; ++x) {//●○ if (x == px && y == py) std::cout<<"¤"; else if (map[x+y*w] == 1) std::cout<<"黑"; else if (map[x+y*w] == 2) std::cout<<"白"; else if (x == 0 && y == 0) std::cout<<"┏"; else if (x == w-1 && y == 0) std::cout<<"┓"; else if (x == 0 && y == h-1) std::cout<<"┗"; else if (x == w-1 && y == h-1) std::cout<<"┛"; else if (y == 0) std::cout<<"┳"; else if (y == h-1) std::cout<<"┻"; else if (x == 0) std::cout<<"┣"; else if (x == w-1) std::cout<<"┫"; else std::cout<<"╋"; } std::cout<<std::endl; } //邏輯 int a = _getch(); if (a == 'w' || a == 'W') { if (py > 0) py--; } else if (a == 's' || a == 'S') { if (py < h-1) py++; } else if (a == 'a' || a == 'A') { if (px > 0) px--; } else if (a == 'd' || a == 'D') { if (px < w-1) px++; } //落子 else if (a == ' ') { //只有空子的地方才能落子 if (map[px+py*w] == 0) { map[px+py*w] = black?1:2; //勝負判斷 bool win = false;//勝利與否 //橫向判斷 int count = 0;//計數的 for (int x = px+1; x < w; ++x) { if (map[x + py*w] == map[px+py*w]) count++; else break; } for (int x = px-1; x >= 0; --x) { if (map[x + py*w] == map[px+py*w]) count++; else break; } if (count >= 4) win = true; if (!win) { //豎向 count = 0; for (int y = py+1; y < h; ++y) { if (map[px+y*w] == map[px+py*w]) count++; else break; } for (int y = py-1; y >= 0; --y) { if (map[px+y*w] == map[px+py*w]) count++; else break; } if (count >= 4) win = true; } if (!win) { //斜向的 count = 0; for (int x = px-1, y = py-1; x >= 0 && y >= 0; x--,y--) { if (map[x+y*w] == map[px+py*w]) count++; else break; } for (int x = px+1, y = py+1; x < w && y < h; x++,y++) { if (map[x+y*w] == map[px+py*w]) count++; else break; } if (count >= 4) win = true; } if (!win) { count = 0; for (int x = px+1,y = py-1; x < w && y >= 0; x++, y--) { if (map[x+y*w] == map[px+py*w]) count++; else break; } for (int x = px-1,y = py+1; x >= 0 && y < h; x--, y++) { if (map[x+y*w] == map[px+py*w]) count++; else break; } if (count >= 4) win = true; } if (win) { std::cout<<(black?"黑方勝利":"白方勝利"); system("pause"); //還原資料為初始的資料 for(int i = 0;i < w*h; ++i) map[i] = 0; px = 0; py = 0; black = true; } //變換棋子顏色 black = !black; } } } }