CS1101S

Lecture 8: The Game of Nim

7 September 2012

Martin Henz

Overview

Game of Nim

Game state: Wishful Thinking!


function make_game_state(n, m) { ... }

function size_of_pile(game_state, p) { ... }

How to remove coins from pile?

Poor Rabbit Rick!

Playing the game

Displaying the game state


function display_game_state(game_state) {
    alert("Pile 1: " + 
          size_of_pile(game_state, 1) + "\n" +
          "Pile 2: " + 
          size_of_pile(game_state, 2));
}

Game over


function game_over(game_state) {
    return total_size(game_state) === 0;
}

function total_size(game_state) {
    return size_of_pile(game_state, 1) + 
           size_of_pile(game_state, 2);
}

Announce Winner


function announce_winner(player) {
    if (player === "human") {
        alert("You lose. Try again.");
    } else {
        alert("You win. Congratulations.");
    }
}

Human Move


function human_move(game_state) {
    var pile_string = prompt("Which pile from?");
    var pile = parseInt(pile_string);
    var coins_string = prompt("How many?");
    var coins = parseInt(coins_string);
    return remove_coins_from_pile(game_state, 
                                  coins, pile);
}

Artificial Intelligence


function computer_move(game_state) {
    var pile = 
        (size_of_pile(game_state, 1) > 0) ? 1 : 2;
    alert("I take one coin from pile "+ pile);
    return remove_coins_from_pile(game_state, 1, 
                                  pile);
}

Representing the Game State: First attempt


function make_game_state(n, m) {
    return 10 * n + m;
}

Representing the Game State: Second attempt

function make_game_state(n, m) {
    return pair(n, m);
}
function size_of_pile(game_state, p) {
    if (p === 1) {
        return head(game_state);
    } else if (p === 2) {
        return tail(game_state);
    } else {
        return "error";
    }
}

Data Structure Design

Challenge: Implement Undo Function for Nim

Summary

/

#