Skip to content

Instantly share code, notes, and snippets.

@okumurakengo
Created May 27, 2020 19:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save okumurakengo/8a7d117373f98b02527850f13ceeffbc to your computer and use it in GitHub Desktop.
Save okumurakengo/8a7d117373f98b02527850f13ceeffbc to your computer and use it in GitHub Desktop.
石取りゲーム
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int x, r, my_turn;
int one_times_max = 5;
int total = 22;
printf("最後に石を取った側が負けです. パスはできません.\n");
if (total < 1 || one_times_max < 1) {
return 1;
}
// totalが0になるまで繰り返す
for (my_turn = 1; total != 0; my_turn ^= 1) {
if (my_turn) {
// コンピュータのターン
// 相手が1,2,3と石をとれば、
// 自分は3,2,1と石をとる
// 石の数が 4k+1 だと必ず相手が最後の一個をとることになって勝てる
//
// 一度に3つしか石を取れないのであれば (total-1) を 常に 4k(one_times_max + 1) にすると勝てる
// 一度に5つしか石を取れないのであれば (total-1) を 常に 6k(one_times_max + 1) にすると勝てる
x = (total - 1) % (one_times_max + 1);
// ルール上1つは石を取らなければいけないので、とりあえず1個取る
if (x == 0) {
x = 1;
}
printf("私は %d 個の石を取ります.\n", x);
} else {
// 自分のターン
do {
printf("何個取りますか? ");
r = scanf("%d", &x);
} while (r != 1 || x <= 0 || x > one_times_max || x > total);
}
total -= x;
printf("残りは %d 個です.\n", total);
}
if (my_turn) {
printf("あなたの負けです!\n");
} else {
printf("私の負けです!\n");
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment