Skip to content

Instantly share code, notes, and snippets.

@elnikkis
Created June 9, 2019 13:04
Show Gist options
  • Save elnikkis/39e93145ab876b43e48fcf79647de597 to your computer and use it in GitHub Desktop.
Save elnikkis/39e93145ab876b43e48fcf79647de597 to your computer and use it in GitHub Desktop.
三目並べ
#include <stdio.h>
/*
* 三目並べを作る
* */
#define WIDTH 3
#define HEIGHT 3
#define BLANK 0
#define BLACK 1
#define WHITE -1
#define DRAW 2
int board[WIDTH * HEIGHT];
void showBoard()
{
int x, y;
// print col header
printf(" ");
for(x=0; x<WIDTH; x++){
printf("%2d", (x+1));
}
printf("\n");
for(y=0; y<HEIGHT; y++){
// print row header
printf("%2d", y+1);
for(x=0; x<WIDTH; x++){
if(board[y*WIDTH + x] == BLACK){
printf(" X");
}
else if(board[y*WIDTH + x] == WHITE){
printf(" O");
}
else{
printf(" -");
}
}
printf("\n");
}
}
int isWin()
{
int i, x, y;
// yoko
for(y=0; y<HEIGHT; y++){
int turn = board[y*WIDTH];
if(turn == BLANK)
continue;
for(x=1; x<WIDTH; x++){
if(board[y*WIDTH + x] != turn){
break;
}
}
if(x == WIDTH)
return turn;
}
// tate
for(x=0; x<WIDTH; x++){
int turn = board[x];
if(turn == BLANK)
continue;
for(y=1; y<HEIGHT; y++){
if(board[y*WIDTH + x] != turn){
break;
}
}
if(y == HEIGHT)
return turn;
}
// naname
{
int turn = board[0];
for(i=1; i<WIDTH; i++){
if(board[i*WIDTH + i] != turn)
break;
}
if(i == WIDTH)
return turn;
}
// (2, 0) (1, 1) (0, 2)
{
int turn = board[WIDTH - 1]; // (y, x) = (0, 2)
for(i=1; i<WIDTH; i++){
if(board[WIDTH*i + (WIDTH - i - 1)] != turn)
break;
}
if(i == turn)
return turn;
}
return BLANK;
}
/*
* ゲームが終了していれば1を返す。続行なら0。
* 置ける場所がなくなったらゲーム終了。
*/
int checkGameFinished()
{
int win = isWin();
if(win == BLACK || win == WHITE){
// どちらかが勝っている
return win;
}
else{
// 置ける場所はあるか
int i;
for(i=0; i<WIDTH*HEIGHT; i++){
if(board[i] == BLANK)
break;
}
if(i == WIDTH*HEIGHT){
return DRAW;
}
}
return BLANK;
}
int main()
{
int i;
// init
for(i=0; i<(WIDTH*HEIGHT); i++){
board[i] = BLANK;
}
int x, y, px, py;
int turn = BLACK;
while(1){
showBoard();
// if ゲーム終了
int state = checkGameFinished();
if(state == WHITE){
printf("白の勝ちです\n");
break;
}
else if(state == BLACK){
printf("黒の勝ちです\n");
break;
}
else if(state == DRAW){
printf("引き分けです\n");
break;
}
if(turn == WHITE){
printf("白の番です\n");
}
else{
printf("黒の番です\n");
}
do{
printf("Put 行列: ");
scanf("%d", &i);
py = i / 10;
px = i % 10;
px -= 1; py -= 1;
if(0 <= px && WIDTH > px && 0 <= py && HEIGHT > py && board[py*WIDTH + px] == BLANK){
board[py*WIDTH + px] = turn;
break;
}
else{
printf("%d %dには置けません\n", py+1, px+1);
}
}while(1);
turn *= -1;
}
return 0;
}
22
21
13
31
23
33
32
11
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment