Practicing Prototypes

Finally, let’s work on this and objects linked via prototype (Chapter 4, Pillar 2).

Define a slot machine with three reels that can individually spin(), and then display() the current contents of all the reels.

The basic behavior of a single reel is defined in the reel object below. But the slot machine needs individual reels—objects that delegate to reel, and which each have a position property.

A reel only knows how to display() its current slot symbol, but a slot machine typically shows three symbols per reel: the current slot (position), one slot above (position - 1), and one slot below (position + 1). So displaying the slot machine should end up displaying a 3 x 3 grid of slot symbols.

  1. function randMax(max) {
  2. return Math.trunc(1E9 * Math.random()) % max;
  3. }
  4. var reel = {
  5. symbols: [
  6. "♠", "♥", "♦", "♣", "☺", "★", "☾", "☀"
  7. ],
  8. spin() {
  9. if (this.position == null) {
  10. this.position = randMax(
  11. this.symbols.length - 1
  12. );
  13. }
  14. this.position = (
  15. this.position + 100 + randMax(100)
  16. ) % this.symbols.length;
  17. },
  18. display() {
  19. if (this.position == null) {
  20. this.position = randMax(
  21. this.symbols.length - 1
  22. );
  23. }
  24. return this.symbols[this.position];
  25. }
  26. };
  27. var slotMachine = {
  28. reels: [
  29. // this slot machine needs 3 separate reels
  30. // hint: Object.create(..)
  31. ],
  32. spin() {
  33. this.reels.forEach(function spinReel(reel){
  34. reel.spin();
  35. });
  36. },
  37. display() {
  38. // TODO
  39. }
  40. };
  41. slotMachine.spin();
  42. slotMachine.display();
  43. // ☾ | ☀ | ★
  44. // ☀ | ♠ | ☾
  45. // ♠ | ♥ | ☀
  46. slotMachine.spin();
  47. slotMachine.display();
  48. // ♦ | ♠ | ♣
  49. // ♣ | ♥ | ☺
  50. // ☺ | ♦ | ★

Try to solve this yourself first.

Hints:

  • Use the % modulo operator for wrapping position as you access symbols circularly around a reel.

  • Use Object.create(..) to create an object and prototype-link it to another object. Once linked, delegation allows the objects to share this context during method invocation.

  • Instead of modifying the reel object directly to show each of the three positions, you can use another temporary object (Object.create(..) again) with its own position, to delegate from.

Once you have code that works, compare your solution(s) to the code in “Suggested Solutions” at the end of this appendix.