/* */ #include #include #define MAXPILES 10 int pile[MAXPILES]; int npiles; extern void choosepiles(); extern int isover(); extern void usermove(); extern void computermove(); extern int randint(int from, int to); /* inclusive */ int main() { choosepiles(); while (!isover()) { usermove(); if (isover()) { printf("you win! You must have cheated.\n"); break; } computermove(); if (isover()) { printf("I won! Despite your cheating.\n"); break; } } return 0; } void choosepiles() { int i; npiles = randint(0, MAXPILES); for (i = 0; i < npiles; i++) pile[i] = randint(1, 10); } int isover() { int i; for (i = 0; i < npiles; i++) if (pile[i]) return 0; return 1; } void usermove() { int i, userpile, usersticks; char buf[100]; do { printf("Choose a number of sticks and a pile to take them from:\n"); for (i = 0; i < npiles; i++) printf("pile %d has %d sticks.\n", i, pile[i]); printf("Pick a pile.\n"); fgets(buf, 100, stdin); if (sscanf(buf, "%d", &userpile) != 1) userpile = -1; /* go around the loop */ } while (userpile < 0 || userpile >= npiles || !pile[userpile]); do { printf("How many sticks from pile %d (out of %d)?\n", userpile, pile[userpile]); scanf("%d", &usersticks); } while (usersticks < 0 || usersticks > pile[userpile]); pile[userpile] -= usersticks; } void computermove() /* precondition: the game is not over */ { int extrabits = 0; int mypile, mysticks; int i; for (i = 0; i < npiles; i++) extrabits = extrabits ^ pile[i]; if (extrabits == 0) { for (i = 0; i < npiles; i++) { if (pile[i]) { mypile = i; mysticks = 1; } } } else { for (i = 0; i < npiles; i++) { if ((pile[i] ^ extrabits) < pile[i]) { mypile = i; mysticks = pile[i] - (pile[i] ^ extrabits); } } } printf("I take %d sticks from pile %d.\n", mysticks, mypile); pile[mypile] -= mysticks; } int randint(int from, int to) /* inclusive */ { return rand() % (to - from + 1) + from; }