Scrabble Word Score Calculator in Go
Introduction
Scrabble is a popular word game where players earn points based on the letters used in forming words. Each letter in Scrabble has a specific point value. In this tutorial, we will write a program in Go to calculate the score of a given Scrabble word.
The objective is to create a Go program that accepts a Scrabble word and computes its score based on the letter values as per the official Scrabble rules.
Code to Calculate Scrabble Word Score
package main
import (
"fmt"
"strings"
)
// Letter values according to Scrabble rules
var letterScores = map[rune]int{
'A': 1, 'B': 3, 'C': 3, 'D': 2, 'E': 1, 'F': 4, 'G': 2, 'H': 4, 'I': 1,
'J': 8, 'K': 5, 'L': 1, 'M': 3, 'N': 1, 'O': 1, 'P': 3, 'Q': 10, 'R': 1,
'S': 1, 'T': 1, 'U': 1, 'V': 4, 'W': 4, 'X': 8, 'Y': 4, 'Z': 10,
}
func calculateScore(word string) int {
word = strings.ToUpper(word) // Convert the word to uppercase
score := 0
for _, letter := range word {
score += letterScores[letter]
}
return score
}
func main() {
var word string
fmt.Println("Enter a Scrabble word:")
fmt.Scanln(&word)
score := calculateScore(word)
fmt.Printf("The Scrabble score for the word '%s' is: %d\n", word, score)
}
Explanation of the Program
This Go program works by using a map to store the Scrabble letter scores. Here’s a breakdown of the program:
- letterScores map: This map contains the point value for each letter in the alphabet as per Scrabble rules.
- calculateScore function: This function accepts a word, converts it to uppercase, and then calculates the total score by adding up the points for each letter in the word.
- main function: The user is prompted to input a word, which is then passed to the
calculateScore
function to compute the score. Finally, the result is printed to the console.
To run the program:
- Install Go on your machine, if you haven’t already. You can download it from here.
- Copy and paste the code into a file with a .go extension, for example,
scrabble_score.go
. - Open a terminal, navigate to the folder containing your
scrabble_score.go
file, and run the following command: - Enter a word when prompted, and the program will display the Scrabble score for that word.
go run scrabble_score.go