golang-exercises/golangr/file-reader/main.go

133 lines
2.2 KiB
Go

package main
import (
"bufio"
"fmt"
"math/rand"
"os"
"strconv"
"strings"
"time"
//"time"
//"strconv"
)
type PlayerStats struct {
name string
lives int8
}
func clear() {
fmt.Print("\033[H\033[2J")
}
var player PlayerStats
var names = []string{}
var err error
var guess string
var guessLetter rune
func scanLine() (line string) {
in := bufio.NewReader(os.Stdin)
lineNew, err := in.ReadString('\n')
catchErr(err)
line = strings.Trim(lineNew, "\n")
return line
}
func main() {
if len(os.Args) < 2 || len(os.Args) > 2 {
fmt.Println("Usage: ./file-reader names.txt")
os.Exit(1)
}
for {
clear()
fmt.Printf("Welcome to the hanged man game!\nMay I know your name?\nName: ")
// _, err = fmt.Scanln(&player.name)
// catchErr(err)
player.name = scanLine()
fmt.Printf("How many lives would you like to have?\nLives: ")
stringLives := scanLine()
//TODO: fix this garbage
intLives, err := strconv.Atoi(stringLives)
catchErr(err)
player.lives = int8(intLives)
clear()
fmt.Printf("Name: %v\n", player.name)
fmt.Printf("Lives: %v\n", player.lives)
fmt.Printf("Is this correct? [y/n] ")
var choice string
_, err = fmt.Scanln(&choice)
catchErr(err)
if choice == "y" {
game()
}
}
//
// fmt.Printf("The chosen name is %v\n", randWord)
// fmt.Scanln(&guessLetter)
}
func gameStatus() {
clear()
fmt.Println("Player:", player.name)
fmt.Println("Lives:", player.lives)
}
func game() {
clear()
filePath := os.Args[1]
randWord := getWord(filePath)
for {
gameStatus()
if player.lives < 0 {
fmt.Println("You lose!")
os.Exit(0)
}
fmt.Printf("Guess: ")
fmt.Scanln(&guess)
if guess == randWord {
fmt.Println("You win!")
os.Exit(0)
} else {
fmt.Printf("Wrong!")
player.lives--
time.Sleep(1 * time.Second)
clear()
}
}
}
func catchErr(err error) {
if err != nil {
fmt.Println(err)
os.Exit(2)
}
}
func getWord(path string) (word string) {
file, err := os.Open(path)
if err != nil {
fmt.Println(err)
os.Exit(2)
}
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
names = append(names, scanner.Text())
}
randName := names[rand.Intn(len(names)-0)]
return randName
}