slots

slots

by Joseph Tate

HTML

<h1></h1>

CSS

h1.win {
    font-size: 2em;
    color: #008000;    
}

h1.lose {
    font-size: 2em;
    color: #990000;    
}

JavaScript

/**
 * Returns true if the symbols displayed on a slot machine
 * are a winning combination.  A winning combination is
 * one in which the same symbol is displayed in N
 * or more adjacent slots.
 *
 * @param slots an array describing the selections in each slot.
 *  the first symbol is slots[0], and so on.  Each element of the
 *  array is a string (e.g., "cherry").
 *
 * @param n the number of consecutive symbols required to
 *   achieve a win.
 *
 * @return true if 'n' or more adjacent slots contain
 *   the same symbol.
 */

function allElementsMatch(list) {
    var i;
    for (var i = 0; i < list.length - 1; i++) {
        if (list[i] !== list[i + 1]) {
            return false;
        }
    } 
    return true;
}

function isWinningCombination(slots, n) {
    var i;
    for (i = 0; i <= slots.length - n; i++) {
       if (allElementsMatch(slots.slice(i, i + n))) {
           return true;
       }      
    }
    return false;
}

$(function () { 
    if (isWinningCombination(['lemon', 'lemon', 'lemon' ], 3)) { 
        $('h1').addClass('win').append('Win!');            
    } else { 
        $('h1').addClass('lose').append('Lose.');      
    }   
});