Introduction
Tic-Tac-Toe is a classic two-player game that is both fun and a great way to understand basic programming concepts like arrays, loops, and conditionals.
In this project, we will implement a simple console-based Tic-Tac-Toe game in Go.
Objective
The objective of this project is to create an interactive Tic-Tac-Toe game that allows two players to compete in turns.
This project helps learners understand Go programming by practicing with arrays, functions, and user input.
Code
package main
import (
"fmt"
)
// Initialize the game board
var board = [3][3]string{
{" ", " ", " "},
{" ", " ", " "},
{" ", " ", " "},
}
// Display the current game board
func displayBoard() {
fmt.Println("Current Board:")
for i := 0; i < 3; i++ {
fmt.Printf(" %s | %s | %s \n", board[i][0], board[i][1], board[i][2])
if i < 2 {
fmt.Println("---+---+---")
}
}
}
// Check if there is a winner
func checkWinner() (bool, string) {
// Check rows, columns, and diagonals
winPatterns := [][][2]int{
{{0, 0}, {0, 1}, {0, 2}}, // Row 1
{{1, 0}, {1, 1}, {1, 2}}, // Row 2
{{2, 0}, {2, 1}, {2, 2}}, // Row 3
{{0, 0}, {1, 0}, {2, 0}}, // Column 1
{{0, 1}, {1, 1}, {2, 1}}, // Column 2
{{0, 2}, {1, 2}, {2, 2}}, // Column 3
{{0, 0}, {1, 1}, {2, 2}}, // Diagonal 1
{{0, 2}, {1, 1}, {2, 0}}, // Diagonal 2
}
for _, pattern := range winPatterns {
first := board[pattern[0][0]][pattern[0][1]]
if first != " " && first == board[pattern[1][0]][pattern[1][1]] && first == board[pattern[2][0]][pattern[2][1]] {
return true, first
}
}
return false, ""
}
// Check if the board is full
func isBoardFull() bool {
for i := 0; i < 3; i++ {
for j := 0; j < 3; j++ {
if board[i][j] == " " {
return false
}
}
}
return true
}
// Main function to play the game
func main() {
fmt.Println("Welcome to Tic-Tac-Toe!")
displayBoard()
player := "X"
for {
var row, col int
fmt.Printf("Player %s, enter your move (row and column, e.g., 0 1): ", player)
_, err := fmt.Scanf("%d %d", &row, &col)
if err != nil || row < 0 || row > 2 || col < 0 || col > 2 || board[row][col] != " " {
fmt.Println("Invalid move. Try again.")
continue
}
// Make the move
board[row][col] = player
displayBoard()
// Check for a winner
if winner, mark := checkWinner(); winner {
fmt.Printf("Player %s wins!\n", mark)
break
}
// Check for a draw
if isBoardFull() {
fmt.Println("It's a draw!")
break
}
// Switch players
if player == "X" {
player = "O"
} else {
player = "X"
}
}
}
Explanation
The program structure is as follows:
- Game Board: A 3×3 array represents the Tic-Tac-Toe board, initialized with empty spaces.
- Display Board: The
displayBoard
function displays the current state of the board to the players. - Winning Logic: The
checkWinner
function checks rows, columns, and diagonals for a winning pattern. - Player Input: The program prompts each player to enter their move, validates the input, and updates the board.
- Game Loop: The main game loop alternates between players until a win or a draw occurs.
How to Run the Program
- Ensure you have Go installed on your system. You can download it from
Go’s official website. - Save the code in a file named
tic_tac_toe.go
. - Open a terminal and navigate to the directory containing the file.
- Run the program with the following command:
go run tic_tac_toe.go
- Follow the on-screen instructions to play the game.
Copyright © Learn Programming. All rights reserved.