Golang
Golang

 

 

Introduction

Tic-Tac-Toe is a classic game that is simple to play but challenging to master. This program enhances the traditional Tic-Tac-Toe game by adding a simple AI opponent. The AI employs basic strategies to compete against the player, ensuring an engaging experience.

Objective

The primary goal of this program is to demonstrate how to implement a simple AI for Tic-Tac-Toe using the Go programming language. It highlights core programming concepts such as game logic, input validation, and AI decision-making.

Code

        package main

        import (
            "fmt"
            "math/rand"
            "time"
        )

        const (
            empty = " "
            player = "X"
            ai = "O"
        )

        func main() {
            board := [3][3]string{
                {empty, empty, empty},
                {empty, empty, empty},
                {empty, empty, empty},
            }

            for {
                printBoard(board)
                playerMove(&board)
                if checkWin(board, player) {
                    printBoard(board)
                    fmt.Println("You win!")
                    break
                }
                if isBoardFull(board) {
                    printBoard(board)
                    fmt.Println("It's a draw!")
                    break
                }
                aiMove(&board)
                if checkWin(board, ai) {
                    printBoard(board)
                    fmt.Println("AI wins!")
                    break
                }
                if isBoardFull(board) {
                    printBoard(board)
                    fmt.Println("It's a draw!")
                    break
                }
            }
        }

        func printBoard(board [3][3]string) {
            fmt.Println("\nCurrent Board:")
            for _, row := range board {
                fmt.Printf("%s | %s | %s\n", row[0], row[1], row[2])
                fmt.Println("---------")
            }
        }

        func playerMove(board *[3][3]string) {
            var row, col int
            for {
                fmt.Print("Enter your move (row and column: 0, 1, or 2): ")
                fmt.Scan(&row, &col)
                if row >= 0 && row < 3 && col >= 0 && col < 3 && board[row][col] == empty {
                    board[row][col] = player
                    break
                }
                fmt.Println("Invalid move. Try again.")
            }
        }

        func aiMove(board *[3][3]string) {
            rand.Seed(time.Now().UnixNano())
            for {
                row := rand.Intn(3)
                col := rand.Intn(3)
                if board[row][col] == empty {
                    board[row][col] = ai
                    fmt.Printf("AI moves to %d, %d\n", row, col)
                    break
                }
            }
        }

        func checkWin(board [3][3]string, symbol string) bool {
            for i := 0; i < 3; i++ {
                if board[i][0] == symbol && board[i][1] == symbol && board[i][2] == symbol {
                    return true
                }
                if board[0][i] == symbol && board[1][i] == symbol && board[2][i] == symbol {
                    return true
                }
            }
            if board[0][0] == symbol && board[1][1] == symbol && board[2][2] == symbol {
                return true
            }
            if board[0][2] == symbol && board[1][1] == symbol && board[2][0] == symbol {
                return true
            }
            return false
        }

        func isBoardFull(board [3][3]string) bool {
            for _, row := range board {
                for _, cell := range row {
                    if cell == empty {
                        return false
                    }
                }
            }
            return true
        }

Explanation

This program performs the following steps:

  1. Define constants: Symbols for the player, AI, and empty cells are defined for clarity.
  2. Initialize the board: A 3×3 array represents the Tic-Tac-Toe grid.
  3. Game loop: The game alternates between the player and AI until a win or draw occurs.
  4. Player and AI moves: The player manually selects a cell, while the AI randomly selects an available cell.
  5. Win and draw checks: The program checks rows, columns, and diagonals for a win and determines if the board is full for a draw.

How to Run

  1. Install Go from the official Go website.
  2. Copy the code into a file named tic_tac_toe_ai.go.
  3. Run the program using the command:
                    go run tic_tac_toe_ai.go
    
  4. Follow the prompts to play against the AI.
© 2024 Learn Programming. All rights reserved.

 

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

Your email address will not be published. Required fields are marked *

error

Enjoy this blog? Please spread the word :)