Creating a Go Command-Line Quiz Game

Table of Contents

  1. Introduction
  2. Prerequisites
  3. Setup
  4. Creating the Quiz Game 1. Reading the Quiz File 2. Parsing the Quiz 3. Displaying the Quiz 4. Calculating Score

  5. Conclusion

Introduction

Welcome to the tutorial on creating a Go command-line quiz game! In this tutorial, we will learn how to build a simple quiz game that can be played on the command-line interface. By the end of this tutorial, you will have a basic understanding of Go syntax and packages, and be able to create a functional quiz game.

Prerequisites

Before starting this tutorial, you should have a basic understanding of the Go programming language. Familiarity with command-line interfaces and text file handling would be beneficial.

Setup

To follow along with this tutorial, you need to have Go installed on your system. You can download Go from the official website and follow the installation instructions provided. Once you have Go installed, create a new directory for our project.

Now, let’s create a new Go module by running the following command in the terminal:

go mod init quiz

This command initializes a new Go module named “quiz” in our project directory.

Creating the Quiz Game

Reading the Quiz File

Our quiz game will read questions and answers from a file. Create a new file named quiz.csv in your project directory. In this file, each line will contain a question followed by a comma and then the corresponding answer.

For example:

What is the capital of France?,Paris
Who painted the Mona Lisa?,Leonardo da Vinci

Now, let’s create a function readQuizFile in a new file named quiz.go. This function will read the quiz file and return a slice of Problem struct.

package main

import (
	"encoding/csv"
	"os"
)

type Problem struct {
	Question string
	Answer   string
}

func readQuizFile(filename string) ([]Problem, error) {
	file, err := os.Open(filename)
	if err != nil {
		return nil, err
	}
	defer file.Close()

	reader := csv.NewReader(file)
	lines, err := reader.ReadAll()
	if err != nil {
		return nil, err
	}

	problems := make([]Problem, len(lines))
	for i, line := range lines {
		problems[i] = Problem{
			Question: line[0],
			Answer:   line[1],
		}
	}

	return problems, nil
}

Parsing the Quiz

Next, we need to parse the command-line arguments to get the name of the quiz file. Update the main function in quiz.go as follows:

package main

import (
	"fmt"
	"os"
)

func main() {
	if len(os.Args) != 2 {
		fmt.Println("Usage: go run quiz.go <quiz-file>")
		os.Exit(1)
	}

	filename := os.Args[1]

	problems, err := readQuizFile(filename)
	if err != nil {
		fmt.Printf("Failed to read file: %s\n", err)
		os.Exit(1)
	}

	// Rest of the code goes here...
}

Now, our program will display the usage message when the quiz file is not provided as a command-line argument.

Displaying the Quiz

Let’s create a function named playQuiz that will display the questions one by one and prompt the user for answers. Update the main function as follows:

package main

import (
	"bufio"
	"fmt"
	"os"
	"strings"
)

func playQuiz(problems []Problem) {
	reader := bufio.NewReader(os.Stdin)
	correct := 0

	for i, problem := range problems {
		fmt.Printf("Problem #%d: %s = ", i+1, problem.Question)

		answer, _ := reader.ReadString('\n')
		answer = strings.TrimSpace(answer)
		if answer == problem.Answer {
			correct++
		}
	}

	fmt.Printf("You scored %d out of %d.\n", correct, len(problems))
}

Calculating Score

Finally, let’s call the playQuiz function in the main function:

package main

import (
	"fmt"
	"os"
)

func main() {
	if len(os.Args) != 2 {
		fmt.Println("Usage: go run quiz.go <quiz-file>")
		os.Exit(1)
	}

	filename := os.Args[1]

	problems, err := readQuizFile(filename)
	if err != nil {
		fmt.Printf("Failed to read file: %s\n", err)
		os.Exit(1)
	}

	playQuiz(problems)
}

Now, if you run the program with the command go run quiz.go quiz.csv, it will display the questions one by one and prompt the user for answers. After answering all the questions, it will display the score.

Conclusion

Congratulations! You have successfully created a Go command-line quiz game. In this tutorial, we learned how to read a quiz file, parse the file contents, display the quiz, and calculate the score. You now have the foundation to build more advanced features, such as timers or randomized questions.

Feel free to explore additional Go packages to enhance the functionality and user experience of your quiz game. Remember to regularly practice and apply your knowledge to reinforce what you have learned. Happy coding!