123

Pen Settings

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

You're using npm packages, so we've auto-selected Babel for you here, which we require to process imports and make it all work. If you need to use a different JavaScript preprocessor, remove the packages in the npm tab.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Use npm Packages

We can make npm packages available for you to use in your JavaScript. We use webpack to prepare them and make them available to import. We'll also process your JavaScript with Babel.

⚠️ This feature can only be used by logged in users.

Code Indentation

     

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

HTML Settings

Here you can Sed posuere consectetur est at lobortis. Donec ullamcorper nulla non metus auctor fringilla. Maecenas sed diam eget risus varius blandit sit amet non magna. Donec id elit non mi porta gravida at eget metus. Praesent commodo cursus magna, vel scelerisque nisl consectetur et.

            
              <main class="container">
	<div class="config">
		<button id="player-sign-btn">Playing as: <span>X</span> <i>(X goes first!)</i></button>
	</div>
	<table class="board">
		<tbody>
			<tr>
				<td class="corner" data-cell="0">&nbsp;</td>
				<td class="side" data-cell="1">&nbsp;</td>
				<td class="corner" data-cell="2">&nbsp;</td>
			</tr>
			<tr>
				<td class="side" data-cell="3">&nbsp;</td>
				<td class="center" data-cell="4">&nbsp;</td>
				<td class="side" data-cell="5">&nbsp;</td>
			</tr>
			<tr>
				<td class="corner" data-cell="6">&nbsp;</td>
				<td class="side" data-cell="7">&nbsp;</td>
				<td class="corner" data-cell="8">&nbsp;</td>
			</tr>
		</tbody>
	</table>
	<div class="config">
		<p>You: <span data-player="player">0</span></p>
		<p>Computer: <span data-player="computer">0</span></p>
	</div>
</main>
<div id="notification">
	<p></p>
</div>
            
          
!
            
              $board-side: 60vmin;
$yellow: #ffc85d;
$green: #57dd51;
$purple: #994ec3;
$sign-size: ($board-side / 4)/1.25;
@mixin text-selectability($none) {
	-webkit-user-select: $none;
	-moz-user-select: $none;
	-ms-user-select: $none;
	user-select: $none;
}

* {
	margin: 0;
	padding: 0;
	box-sizing: border-box;
}

html,
body {
	height: 100%;
}

body {
	display: flex;
	align-items: center;
	justify-content: center;
	background: linear-gradient(white, $yellow);
	@include text-selectability(none);
}

.container {
	display: flex;
	align-items: center;
	flex-direction: column;
	max-width: $board-side;
}

.config {
	display: flex;
	justify-content: space-around;
	margin: auto auto 1vmin;
	width: $board-side;
	button {
		background-color: white;
		font: 2vmin "Titillium Web", sans-serif;
		border: 0 solid transparent;
		background-color: $yellow;
		border-radius: 25%;
		padding: 5px;
		cursor: pointer;
		outline: .1vmin solid transparent;
		&:disabled {
			cursor: not-allowed;
			background-color: lightgray;
		}
		&:not(:active) {
			animation: {
				name: fadeIn;
				duration: 800ms;
			}
		}
		&:hover {
			background-color: white;
		}
		span {
			font-size: 3vmin;
		}
	}
	#player-sign-btn {
		background-color: $purple;
		font-weight: bolder;
		&:disabled {
			background-color: lightgray;
		}
	}
	p {
		font: bold 3vmin "Titillium Web", sans-serif;
		display: inline-block;
		margin-top: 1vmin;
		span {
			font-size: 4vmin;
		}
	}
}

.board {
	border-radius: 2%;
	position: relative;
	border: .5vmin solid black;
	height: $board-side;
	width: $board-side;
	background-color: white;
	td {
		border-radius: 3%;
		border: .5vmin solid lightgray;
		font: bold $sign-size "Droid Sans Mono", monospace;
		text-align: center;
		cursor: pointer;
		&:active {
			opacity: 0;
		}
		&:not(:active) {
			animation: {
				name: fadeIn, fontEnlarge;
				duration: 600ms, 300ms;
				timing-function: cubic-bezier(0, .5, .25, 1);
			}
		}
		&:hover {
			border-color: black;
		}
	}
}

#notification {
	display: flex;
	position: fixed;
	left: 0;
	top: 0;
	width: 100%;
	height: 100%;
	margin: auto;
	font: bold $board-side / 10 "Titillium Web", sans-serif;
	z-index: -1;
	p {
		margin: auto;
		background-color: rgba(255, 255, 255, .85);
		padding: 1vmin;
		border-radius: 3%;
	}
}

@keyframes fadeIn {
	from {
		opacity: 0;
	}
	to {
		opacity: 1;
	}
}

@keyframes fontEnlarge {
	from {
		font-size: .1vmin;
	}
	to {
		font-size: $sign-size;
	}
}
            
          
!
            
              const winCombos = [
	[0, 1, 2],
	[0, 3, 6],
	[0, 4, 8],
	[1, 4, 7],
	[2, 4, 6],
	[2, 5, 8],
	[3, 4, 5],
	[6, 7, 8]
];

let isPlayerO = false;
let spotsTaken = 0;
let xPlayerMoves = [];
let oPlayerMoves = [];
let computerScore = 0;
let playerScore = 0;

function chooseSpot(arrCellsToChooseFrom) {
	let randomCell = arrCellsToChooseFrom[Math.floor(Math.random() * arrCellsToChooseFrom.length)];

	if ($(randomCell).prop("hasSign") === true) { // If cell is already taken, choose another cell.
		while ($(randomCell).prop("hasSign") === true) {
			randomCell = arrCellsToChooseFrom[Math.floor(Math.random() * arrCellsToChooseFrom.length)];
		}
	}

	return randomCell;
}

function addToScore(player) { // Call when a player wins.
	if (player === "computer") {
		computerScore++;
		$("[data-player='computer']").text(computerScore);
	} else {
		playerScore++;
		$("[data-player='player']").text(playerScore);
	}
}

function isWinCombo(array, player) {
	if (spotsTaken < 5) return;

	array.sort();

	for (let i = 0; i < winCombos.length; i++) {
		let matches = 0;
		for (let j = 0; j < winCombos[i].length; j++) {
			if (array.includes(winCombos[i][j])) {
				matches++;
			}
			if (matches === 3) {
				showVictory(player);
				return true;
			}
		}
	}
	return false;
}

/* This function should take an arbitrary cell and "player" if it is the player's turn. 
    The cell parameter can also take a random cell, or a semi-random cell if !isEasy. */
function drawPlayerSign(cell, player) {
	let cellIndex = $(cell).data("cell");

	function takeSpot(sign) {
		sign === "O" ?
			$(cell).css("background-color", "#57dd51") :
			$(cell).css("background-color", "#994ec3");

		$(cell).text(sign);
		$(cell).prop("hasSign", true);
		spotsTaken++;
	}

	if (player === "computer") {
		if (isPlayerO) {
			takeSpot("X");
			xPlayerMoves.push(cellIndex);
			// console.log("Computer moves: ", xPlayerMoves);
		} else {
			if (spotsTaken === 0) return;
			takeSpot("O");
			oPlayerMoves.push(cellIndex);
			// console.log("Computer moves: ", oPlayerMoves);
		}
	} else {
		if (isPlayerO) {
			takeSpot("O")
			oPlayerMoves.push(cellIndex);
			// console.log("Player moves: ", oPlayerMoves);
		} else {
			takeSpot("X");
			xPlayerMoves.push(cellIndex);
			// console.log("Player moves: ", xPlayerMoves);
		}
	}

	return cellIndex;
}

function showVictory(player) {
	$("#notification p").text(`${player.toUpperCase()} has won!`);
	addToScore(player);
	$("#notification").css("z-index", "2");
	spotsTaken = 0;
	return setTimeout(() => {
		clearBoard();
	}, 1000);
}

function $toggleButton(button, boolean) {
	return boolean === true ?
		$(button).prop("disabled", true) :
		$(button).prop("disabled", false);
}

const clearBoard = () => { // To be called when spotsTaken === 9.
	for (let cellIndex = 0; cellIndex < $("td").length; cellIndex++) {
		$($("td")[cellIndex]).css("background", "white");
		$($("td")[cellIndex]).prop("hasSign", false);
		$($("td")[cellIndex]).html("&nbsp;");
		spotsTaken = 0;
	}
	xPlayerMoves = [];
	oPlayerMoves = [];

	$("#notification").css("z-index", "-1");

	if (isPlayerO) {
		setTimeout(() => {
			drawPlayerSign(chooseSpot($(".corner")), "computer");
		}, 250);
	}
}

const takeTurn = cell => {
	const $thisCell = $(cell.target);

	if (isPlayerO && spotsTaken === 0) return;

	if (isPlayerO) {
		drawPlayerSign($thisCell, "player");
		isWinCombo(oPlayerMoves, "player");
		if (isWinCombo(oPlayerMoves, "player")) return;

		if (spotsTaken !== 0) {
			setTimeout(() => {
				drawPlayerSign(chooseSpot($("td")), "computer");
				isWinCombo(xPlayerMoves, "computer");
				if (isWinCombo(xPlayerMoves, "computer")) return;
				else if (spotsTaken === 9) {
					$("#notification p").text("Draw!");
					$("#notification").css("z-index", "2");
					return setTimeout(clearBoard, 750);
				}
			}, 200);
		}
	} else {
		drawPlayerSign($thisCell, "player");
		isWinCombo(xPlayerMoves, "player");
		if (spotsTaken === 0) return setTimeout(clearBoard, 750);
		if (isWinCombo(xPlayerMoves, "player")) return;

		if (spotsTaken === 9) {
			$("#notification p").text("Draw!");
			$("#notification").css("z-index", "2");
			return setTimeout(clearBoard, 750);
		} else {
			setTimeout(() => {
				drawPlayerSign(chooseSpot($("td")), "computer");
				isWinCombo(oPlayerMoves, "computer");
			}, 200);
			if (isWinCombo(oPlayerMoves, "computer")) return;
		}
	}
};

$(document).ready(() => {
	$toggleButton("#player-sign-btn", false);

	$("#player-sign-btn").on("click", () => {
		const $playerSign = $("#player-sign-btn span");

		if (isPlayerO) {
			isPlayerO = false;
			$("#player-sign-btn").css("background-color", "#994ec3");
			$playerSign.text("X");
		} else {
			isPlayerO = true;
			$("#player-sign-btn").css("background-color", "#57dd51");
			$playerSign.text("O");
		}

		clearBoard();
	});

	$("td").on("click", cell => {
		if ($(cell.target).prop("hasSign") === true) return;

		takeTurn(cell);
	});
});
            
          
!
999px
🕑 One or more of the npm packages you are using needs to be built. You're the first person to ever need it! We're building it right now and your preview will start updating again when it's ready.

Console