Skip to content

Instantly share code, notes, and snippets.

@anbnyc
Last active November 13, 2016 00:11
Show Gist options
  • Save anbnyc/f7ec5d73ae81b4afdf87500c4a67b740 to your computer and use it in GitHub Desktop.
Save anbnyc/f7ec5d73ae81b4afdf87500c4a67b740 to your computer and use it in GitHub Desktop.
Tic Tac Toe
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.3.0/d3.js"></script>
<style>
rect{
fill: rgba(0,0,0,.2);
stroke: black;
}
</style>
</head>
<body>
</body>
<script>
var turn = "X",
dim = 50,
move,
text,
flat,
position,
spaces = [[0,0],[0,1],[0,2],[1,0],[1,1],[1,2],[2,0],[2,1],[2,2]],
board = [[" "," "," "],[" "," "," "],[" "," "," "]],
row = {
"top": 0,
"middle": 1,
"bottom": 2
},
column = {
"left": 0,
"center": 1,
"right": 2
};
setBoard();
function setBoard(){
var svg = d3.select("body").append("svg");
var rows = svg.selectAll("g")
.data(board,(d,i) => d[i])
.enter()
.append("g")
.attr("width",dim)
.attr("height",dim)
.attr("transform",(d,i) => "translate(0,"+i*dim+")" );
var cells = rows.selectAll("g")
.data(d => d)
.enter()
.append("g");
cells.append("rect")
.attr("width",dim)
.attr("height",dim)
.attr("x",(d,i) => i*dim);
text = cells.append("text")
.attr("dx",(d,i) => i*dim+20)
.attr("dy",.5*dim+5);
beginTurn();
}
function beginTurn(){
setTimeout(getMove,50,"");
}
function getMove(msg){
if(turn === "X") { // human
move = prompt(msg+"Player "+turn+", give the coordinates [top/middle/bottom] [left/center/right] of your next move:");
move = move.split(" ");
if(board[row[move[0]]][column[move[1]]] === " "){
writeMove(row[move[0]],column[move[1]]);
} else {
getMove("Invalid move. ");
}
} else { // computer
move = computerMove();
writeMove(move[0],move[1]);
}
evalMove();
}
function writeMove(row,col){
var index = spaces.findIndex((o) => {
return o[0] === row && o[1] === col;
});
if(spaces.length > 0){
spaces.splice(index,1);
}
board[row][col] = turn;
flat = board.reduce((t,v) => t+v.join(""),"");
}
function computerMove(){
position = Math.floor(Math.random()*spaces.length);
var choice = spaces[position];
return choice;
}
function evalMove(){
updateGrid();
if(checkWin(flat)){
setTimeout(function(){
alert(turn+" wins!");
},50);
} else if(flat.indexOf(" ") === -1) {
setTimeout(function(){
alert("It's a tie!");
},50);
} else {
turn = (turn === "X") ? "O" : "X";
beginTurn();
}
}
function updateGrid(){
text.data(d => d).text(d => d);
}
function checkWin(flat){
var combos = [];
for(var i = 0; i < 3; i++){
combos.push(flat[0+i]+flat[3+i]+flat[6+i]); // cols
combos.push(flat[i*3+0]+flat[i*3+1]+flat[i*3+2]); // rows
}
combos.push(flat[0]+flat[4]+flat[8]); //diag
combos.push(flat[2]+flat[4]+flat[6]); //diag
for(var i = 0; i < combos.length; i++){
if(combos[i] === turn.repeat(3)){
return true;
}
}
return false;
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment