Week 05 - Classes

This week we'll start with some in class exercises and then learn about the class keyword.

View the lecture

Homework

Assignment

Concentration is a game in which the player chooses cards in an attempt to match the other cards they've revealed that turn. If they do not match, the cards revealed during that turn are flipped back over and their turn done. If the player does guess matching cards, those cards remain revealed, and their turn is over. The player then takes her next turn. For now, we'll be concerned with a single player version of the game.

The player wins when all cards have been revealed and loses if they exceed the maximum number of turns allowed.

Write a javascript class called ConcentrationGame.

ConcentrationGame should have a constructor method that takes two arguments, 1) an array of strings representing the card options, and 2) an integer representing how many times each card should be present in the deck (and how many guesses a player gets per turn).

It should also implement get_deck() which returns the deck and guess_card_at(card_index) which is used by the user to guess a card in the deck at the given index. When guess_card_at is called, it should check if the player has won, lost, or if their turn is over.

Starter code on jsbin

class ConcentrationGame {
  constructor(card_options, times_in_deck) {
    // YOUR CODE HERE
    // Generate the deck and store it as this.deck
    // This is also where we'd shuffle it, but don't worry about that for now
    // this.deck = deck
    // to keep track of which cards the user has guessed in a given turn
    this.active_cards = []
    // to keep track of the cards the player has successfully matched overall
    this.revealed_cards = []
    this.turn_count = 0
    this.max_turns = 5
  }
  get_deck() {
    return this.deck
  }
  guess_card_at(card_index) {
    // YOUR CODE HERE
    // You should write other functions as part of this class
    // to do things here like checking if the player's turn is over
    // (and resetting active_cards if it is) as well as if the player has won or lost
  }
}

let game = new ConcentrationGame(["a", "b"], 2)
// i.e. make a deck with two a's and two b's in it
game.get_deck()
// should return ['a', 'a', 'b', 'b']

game.guess_card_at(0) // should return a
game.guess_card_at(1) // should return a
game.guess_card_at(2) // should return b
game.guess_card_at(3) // should return b
// and should console.log('You win!')

// Whereas
game.guess_card_at(0) // should return a
game.guess_card_at(2) // should return b
game.guess_card_at(1) // should return a
game.guess_card_at(3) // should return b
// Should *not* output the win message
game.guess_card_at(0) // should return b
// Should console.log('You lose!')