Building CLI Tic Tac Toe Game with Node JS | By Alvin Endratno | Tealfeed (2023)

One thing that makes developers other than ordinary people out there is a command line. The moment someone opens up the terminal and types out some commands, they instantly transform into a hacker (at least they seem to be hackers). It makes me want to build it myself.

Why Tic Tac Toe, you think? Well, it's simple enough to build but requires user input to make a game playable.

The tutorial is divided into three different sections. In the first section, you will learn how to set the environment to build a CLI App. After that, we develop our tic tac toe platform. Finally, we will publish it to NPM and see if we can play it on our terminal.

And our goal is to make a playable two-player Tic Tac Toe game from CLI. You can try the final result by executing this command.

npx @alvinend/tic-tac-toe-cli

Let's start setting up our environment. For prerequisite, if you want to publish it on NPM. Make sure you have NPM and are logged in.

Initiate NPM

Since we want to use Nodejs and publish our application in NPM, it's good to initiate it with NPM.

npm init --scope=@alvinend

I want my application to be accessible via npx @alvinend/tic-tac-toe-cli.
To do that, we can put scoped option
--scope=@user-name and replace your "user-name with your username. More Info: https://docs.npmjs.com/cli/v8/using-npm/scope.

Install Package

Here is the list of the package we need:

npm i chalk figlet inquirer

  1. chalk Basically add color to console.log
  2. figlet Make BIG text in a terminal
  3. inquirer Enable us to ask a question in terminal

Home

Start simple, writing what this application is all about, a tic tac toe game. But it's boring to console log the title. I wanted to go flashy. Fortunately, with Figlet, I could do that!

We start by making a file named index.js.

// index.js

console.log(figlet.textSync('Tic Tac Toe'))

Output:

And maybe there is someone who does not know tic tac toe's rule. So I added it.

// index.js

console.log(`

===============================================================================================================

${chalk.yellow('How To Play')}

${chalk.yellow('1. Have the first player go first')}

${chalk.yellow('2. Have the second player go second.')}

${chalk.yellow('3. Keep alternating moves until one of the players has drawn a row of three symbols or until no one can win.')}

${chalk.yellow('Any Question? Google it!')}

===============================================================================================================

`)

With chalk.js, we can color some text to make it less "terminal" like.
Output:

And we are done. The first step is to be CLI Developer.

Player

First, we make a class that defines Player, setting order the variable which tells if the player is first or second to make a move and name to record the player's name.

// player.js

export class Player {

constructor(order) {

this.order = order

this.name = `Player ${order}`

}

}

We want the player to put their name in, so we add a function in that class to ask the player what their name is. Using inquirer, we can do that easily.

// player.js

async init() {

const ans = await inquirer.prompt({

name: 'name',

type: 'input',

message: 'What is your name?',

default: `Player ${this.order}`

})

if (ans.name) {

this.name = ans.name

}

}

Finally, we want a function that lets players choose which spot they want to mark. Tic Tac Toe has nine spots, so we make an array of it.

// player.js

const MOVE_LIST = [

'0 (Top Left)',

'1 (Top Middle)',

'2 (Top Right)',

'3 (Middle Left)',

'4 (Middle Middle)',

'5 (Middle Right)',

'6 (Bottom Left)',

'7 (Bottom Middle)',

'8 (Bottom Right)',

]

But we don't want players to choose spots with a mark on it. So we make a function that asks the player to select only empty spots.

// player.js

async calcMove(board) {

const legalMoveList = MOVE_LIST.filter((_, index) => !board.table[index])

const ans = await inquirer.prompt({

name: 'move',

type: 'list',

message: `${this.name} Chose Your Move.`,

choices: legalMoveList

})

return MOVE_LIST.findIndex(move => move === ans.move)

}

That is it for players!

Board

Board is a place where the player can put marks on it. As said before, Tic Tac Toe contains nine spots. We start by making a class that has board information in it. 0 are empty spots, 1 are spots with player order one's mark (O), and 2 are spots with player order two's mark (X).

// board.js

export class Board {

constructor() {

this.table = [0, 0, 0, 0, 0, 0, 0, 0, 0]

}

}

If we want to make a board, we should print it like a board. Rather than printing the board's array, it makes sense to print a 2D board with marks on it.

