Loading [MathJax]/jax/output/HTML-CSS/jax.js

CPSC120A
Fundamentals of Computer Science I

Lab 21

Review

Use the command line to create a new directory called lab21 in your labs directory. Make sure all of the .py files that you create for this activity are in that directory.

Pick-up Sticks

Nim is an ancient game where players take turns picking up stones. The stones are arranged in some fashion and each turn a player must remove 1, 2, or 3 stones from the collection. The player that picks up the last stone loses. In this activity you will write a command line version of the game, using sticks instead of stones.

Details

Write a function called play_nim(num_sticks) in a file called nim.py. The function should play a two-player game of nim with num_sticks initially in a row. The function should prompt the player for the number of sticks to remove. If the player does not enter a number of sticks in the range [1, 3], the user should be prompted to enter a new value. The removed sticks should be displayed with underscore characters. When player 1 removes sticks, they should be removed from the left side of the collection. When player 2 removes sticks, they should be removed from the right side of the collection. The winner of the game should be displayed when there are no sticks left.

It is difficult to test a program that uses user input like this one. Make an additional function that plays one turn of nim without using user input, for testing purposes.

Example

>>> nim(10)
||||||||||
Player 1, enter a number of sticks (1-3): 3
___|||||||
Player 2, enter a number of sticks (1-3): 3
___||||___
Player 1, enter a number of sticks (1-3): 4
Player 1, enter a number of sticks (1-3): 3
______|___
Player 2, enter a number of sticks (1-3): 1
__________
Player 1 wins!

Hint

Challenge

Create a 1-player version of the game that uses a very simple artificial intelligence. If the computer can win by leaving the player with only 1 stick, it should. Otherwise, the computer should remove a random number of sticks between 1 and 3.


Challenge

Create a 1-player version of the game that uses an intelligent artificial intelligence. The computer should use the optimal game strategy. If one player is using the optimal strategy and the other is not, the optimal strategy will always win. If both players are using the optimal strategy then whoever goes first will win. It is up to you to figure out what the optimal strategy is.

Submission

Please show your source code and run your programs for the instructor or lab assistant. Only a programs that have perfect style and flawless functionality will be accepted as complete.