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]
- Project 3 requirements – 3 weeks to go!
innerHTML
vsinnerText
vs.textContent
- Suggestion:
"use strict";
in every file
Lecture [25 min]
- 33_Textbook_8.8-10.2.pdf – by Connolly and Hoar
- listing8.13.js listing8.14.js listing10.4.js
- listing10.5.js listing10.6.js listing10.7.js
- Prototype vs Class in JS – summary by ChatGPT
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 ofrows
andcols
- Create a 2D array of
placeTile()
should setthis.grid[row][col]
to theTile
and returntrue
- But only if the cell is
null
; in that case don't update, and returnfalse
- But only if the cell is
display()
should get theboard
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 thetile
's letter (or_
if null) - Set the cell's padding to
4px
. - Append each
span
to thediv
; append eachdiv
to the board
- Create a
The Player
class
playTile()
should returntrue
on success orfalse
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()
)
- If there is a tile at
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
- If the tile bag is not empty
- Write a loop to run for