How to write the 7 Boom game. If a number is divided by 7 or includes the digit 7, the user writes Boom in Go

1 Answer

0 votes
package main

// 7 Boom game. The user enters a number he wants to start the game, 
// (-1 to end the game, or lost), then the user enters numbers, from the number he entered
// If the current number is divisible by 7, or one of its digits is 7, 
// And the user did not write the word 'Boom', the user loses. 

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

func containsSeven(num int) bool {
    return strings.Contains(strconv.Itoa(num), "7")
}

func isBoom(num int) bool {
    return num%7 == 0 || containsSeven(num)
}

func getUserInput(prompt string) string {
    fmt.Print(prompt)
    scanner := bufio.NewScanner(os.Stdin)
    scanner.Scan()
    return strings.TrimSpace(scanner.Text())
}

func processTurn(expected int, input string) bool {
    lower := strings.ToLower(input)
    shouldBoom := isBoom(expected)

    if shouldBoom {
        if lower != "boom" {
            fmt.Printf("%s (should be Boom)\n", input)
            fmt.Println("YOU LOSE!")
            return false
        }
    } else {
        if lower == "boom" {
            fmt.Printf("Wrong move! It was %d\n", expected)
            fmt.Println("YOU LOSE!")
            return false
        }

        value, err := strconv.Atoi(input)
        if err != nil || value != expected {
            fmt.Printf("Wrong move! It was %d\n", expected)
            fmt.Println("YOU LOSE!")
            return false
        }
    }

    return true
}

func runGame() {
    startInput := getUserInput("Enter a number from which you want to start the game (-1 to exit): ")

    startNum, err := strconv.Atoi(startInput)
    if err != nil || startNum == -1 {
        return
    }

    current := startNum

    for {
        input := getUserInput("Enter a number (or Boom): ")

        if input == "-1" {
            fmt.Println("Game Over!")
            break
        }

        if !processTurn(current, input) {
            break
        }

        current++
    }
}

func main() {
    runGame()
}




/*
run:

Enter a number from which you want to start the game (-1 to exit): 6
Enter a number (or Boom): 6
Enter a number (or Boom): Boom
Enter a number (or Boom): 8
Enter a number (or Boom): 9
Enter a number (or Boom): 10
Enter a number (or Boom): 11
Enter a number (or Boom): 12
Enter a number (or Boom): 13
Enter a number (or Boom): Boom
Enter a number (or Boom): 15
Enter a number (or Boom): 16
Enter a number (or Boom): Boom
Enter a number (or Boom): 18
Enter a number (or Boom): 19
Enter a number (or Boom): 20
Enter a number (or Boom): 21
21 (should be Boom)
YOU LOSE!

*/

 



answered Mar 15 by avibootz
edited Mar 16 by avibootz
...