Created
March 24, 2019 16:58
-
-
Save giacomoferretti/fb002ab21495bd395f1a144e59b1d8ba to your computer and use it in GitHub Desktop.
Rock Paper Scissors written in Go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import "fmt" | |
import "math/rand" | |
import "os" | |
import "os/exec" | |
import "time" | |
func main() { | |
clearScreen() | |
fmt.Println(" ┌─── Rock Paper Scissors ───┐ ") | |
fmt.Println(" │ v1.0 │ ") | |
fmt.Println(" └───────────────────────────┘ ") | |
fmt.Println(" ROCK PAPER SCISSORS ") | |
fmt.Println(" 1 2 3 ") | |
fmt.Println() | |
rand.Seed(time.Now().UnixNano()) | |
p2 := randBetween(1, 4) | |
var p1 int | |
for p1 < 1 || p1 > 3 { | |
fmt.Print("Choose a number [1-3]: ") | |
fmt.Scan(&p1) | |
if (p1 < 1 || p1 > 3) { | |
fmt.Println("You must choose a number between 1 and 3. Retry.") | |
fmt.Println() | |
} | |
} | |
fmt.Println() | |
fmt.Println("You chose", printMove(p1)) | |
fmt.Println() | |
fmt.Println("The CPU chose", printMove(p2)) | |
if p1 == p2 { | |
fmt.Println() | |
fmt.Println(printMove(p1), "==", printMove(p2)) | |
fmt.Println("It's a draw.") | |
} else if (p1 == 1 && p2 == 3) || (p1 == 2 && p2 == 1) || (p1 == 3 && p2 == 2) { | |
fmt.Println() | |
fmt.Println(printMove(p1), "=>", printMove(p2)) | |
fmt.Println("YOU WON!") | |
} else { | |
fmt.Println() | |
fmt.Println(printMove(p1), "<=", printMove(p2)) | |
fmt.Println("You lost. :(") | |
} | |
} | |
func randBetween(min, max int) int { | |
return min + rand.Intn(max - min) | |
} | |
func printMove(move int) string { | |
switch (move) { | |
case 1: | |
return "ROCK" | |
case 2: | |
return "PAPER" | |
case 3: | |
return "SCISSORS" | |
default: | |
return "ERROR" | |
} | |
} | |
func clearScreen() { | |
c := exec.Command("clear") | |
c.Stdout = os.Stdout | |
c.Run() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment