Skip to content

Instantly share code, notes, and snippets.

@castaneai
Last active December 10, 2015 05:48
Show Gist options
  • Save castaneai/4389614 to your computer and use it in GitHub Desktop.
Save castaneai/4389614 to your computer and use it in GitHub Desktop.
簡易五目並べ(CPU vs CPU)
#include <iostream>
#include <string>
#include <iomanip>
#include <stdlib.h>
#include <time.h>
using namespace std;
string StateChars[] = {"・", "●", "○"};
enum State
{
EMPTY,
BLACK,
WHITE
};
struct Point
{
int x;
int y;
Point(const int x, const int y) : x(x), y(y)
{
}
};
const int SIZE = 12;
const int MOKU = 5;
State Board[SIZE][SIZE] = { EMPTY };
void printBoard()
{
cout << " ";
for (int x = 0; x < SIZE; x++) {
cout << right << setfill(' ') << setw(2) << x;
}
cout << endl;
for (int y = 0; y < SIZE; y++) {
cout << right << setfill(' ') << setw(2) << y;
for (int x = 0; x < SIZE; x++) {
cout << StateChars[Board[y][x]];
}
cout << endl;
}
}
bool putStone(const Point p, State turn){
if (Board[p.y][p.x] != EMPTY) {
return false;
}
Board[p.y][p.x] = turn;
return true;
}
int judgeDir(Point p, const Point dp)
{
const State myState = Board[p.y][p.x];
int count = 0;
while (Board[p.y][p.x] == myState) {
count++;
p.x += dp.x;
p.y += dp.y;
if (count >= MOKU)
break;
if (p.x < 0 || p.x >= SIZE)
break;
if (p.y < 0 || p.y >= SIZE)
break;
}
return count;
}
bool judge(const Point p)
{
Point points[] = {
Point(1, 0), Point(0, 1), Point(1, 1), Point(1, -1),
};
for (int i = 0; i < sizeof(points) / sizeof(Point); i++) {
Point inversePointUnit(points[i].x * -1, points[i].y * -1);
if (judgeDir(p, points[i]) + judgeDir(p, inversePointUnit) - 1 >= MOKU)
return true;
}
return false;
}
Point randomAI(const State turn)
{
srand(time(NULL));
for (;;) {
int randX = rand() % SIZE;
int randY = rand() % SIZE;
Point randPoint(randX, randY);
if (Board[randY][randX] == EMPTY) {
return randPoint;
}
}
}
Point manualAI(const State turn)
{
int x, y;
for (;;) {
cout << "x y" << endl;
cin >> x >> y;
if (Board[y][x] == EMPTY) {
return Point(x, y);
} else {
cout << "そこには置けません" << endl;
}
}
}
State changeTurn(const State nowTurn)
{
return nowTurn == BLACK ? WHITE : BLACK;
}
int main(void)
{
printBoard();
State turn = BLACK;
for(;;) {
cout << StateChars[turn] << "のターン" << endl;
Point p = randomAI(turn);
//Point p = turn == BLACK ? manualAI(turn) : randomAI(turn);
cout << StateChars[turn] << "は(" << p.x << ", " << p.y << ")に置きます" << endl;
if (putStone(p, turn) == false) {
cout << StateChars[turn] << "はそこに置けるはずがない!" << endl;
continue;
}
printBoard();
if (judge(p)) {
cout << StateChars[turn] << "の勝ち!" << endl;
break;
}
turn = changeTurn(turn);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment