tic tac toe threejs in javascript

Tic Tac Toe Game using Three.js in JavaScript

Tic Tac Toe is a popular game that can be implemented using various programming languages, and web technologies. Here, we will see how to create a Tic Tac Toe game in JavaScript using the popular 3D library, Three.js.

Step 1: Setting up the Scene

The first step is to create a scene and add it to the canvas using Three.js. We also need to add a camera and a light source to the scene.

index.tsx
// Setup the scene
const scene = new THREE.Scene();

// Setup the camera
const camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );
camera.position.z = 5;

// Setup the renderer
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );

// Setup the light
const light = new THREE.AmbientLight( 0xffffff );
scene.add( light );
482 chars
16 lines

Step 2: Creating the Board

We need to create a board for the Tic Tac Toe game. Here, we can use a simple plane geometry and apply a texture to it.

index.tsx
// Setup the board
const boardGeometry = new THREE.PlaneGeometry( 3, 3, 1 );
const boardMaterial = new THREE.MeshBasicMaterial( {color: 0xffffff, side: THREE.DoubleSide} );
const board = new THREE.Mesh( boardGeometry, boardMaterial );

// Load the board texture
const loader = new THREE.TextureLoader();
loader.load( 'board_texture.jpg', function ( texture ) {
    boardMaterial.map = texture;
    boardMaterial.needsUpdate = true;
});

scene.add( board );
457 chars
14 lines

Step 3: Adding the X and O Symbols

We need to create models for the X and O symbols, which can be added to the scene when a player makes a move.

index.tsx
// Setup the X symbol
const xGeometry = new THREE.Geometry();
xGeometry.vertices.push( new THREE.Vector3( -0.5, -0.5, 0 ) );
xGeometry.vertices.push( new THREE.Vector3( 0.5, 0.5, 0 ) );
xGeometry.vertices.push( new THREE.Vector3( 0.5, -0.5, 0 ) );
xGeometry.vertices.push( new THREE.Vector3( -0.5, 0.5, 0 ) );
xGeometry.faces.push( new THREE.Face3( 0, 1, 2 ) );
xGeometry.faces.push( new THREE.Face3( 1, 0, 3 ) );
const xMaterial = new THREE.MeshBasicMaterial( { color: 0xff0000 } );
const xSymbol = new THREE.Mesh( xGeometry, xMaterial );

// Setup the O symbol
const oGeometry = new THREE.CircleGeometry( 0.4, 32 );
const oMaterial = new THREE.MeshBasicMaterial( { color: 0x0000ff } );
const oSymbol = new THREE.Mesh( oGeometry, oMaterial );
oSymbol.rotation.x = Math.PI / 2;

scene.add( xSymbol );
scene.add( oSymbol );
823 chars
20 lines

Step 4: Handling User Input

We need to handle user input to detect when a player has made a move on the board. We can use the Raycaster object from Three.js to detect when the user clicks on the board.

index.tsx
// Setup the Raycaster
const raycaster = new THREE.Raycaster();
const mouse = new THREE.Vector2();

function onMouseMove( event ) {
    // Calculate mouse position
    mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1;
    mouse.y = - ( event.clientY / window.innerHeight ) * 2 + 1;
}

function onClick( event ) {
    // Update the picking ray with the camera and mouse position
    raycaster.setFromCamera( mouse, camera );

    // Calculate objects intersecting the picking ray
    const intersects = raycaster.intersectObjects( scene.children );

    for ( let i = 0; i < intersects.length; i++ ) {
        if ( intersects[ i ].object == board ) {
            // Add X or O symbol at the clicked position
            const symbol = ( currentPlayer == 1 ) ? xSymbol.clone() : oSymbol.clone();
            symbol.position.copy( intersects[ i ].point );
            scene.add( symbol );

            // Update game matrix and check for winner
            matrix[ intersects[ i ].faceIndex ] = currentPlayer;
            checkForWinner();

            // Switch players
            currentPlayer = ( currentPlayer == 1 ) ? 2 : 1;
        }
    }
}

document.addEventListener( 'mousemove', onMouseMove, false );
document.addEventListener( 'click', onClick, false );
1270 chars
37 lines

Step 5: Checking for a Winner

Finally, we need to check for a winner after each move. This can be done by checking for 3 consecutive X or O symbols in a row, column or diagonal.

index.tsx
// Setup the game matrix
const matrix = [ 0, 0, 0, 0, 0, 0, 0, 0, 0 ];

// Check for a winner
function checkForWinner() {
    if ( matrix[0] == currentPlayer && matrix[1] == currentPlayer && matrix[2] == currentPlayer ) {
        // Winner found in top row
        alert('Player ' + currentPlayer + ' wins!');
    }
    else if ( matrix[3] == currentPlayer && matrix[4] == currentPlayer && matrix[5] == currentPlayer ) {
        // Winner found in middle row
        alert('Player ' + currentPlayer + ' wins!');
    }
    // More checks for other rows, columns and diagonals
}
577 chars
16 lines

That's it! We have successfully created a Tic Tac Toe game in JavaScript using Three.js.

gistlibby LogSnag