Merge pull request #819 from spasticus74/main

add go for Acey Ducey
This commit is contained in:
Jeff Atwood
2022-10-12 16:46:49 -07:00
committed by GitHub
3 changed files with 488 additions and 0 deletions

View File

@@ -0,0 +1,112 @@
package main
import (
"bufio"
"fmt"
"math/rand"
"os"
"sort"
"strconv"
"strings"
"time"
)
var welcome = `
Acey-Ducey is played in the following manner
The dealer (computer) deals two cards face up
You have an option to bet or not bet depending
on whether or not you feel the card will have
a value between the first two.
If you do not want to bet, input a 0
`
func main() {
rand.Seed(time.Now().UnixNano())
scanner := bufio.NewScanner(os.Stdin)
fmt.Println(welcome)
for {
play(100)
fmt.Println("TRY AGAIN (YES OR NO)")
scanner.Scan()
response := scanner.Text()
if strings.ToUpper(response) != "YES" {
break
}
}
fmt.Println("O.K., HOPE YOU HAD FUN!")
}
func play(money int) {
scanner := bufio.NewScanner(os.Stdin)
var bet int
for {
// Shuffle the cards
cards := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14}
rand.Shuffle(len(cards), func(i, j int) { cards[i], cards[j] = cards[j], cards[i] })
// Take the first two for the dealer and sort
dealerCards := cards[0:2]
sort.Ints(dealerCards)
fmt.Printf("YOU NOW HAVE %d DOLLARS.\n\n", money)
fmt.Printf("HERE ARE YOUR NEXT TWO CARDS:\n%s\n%s", getCardName(dealerCards[0]), getCardName(dealerCards[1]))
fmt.Printf("\n\n")
//Check if Bet is Valid
for {
fmt.Println("WHAT IS YOUR BET:")
scanner.Scan()
b, err := strconv.Atoi(scanner.Text())
if err != nil {
fmt.Println("PLEASE ENTER A POSITIVE NUMBER")
continue
}
bet = b
if bet == 0 {
fmt.Printf("CHICKEN!\n\n")
goto there
}
if (bet > 0) && (bet <= money) {
break
}
}
// Draw Players Card
fmt.Printf("YOUR CARD: %s\n", getCardName(cards[2]))
if (cards[2] > dealerCards[0]) && (cards[2] < dealerCards[1]) {
fmt.Println("YOU WIN!!!")
money = money + bet
} else {
fmt.Println("SORRY, YOU LOSE")
money = money - bet
}
fmt.Println()
if money <= 0 {
fmt.Printf("%s\n", "SORRY, FRIEND, BUT YOU BLEW YOUR WAD.")
return
}
there:
}
}
func getCardName(c int) string {
switch c {
case 11:
return "JACK"
case 12:
return "QUEEN"
case 13:
return "KING"
case 14:
return "ACE"
default:
return strconv.Itoa(c)
}
}

View File

@@ -0,0 +1,217 @@
package main
import (
"bufio"
"fmt"
"log"
"math/rand"
"os"
"strconv"
"time"
)
func main() {
rand.Seed(time.Now().UnixNano())
printWelcome()
h, w := getDimensions()
m := NewMaze(h, w)
m.draw()
}
type direction int64
const (
LEFT direction = iota
UP
RIGHT
DOWN
)
const (
EXIT_DOWN = 1
EXIT_RIGHT = 2
)
type maze struct {
width int
length int
used [][]int
walls [][]int
enterCol int
}
func NewMaze(w, l int) maze {
if (w < 2) || (l < 2) {
log.Fatal("invalid dimensions supplied")
}
m := maze{width: w, length: l}
m.used = make([][]int, l)
for i := range m.used {
m.used[i] = make([]int, w)
}
m.walls = make([][]int, l)
for i := range m.walls {
m.walls[i] = make([]int, w)
}
// randomly determine the entry column
m.enterCol = rand.Intn(w)
// determine layout of walls
m.build()
// add an exit
col := rand.Intn(m.width - 1)
row := m.length - 1
m.walls[row][col] = m.walls[row][col] + 1
return m
}
func (m *maze) build() {
row := 0
col := 0
count := 2
for {
possibleDirs := m.getPossibleDirections(row, col)
if len(possibleDirs) != 0 {
row, col, count = m.makeOpening(possibleDirs, row, col, count)
} else {
for {
if col != m.width-1 {
col = col + 1
} else if row != m.length-1 {
row = row + 1
col = 0
} else {
row = 0
col = 0
}
if m.used[row][col] != 0 {
break
}
}
}
if count == (m.width*m.length)+1 {
break
}
}
}
func (m *maze) getPossibleDirections(row, col int) []direction {
possible_dirs := make(map[direction]bool, 4)
possible_dirs[LEFT] = true
possible_dirs[UP] = true
possible_dirs[RIGHT] = true
possible_dirs[DOWN] = true
if (col == 0) || (m.used[row][col-1] != 0) {
possible_dirs[LEFT] = false
}
if (row == 0) || (m.used[row-1][col] != 0) {
possible_dirs[UP] = false
}
if (col == m.width-1) || (m.used[row][col+1] != 0) {
possible_dirs[RIGHT] = false
}
if (row == m.length-1) || (m.used[row+1][col] != 0) {
possible_dirs[DOWN] = false
}
ret := make([]direction, 0)
for d, v := range possible_dirs {
if v {
ret = append(ret, d)
}
}
return ret
}
func (m *maze) makeOpening(dirs []direction, row, col, count int) (int, int, int) {
dir := rand.Intn(len(dirs))
if dirs[dir] == LEFT {
col = col - 1
m.walls[row][col] = int(EXIT_RIGHT)
} else if dirs[dir] == UP {
row = row - 1
m.walls[row][col] = int(EXIT_DOWN)
} else if dirs[dir] == RIGHT {
m.walls[row][col] = m.walls[row][col] + EXIT_RIGHT
col = col + 1
} else if dirs[dir] == DOWN {
m.walls[row][col] = m.walls[row][col] + EXIT_DOWN
row = row + 1
}
m.used[row][col] = count
count = count + 1
return row, col, count
}
// draw the maze
func (m *maze) draw() {
for col := 0; col < m.width; col++ {
if col == m.enterCol {
fmt.Print(". ")
} else {
fmt.Print(".--")
}
}
fmt.Println(".")
for row := 0; row < m.length; row++ {
fmt.Print("|")
for col := 0; col < m.width; col++ {
if m.walls[row][col] < 2 {
fmt.Print(" |")
} else {
fmt.Print(" ")
}
}
fmt.Println()
for col := 0; col < m.width; col++ {
if (m.walls[row][col] == 0) || (m.walls[row][col] == 2) {
fmt.Print(":--")
} else {
fmt.Print(": ")
}
}
fmt.Println(".")
}
}
func printWelcome() {
fmt.Println(" AMAZING PROGRAM")
fmt.Print(" CREATIVE COMPUTING MORRISTOWN, NEW JERSEY\n\n\n")
}
func getDimensions() (int, int) {
scanner := bufio.NewScanner(os.Stdin)
fmt.Println("Enter a width ( > 1 ):")
scanner.Scan()
w, err := strconv.Atoi(scanner.Text())
if err != nil {
log.Fatal("invalid dimension")
}
fmt.Println("Enter a height ( > 1 ):")
scanner.Scan()
h, err := strconv.Atoi(scanner.Text())
if err != nil {
log.Fatal("invalid dimension")
}
return w, h
}