// board.js

const MARKS = ['', 'O', 'X']

print() {

const arr = []

for (let i = 0; i < 3; i++) {

let row = []

for (let j = 0; j < 3; j++) {

row.push(MARKS[this.table[i * 3 + j]])

}

arr.push(row.join(' | '))

}

console.log(arr.join('\n') + '\n')

}

Now we get into building the game rule. First, we want to enable the player to play it. And to do that, the player needs to put their marks on board. So we make the function of it.

// board.js

async place(player) {

const pos = await player.calcMove(this)

if (this.table[pos] == 0) {

this.table[pos] = player.order

return true

}

console.log('Placement Error, Already someone there')

return false

}

A game is not a game if there is no winner. In Tic Tac Toe, you can win by putting three marks vertically, horizontally, or diagonally. There are many ways to do this. Here is my way. Feel free to make your version of it.

// board.js

checkIsWin(player) {

const checkList = [

[0, 1, 2],

[3, 4, 5],

[6, 7, 8],

[0, 3, 6],

[1, 4, 7],

[2, 5, 8],

[0, 4, 8],

[2, 4, 6]

]

for (let i = 0; i < checkList.length; i++) {

const check = checkList[i]

let count = 0

for (let i = 0; i < check.length; i++) {

if (this.table[check[i]] === player.order) {

count = count + 1

}

if (count === 3) {

return true

}

}

}

return false

}

And... we are done. We built a functional board class of Tic Tac Toe.

Match

We built Player and Board. The last thing we need is for those players to use Board and play with it.

  1. Declare board and player
  2. Loop to maximum move that Tic Tac Toe game can do (nine times)
  3. For each loop, the player places a mark on a spot, print the board, and check the winner
  4. Game end a player win or game reaches maximum move count

// match.js

import { Board } from "./board.js"

import { Player } from "./player.js"

export const startGame = async (board, firstPlayer, secondPlayer) => {

// Init Board and Player

board = new Board()

firstPlayer = new Player(1)

await firstPlayer.init()

secondPlayer = new Player(2)

await secondPlayer.init()

// For recording turn

let turn = 0

for (let i = 0; i < 9; i++) {

const inTurnPlayer = (turn % 2 + 1 === 1) ? firstPlayer : secondPlayer

await board.place(inTurnPlayer)

board.print()

// Check If has winner

if (board.checkIsWin(inTurnPlayer)) {

console.log(`${inTurnPlayer.name} won!`)

return

}

turn++

}

console.log('Draw!')

}

Call that function in index.js, and we are done!

// index.js

#!/usr/bin/env node

import chalk from "chalk";

import figlet from "figlet";

import { startGame } from "./match.js";

console.log(figlet.textSync('Tic Tac Toe'))

console.log(`

===============================================================================================================

${chalk.yellow('How To Play')}

${chalk.yellow('1. Have the first player go first')}

${chalk.yellow('2. Have the second player go second.')}

${chalk.yellow('3. Keep alternating moves until one of the players has drawn a row of three symbols or until no one can win.')}

${chalk.yellow('Any Question? Google it!')}

===============================================================================================================

`)

startGame()

Publishing CLI is as easy as entering one line of command in the terminal.

npm publish

If this is your first time, you might run into errors, but almost everybody uses and publishes npm's packages, google, and you are set to go.

Congratulations, you published your own CLI application!
In this article, I focused on building our own CLI and Tic Tac Toe. I hope it gives you a grasp of how npm CLI works.

If you are interested, here is my link to the complete code on this application

https://github.com/alvinend/tic-tac-toe-cli

FAQs

How many X's and O's do you need for tic-tac-toe? ›

For traditional tic-tac-toe game you need 10 game pieces, with 5 x's and 5 o's. But, I like to add a few extras of both the x's and o's in case some pieces go missing.

How do you make a tic Tactoe game? ›

General order of steps to implement:

Create a Tic Tac Toe board and fill it with dashes. Create a function that draws the board like a square. Keep track of the player's turn and what symbol they are using. Keep asking the user to enter a row and col until they are valid.

How many endings does tic-tac-toe have? ›

In actuality, tic-tac-toe players fill in each of the nine entries with one of only three values: an X, an O, or leave it blank. That's a total of 3*3*3*3*3*3*3*3*3 = 3^9 = 19,683 different ways the 3x3 grid can be filled in.

Is 4x4 tic-tac-toe possible? ›

3D Tic-tac-toe

One can play on a board of 4x4 squares, winning in several ways. Winning can include: four in a straight line, four in a diagonal line, four in a diamond, or four to make a square.

Can Player 1 always win tic-tac-toe? ›

If both players play optimally, the first player will always win if they place their first move in the center of the cube. This is the same fork strategy that is used by two-dimensional boards, except that in 3x3 cubes, this strategy always works.

Can I make a game using C++? ›

C++ allows you to develop games across various platforms, including Windows, Mac, Linux, Android, and iOS. You need a game engine to create games, and C++ is used in numerous 2D game engines and 3D game engines. Godot and Unreal Engine, for instance, use C++ as their scripting language.

How do you beat the impossible game mode on tic-tac-toe? ›

Play the game using the new “Impossible” mode.

Now, you can play Medium-difficulty tic tac toe on Google while disguising it as Impossible. Keep in mind that this is just for show; there's no way to beat the true Impossible mode!

What is the algorithm of tic-tac-toe game? ›

The key to the Minimax algorithm is a back and forth between the two players, where the player whose "turn it is" desires to pick the move with the maximum score. In turn, the scores for each of the available moves are determined by the opposing player deciding which of its available moves has the minimum score.

What game has the most endings? ›

15 Games With The Most Possible Endings, Depending On How You Play
  • 7/15 Tekken Tag Tournament 2 – 52.
  • 6/15 BlazBlue Continuum Shift Extend – 62.
  • 5/15 Time Travelers – 71.
  • 4/15 Princess Maker 2 – 74.
  • 3/15 428: Shibuya Scramble – 85.
  • 2/15 Star Ocean: The Second Story – 87.
  • 1/15 Star Ocean: Second Evolution – 100.
25 Feb 2021

How many endings have A Way Out? ›

What's interesting about A Way Out is that it can end in two different ways depending on an outcome that is fully determined by the players. While the route to find both versions of the A Way Out ending are similar, they each provide their own story that ties up the loose ends of the adventure.

What game has a lot of endings? ›

Alternate endings
GameRelease yearNumber of endings
428: In a Blockaded Shibuya200885
Der Langrisser199575
Princess Maker 2199374
Time Travelers201271
93 more rows

Can we learn NodeJS in 1 day? ›

It takes around 3 months to fully learn Node JS and be able to build a functional full-stack application. If you already know some other programming, you can get the basics down within a few week's time.

Is NodeJS easy to use? ›

Easy—Node. js is quite easy to start with. It's a go-to choice for web development beginners. With a lot of tutorials and a large community—getting started is very easy.

Is NodeJS good for beginners? ›

js—its entire tech stack is free for use and open-source. Node. js is also frequently listed as one of the best starters for beginner programmers because of its syntax and because JavaScript is an interpreted language.

Why is it called 4x4 and not 2x2? ›

The term 4×4 means a four-wheel-drive vehicle. Technically, the first digit is the number of wheels and the second is the number that are driven, so a four-wheel-drive pickup truck is a 4×4; a rear-wheel-drive one is a 4×2.

How do you play 4x4 tic-tac-toe? ›

The game takes place on a 4x4 board and involves two players, X and O. X starts and players take alternate turns. The object of the game is to place four of your pieces in a row, either vertically, horizontally, or diagonally.

How fast is 4 high? ›

The answer to the “how fast can you drive in 4 high” question is roughly 60mph. However, what happens when you go beyond that? Nothing, really. However, as mentioned before, if you are doing speeds upwards of 60mph you either don't need 4WD or are completely crazy.

Can player 2 ever win in tic tac toe? ›

How To Win Tic Tac Toe If You Go Second. Even when going second, it is possible to still win the game, especially if the first player doesn't employ the unbeatable strategy. It is easily possible to force a draw when you play second, but winning is a bit more complicated.

Why do gamers use C++? ›

The C++ programming language is exceptional with memory management, providing more control, flexibility, and optimization of gaming resources. The C++ programming language is compatible with popular gaming engines (like Unity and Unreal).

Is C# or C++ better for games? ›

Both C# and C++ can be used to create games. However, C++ has better control hardware on the PC or server. Therefore, it is usually a more suitable language for game development. However, both languages are for game development, especially knowing that you won't be creating games from scratch (usually).

Is C++ more powerful than Java? ›

When it comes to system programming and/or other low-level applications, C++ is more powerful. Some people might argue that having automatic GC collections, no pointers, no multiple inheritances make Java more powerful. But when it comes to speed, C++ is powerful.

Is tic tac toe a solved game? ›

Tic-Tac-Toe is a solved game; unless a player makes a dumb mistake, every game will end in a draw. The board game Connect Four has been solved: The first player will always win if they make the perfect moves, regardless of what the other player does.

Can you beat the impossible game? ›

Never skip a question.

The game lets you earn "Skips" which can be used to skip some questions if you get stuck, but don't be tempted! It is impossible to beat the game unless you have all seven "Skips" unused on question 110 (the last question).

How do you beat level 13 on the impossible quiz? ›

Question 13 of the Impossible Quiz Book asks "What do feet eat for breakfast?". The possible answers are "Toast", "Corn flakes", " Crossiants " and "Bacon". The correct one is "Corn flakes", because corns are areas of hard skin on the feet that have been exposed to excessive pressure or friction. Tasty!

How do you solve the Tic Tac logic puzzle? ›

The object is to place X or O in remaining squares so there are no more than two consecutive X's or O's in a row or a column, the number of X's is the same as the number of O's in each row and column, and all rows and all columns are unique.

Is tic-tac-toe 3 or 4 in a row? ›

Tic-Tac-Toe is one of the simplest games you can play with pen and paper. Here are the rules: Let's say you mark X and your friend marks O. Players take turns marking empty boxes in a 3 × 3 grid. To win, you must get your three marks in a row (vertically, horizontally, or diagonally) before your friend does.

How many ways can you solve 3d Tic-Tac-Toe? ›

There are 76 different possibilities for a win (16 rows in each direction, 2 diagonals per face in each direction (which makes 12 faces), and then 4 corner-to-corner diagonals), and this algorithm checks each one in sequence.

What is the longest game title? ›

The longest title for a video game in English is 'Cthulhu Saves the World: Super Hyper Enhanced Championship Edition Alpha Diamond DX Plus Alpha FES HD – Premium Enhanced Game of the Year Collector's Edition (without Avatars!)'

What is the longest game to complete? ›

The Elder Scrolls 5: Skyrim is a contender for the greatest game of all time. It is, however, an open-world game that takes the longest to beat. Quests in The Elder Scrolls V: Skyrim regenerate, so there is seemingly no end to the game.

What is the longest game to fully complete? ›

The Legend Of Zelda: Breath Of The Wild Clocks 97.5 Hours

Completionists can expect to put 189 hours into this game. As the first open-world Zelda, it's fitting that Breath of the Wild is expansive and filled with content. Much of that completionist time will come from hunting down the game's 900 Korok Seeds, though.

Is Leo dead in A Way Out? ›

Ending. In one ending, Vincent grabs the gun first and shoots Leo in the chest. Both realizing that this is the end, they both grab each other's hands until Leo dies from the gunshot.

Does Vincent betray Leo? ›

During the cutscene, the Leo doll will express how he is still mad at Vincent for betraying him and seemingly not feeling sorry, Vincent will ask Leo what he will do about it.

Which brother dies in A Way Out? ›

Gary Moretti is the brother of Vincent. He is seen in some cut scenes and is a Police Officer, like Vincent. Gary was shot in the head by Harvey, resulting in his death.

What are the 3 types of endings? ›

The six types of story endings include:
  • Resolved ending.
  • Unresolved ending.
  • Expanded ending.
  • Unexpected ending.
  • Ambiguous ending.
  • Tied ending.
11 Nov 2021

Do you copy game all endings? ›

Multiple Endings: The game has four distinct endings. The hiker dies. Fail to send the hiker to safety and do not turn on the lights again, and the Goatman will kill him. The watchman dies.

How many shot glasses do you need for tic-tac-toe? ›

To win, simply get three shot glasses in a row loser has to drink. 2 Player Drinking Game set contains 8" x 8" etched glass playing board with rubber corner-pads and nine, 2, 1oz. shot glasses. Always play responsibly.

