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.