View File

@@ -0,0 +1,159 @@
package main
import (
"bufio"
"fmt"
"log"
"os"
"strings"
)
type node struct {
text string
yesNode *node
noNode *node
}
func newNode(text string, yes_node, no_node *node) *node {
n := node{text: text}
if yes_node != nil {
n.yesNode = yes_node
}
if no_node != nil {
n.noNode = no_node
}
return &n
}
func (n *node) update(newQuestion, newAnswer, newAnimal string) {
oldAnimal := n.text
n.text = newQuestion
if newAnswer == "y" {
n.yesNode = newNode(newAnimal, nil, nil)
n.noNode = newNode(oldAnimal, nil, nil)
} else {
n.yesNode = newNode(oldAnimal, nil, nil)
n.noNode = newNode(newAnimal, nil, nil)
}
}
func (n *node) isLeaf() bool {
return (n.yesNode == nil) && (n.noNode == nil)
}
func listKnownAnimals(root *node) {
if root == nil {
return
}
if root.isLeaf() {
fmt.Printf("%s ", root.text)
return
}
if root.yesNode != nil {
listKnownAnimals(root.yesNode)
}
if root.noNode != nil {
listKnownAnimals(root.noNode)
}
}
func parseInput(message string, checkList bool, rootNode *node) string {
scanner := bufio.NewScanner(os.Stdin)
token := ""
for {
fmt.Println(message)
scanner.Scan()
inp := strings.ToLower(scanner.Text())
if checkList && inp == "list" {
fmt.Println("Animals I already know are:")
listKnownAnimals(rootNode)
fmt.Println()
}
if len(inp) > 0 {
token = inp
} else {
token = ""
}
if token == "y" || token == "n" {
break
}
}
return token
}
func avoidVoidInput(message string) string {
scanner := bufio.NewScanner(os.Stdin)
answer := ""
for {
fmt.Println(message)
scanner.Scan()
answer = scanner.Text()
if answer != "" {
break
}
}
return answer
}
func printIntro() {
fmt.Println(" Animal")
fmt.Println(" Creative Computing Morristown, New Jersey")
fmt.Println("\nPlay 'Guess the Animal'")
fmt.Println("Think of an animal and the computer will try to guess it")
}
func main() {
yesChild := newNode("Fish", nil, nil)
noChild := newNode("Bird", nil, nil)
rootNode := newNode("Does it swim?", yesChild, noChild)
printIntro()
keepPlaying := (parseInput("Are you thinking of an animal?", true, rootNode) == "y")
for keepPlaying {
keepAsking := true
actualNode := rootNode
for keepAsking {
if !actualNode.isLeaf() {
answer := parseInput(actualNode.text, false, nil)
if answer == "y" {
if actualNode.yesNode == nil {
log.Fatal("invalid node")
}
actualNode = actualNode.yesNode
} else {
if actualNode.noNode == nil {
log.Fatal("invalid node")
}
actualNode = actualNode.noNode
}
} else {
answer := parseInput(fmt.Sprintf("Is it a %s?", actualNode.text), false, nil)
if answer == "n" {
newAnimal := avoidVoidInput("The animal you were thinking of was a ?")
newQuestion := avoidVoidInput(fmt.Sprintf("Please type in a question that would distinguish a '%s' from a '%s':", newAnimal, actualNode.text))
newAnswer := parseInput(fmt.Sprintf("For a '%s' the answer would be", newAnimal), false, nil)
actualNode.update(newQuestion+"?", newAnswer, newAnimal)
} else {
fmt.Println("Why not try another animal?")
}
keepAsking = false
}
}
keepPlaying = (parseInput("Are you thinking of an animal?", true, rootNode) == "y")
}
}