141k views
0 votes
coen 243 project (nim to win) deadline: december 3, 2023 type: group (not compulsory) weight:7% submission: moodle //*********************************************************************************** write the code in c to simulate a nim game. the rules of nim are as follows: 1- this game includes two players. 2- each player can pick up from one pile. 3- the player can only take one or two tokens. 4- the winner is the player who makes the last move. 5- suppose we only have 5 heaps. 8- the game must be recursive, namely, it calls itself each turn. 7- try to use an array in c style (for example to represent the heaps

1 Answer

4 votes

Final answer:

The COEN 243 project requires creating a C program to simulate a nim game with recursion and an array representing five heaps. The code example provided demonstrates how to create such a game, following the game-logic, player interaction, and recursive turn structure.

Step-by-step explanation:

The COEN 243 project (nim to win) requires writing code in C to simulate a nim game, obeying certain game rules and coding requirements. The game involves simple logic for two players who take turns removing one or two tokens from any of the five piles (heaps). The game continues recursively with the function calling itself each turn until the last move decides the winner.

Here's an example of how the game could be structured in C, using an array to represent the heaps and recursion to enact successive turns:

#include
int heaps[5] = {3, 4, 5, 6, 7}; // Example heap sizes

void displayHeaps() {
for (int i = 0; i < 5; i++)
printf("Heap %d: %d\\", i + 1, heaps[i]);
}

int gameOver() {
for (int i = 0; i < 5; i++)
if (heaps[i] > 0)
return 0;
return 1;
}

void nimGame(int player) {
if (gameOver()) {
printf("Player %d wins!\\", 3 - player);
return;
}
int heap, tokens;

displayHeaps();
printf("Player %d's turn. Choose a heap (1-5) and tokens to take (1-2): ", player);
scanf("%d %d", &heap, &tokens);
if (tokens < 1 || tokens > 2 || heaps[heap-1] < tokens) {
printf("Invalid move. Try again.\\");
nimGame(player);
} else {
heaps[heap - 1] -= tokens;
nimGame(3 - player);
}
}

int main() {
printf("Welcome to Nim!\\");
nimGame(1);
return 0;
}

This code sets up an array representing the heaps, a recursive function to simulate the turns, and a main function to start the game. Players alternate turns taking 1 or 2 tokens until a player clears the last heap and wins.

User Matt Hinze
by
7.4k points