Golang
Golang

 

This tutorial demonstrates how to create a simple Memory Matching Game using the Go programming language. The game involves matching pairs of cards that are hidden and the player needs to find all pairs by flipping the cards.

Objective:

The objective of the game is to reveal matching pairs of cards by flipping them over. Players need to match all the cards with the least number of moves. The game is over when all pairs are matched correctly.

Code for Memory Matching Game in Go:

package main

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

type Card struct {
    Value string
    Flipped bool
}

func main() {
    // Initialize deck of cards
    deck := []Card{
        {"A", false}, {"A", false}, {"B", false}, {"B", false},
        {"C", false}, {"C", false}, {"D", false}, {"D", false},
        {"E", false}, {"E", false}, {"F", false}, {"F", false},
    }

    // Shuffle the deck
    rand.Seed(time.Now().UnixNano())
    rand.Shuffle(len(deck), func(i, j int) {
        deck[i], deck[j] = deck[j], deck[i]
    })

    // Game loop
    var moves int
    for {
        fmt.Println("Memory Matching Game!")
        fmt.Println("Cards:")
        displayBoard(deck)

        var card1, card2 int
        fmt.Print("Select the first card to flip (0-11): ")
        fmt.Scan(&card1)

        if deck[card1].Flipped {
            fmt.Println("Card already flipped. Choose another card.")
            continue
        }

        deck[card1].Flipped = true
        displayBoard(deck)

        fmt.Print("Select the second card to flip (0-11): ")
        fmt.Scan(&card2)

        if card1 == card2 || deck[card2].Flipped {
            fmt.Println("Invalid choice. Choose another card.")
            deck[card1].Flipped = false
            continue
        }

        deck[card2].Flipped = true
        displayBoard(deck)

        if deck[card1].Value == deck[card2].Value {
            fmt.Println("Match found!")
        } else {
            fmt.Println("No match. Try again.")
            deck[card1].Flipped = false
            deck[card2].Flipped = false
        }

        moves++
        if allMatched(deck) {
            fmt.Printf("Game over! You completed the game in %d moves.\n", moves)
            break
        }
    }
}

// Function to display the board
func displayBoard(deck []Card) {
    for i, card := range deck {
        if card.Flipped {
            fmt.Printf("%s ", card.Value)
        } else {
            fmt.Print("[ ] ")
        }

        if (i+1)%4 == 0 {
            fmt.Println()
        }
    }
    fmt.Println()
}

// Function to check if all cards are matched
func allMatched(deck []Card) bool {
    for _, card := range deck {
        if !card.Flipped {
            return false
        }
    }
    return true
}

Explanation of Program Structure:

The program begins by initializing a deck of cards, each represented by a struct containing a value and a boolean indicating whether the card is flipped or not. The deck consists of 6 pairs of cards (A, B, C, D, E, F).

The deck is shuffled using the rand.Shuffle function to randomize the cards. The game proceeds with the user selecting two cards in each turn. If the cards match, they remain flipped; otherwise, they are turned back.

The game continues until all pairs of cards are matched, and the number of moves taken to finish the game is displayed.

Key Functions:

  • displayBoard: This function prints the current state of the game board, showing the flipped cards and hiding the rest.
  • allMatched: Checks if all cards are flipped and matched.

How to Run the Program:

  1. Make sure you have Go installed on your system. You can download it from the official website: https://golang.org/dl/
  2. Create a new file with a .go extension (e.g., memory_game.go).
  3. Copy and paste the code provided above into the file.
  4. Open your terminal and navigate to the directory where the file is located.
  5. Run the program using the command: go run memory_game.go.
  6. Follow the prompts in the terminal to play the game.
© 2025 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 :)