How many boxes do you need for tic-tac-toe? ›

When all 9 squares are full, the game is over. If no player has 3 marks in a row, the game ends in a tie.

How many win lines are there on a 3x3 tic-tac-toe board? ›

In the game of Tic Tac Toe (i.e. noughts and crosses) there are 8 distinct winning lines. Investigate how many distinct winning lines there are in a game played on a 3 by 3 by 3 board, with 27 cells. A winning line connects 3 cells.

How many shots are in a 12 bottle? ›

To recap, one full-sized (750 ml) bottle of whiskey equals: 25 one-ounce shots. 16 one-and-a-half ounce shots. 12 two-ounce shots.

How many shots is a cap full? ›

Caps on liquor bottles should be able to hold one shots worth of liquid. That way you don't need a shot glass to measure.

How much do you fill a shot glass for one shot? ›

The accepted amount of liquor served in a shot glass in the U.S. is 1.5 ounces or 44 milliliters. Even though the government has never officially set a standard measurement for a shot, the state of Utah formally defines it as 1.5 fluid ounces.

How do you beat tic-tac-toe on impossible mode? ›

Put your first X in any corner.

In Impossible mode, the computer will typically respond by placing an O in the center space of the board. It's possible to win against normal opponents even if they place their O in the center space. However, since Impossible mode is programmed not to lose, you'll tie instead.

Who goes first in Tictactoe? ›

The first player is known as X(White pieces) and the second is O(Black pieces). Players alternate placing Xs and Os on the game board until either opponent has three in a row or all nine squares are filled. X always goes first, and if no one has three in a row, the stalemate is called a cat game.

Is tic-tac-toe a solved game? ›

Tic-Tac-Toe is a solved game; unless a player makes a dumb mistake, every game will end in a draw. The board game Connect Four has been solved: The first player will always win if they make the perfect moves, regardless of what the other player does.

How do you play 5 stones step by step? ›

The player throws all five stones onto the ground. The opponent selects the stone to be thrown into the air. The player throws the selected stone and sweeps up the others on the ground and then catches the falling stone. When all these steps are completed, the player scores a point and starts from Step 3 again.

How do I figure out how many rocks I need? ›

How much landscaping rock do I need?
  1. Calculating Rock Needs.
  2. L × W = Square footage of coverage area.
  3. Square feet of coverage area ÷ coverage area per 1 ton = tons of rock needed.

How do you play 3x3 tic-tac-toe? ›

There are 9 games of 3x3 tic-tac-toe on the board.
...
How to play
  1. Each turn, you mark one of the small squares.
  2. When you get three in a row on a small board, you've won that board.
  3. To win the game, you need to win three small boards in a row.
  4. You don't get to pick which of the nine boards to play on.

How do you play 5 in a row in tic-tac-toe? ›

Players alternate placing Xs and Os on the board until either one player has three in a row, horizontally, vertically, or diagonally. If a player is able to draw five of their Xs or three of their Os in a row, then that player wins.

How do you always win tic-tac-toe 4x4? ›

4x4 tic-tac-toe is played on a board with four rows (numbered 0 to 3 from top to bottom) and 4 columns (numbered 0 to 3 from left to right). X is always going to make the first move. The game is won by the first player to get four of their pieces on the same row, column, or diagonal(2 main diagonals only).

Is there a bigger tic-tac-toe? ›

You can choose the classic 3x3 version or try the 5x5 or 7x7 larger versions of Tic Tac Toe. In these version you have to get 4 in a row to win.

Top Articles
Latest Posts
Article information

Author: Foster Heidenreich CPA

Last Updated: 02/01/2023

Views: 6693

Rating: 4.6 / 5 (76 voted)

Reviews: 91% of readers found this page helpful

Author information

Name: Foster Heidenreich CPA

Birthday: 1995-01-14

Address: 55021 Usha Garden, North Larisa, DE 19209

Phone: +6812240846623

Job: Corporate Healthcare Strategist

Hobby: Singing, Listening to music, Rafting, LARPing, Gardening, Quilting, Rappelling

Introduction: My name is Foster Heidenreich CPA, I am a delightful, quaint, glorious, quaint, faithful, enchanting, fine person who loves writing and wants to share my knowledge and understanding with you.