Skip to content

Instantly share code, notes, and snippets.

@celestelayne
Created May 5, 2015 18:32
Show Gist options
  • Save celestelayne/77cf424a123547a10c4c to your computer and use it in GitHub Desktop.
Save celestelayne/77cf424a123547a10c4c to your computer and use it in GitHub Desktop.
Assignment :: Constructors & Prototypes
// Make a Dice constructor that takes a numberOfSides. Add a method called roll that randomly returns a number from 1 up to the numberOfSides.
// Modify your roll method to record the returned side in a lastRoll property.
function Dice(numberOfSides) {
this.numSides = numberOfSides;
this.roll = function () {
return Math.floor(Math.random() * (numberOfSides - 1)) + 1;
}
}
/* Results:
var getRandom = new Dice(25);
getRandom
Dice {numSides: 25, roll: function}
getRandom.roll()
23.294355610385537
*/
// Modify your roll method to record the returned side in a lastRoll property.
// Make a CardDeck constructor that returns an object with a cards property that is an array of 52 numbers, 1..52.
// Write a method called deal that randomly returns a number from cards and removes it from the cards array.
// Write a method called isFull that returns true or false if all 52 cards are present.
// Write a method called cut that randomly picks an index and returns an array of two arrays where the deck was split at that index.
// BONUS: write a shuffle method that mixes up all the cards. How does this change your deal method?
function CardDeck() {
this.cards = [
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,
14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39,
40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52
];
this.deal = function(cards) {
return Math.floor(Math.random() * (52 - 1)) + 1; // randomly returns a number from cards
var index = this.cards.indexOf(deal);
if (index > -1) {
this.cards.splice(index, 1);
}
}
this.isFull = function() {
if this.cards[i].length === 51 {
return true;
} else {
return false;
}
}
this.cut = function() {
// randomly pick an index
return // array of two arrays where deck split
}
}
/*
var x = new CardDeck();
x
CardDeck {cards: Array[52], deal: function}cards: Array[52]deal: function (cards) {__proto__: CardDeck
x.deal(22);
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment