Skip to content

Apr 17: Prototypes/Classes

Learning Objectives

After today's class, you should be able to:

  • Summarize the kinds of programming mistakes that strict mode finds.
  • Explain the difference between a prototype and a class in JavaScript.
  • Implement an object-oriented board/card game that uses 3+ classes.

Lesson Outline

Project [20 min]

Lecture [25 min]

Activity [30 min]

  • CS159-style assignment in JavaScript

Simple Scrabble

Scrabble is a word game where players take turns placing letter tiles on a board to form words. Each letter has a point value, and players earn points based on the words they create. The game ends when all tiles are used or no more moves can be made. The player with the most points wins.

Getting Started

Download the following files:

The following class containing all the game logic is provided:

Requirements

Implement the following classes at the top of scrabble.js:

The Tile class

  • Not much to do here; just write the constructor!

The Board class

  • The constructor should initialize all three attributes
    • Create a 2D array of null values for the given number of rows and cols
  • placeTile() should set this.grid[row][col] to the Tile and return true
    • But only if the cell is null; in that case don't update, and return false
  • display() should get the board element and replace it's HTML contents:
    • Create a div for each row
    • Create a span for each cell (on each row)
    • Set the cell's textContent to the tile's letter (or _ if null)
    • Set the cell's padding to 4px.
    • Append each span to the div; append each div to the board

The Player class

  • playTile() should return true on success or false on failure
    • If there is a tile at tileIndex and you can place the tile
      • Add the tile's points to the player's score
      • Remove the tile from the player's hand (Hint: use hand.splice())
  • drawTiles() is used for a Player to draw (take) tiles from the bag
    • Write a loop to run for count times
      • If the tile bag is not empty
        • Pop the next tile from the bag
        • Push the tile into the Player's hand