Created
June 29, 2018 08:48
-
-
Save zailleh/d8cbc6533b3e95eebc4bac1eebb28cc7 to your computer and use it in GitHub Desktop.
Made a tic-tac-toe game in js and jquery that will work at any size board in as few lines as possible
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// <input type="range" id="size" min="3" max="10" value="3"> | |
// <div class="board"> | |
// </div> | |
let p = 0; | |
const s = []; | |
let size = +$('#size').val() //set size to default | |
const makeBoard = function() { | |
size = +$('#size').val() //get size from input | |
$('.board').html("").css('--size',size+''); //clear boxes and set --size css variable | |
s.length = 0; p = 0; //reset box data and player | |
for(let i = 0; i < size*size; i++ ) { | |
$('.board').append( $(`<div class="box" id="${i}">`)); //make boxes | |
} | |
$('.box').click(click); //listen for click | |
} | |
const winLine = function(i,n,p) { | |
const arr = []; | |
for (let j = 0; j < size; j++ ){ | |
arr[j] = s[i+n*j]; //get values based on grid pattern | |
} | |
return arr.reduce(function(a,b){return (a === b) ? a : false;}) === p //check that array contents are the same and === p | |
}; | |
const click = function(){ | |
s[+$(this).addClass('p'+p).off().attr('id')] = p; //add class for current player, remove click event, return id set score | |
for(let i = 0; i<size*size; i++){ // check win conditions based on formulas (+size = vertical; +1 = horiz; size+1 =diag 1; -size+1 = diag 2) | |
if (winLine(i,size,p) || winLine(i,1,p) || winLine(i,size+1,p) || winLine(i,-size+1,p)){ | |
$('.board').html(p +' wins!'); // if any are true, we have a winner! | |
break; | |
} | |
} | |
p = 1-p; //alternate player; | |
} | |
$('#size').on('input',makeBoard); //listen for input changes on slider | |
makeBoard(); //make first board |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment