From 93062df0744c1a650bb014c73ecf3d5925ec17a7 Mon Sep 17 00:00:00 2001 From: Troy Campbell Date: Fri, 14 Oct 2022 12:23:55 +1000 Subject: [PATCH 01/17] Added go for Bagels --- 00_Alternate_Languages/05_Bagels/go/main.go | 166 ++++++++++++++++++++ 1 file changed, 166 insertions(+) create mode 100644 00_Alternate_Languages/05_Bagels/go/main.go diff --git a/00_Alternate_Languages/05_Bagels/go/main.go b/00_Alternate_Languages/05_Bagels/go/main.go new file mode 100644 index 00000000..b0d2b106 --- /dev/null +++ b/00_Alternate_Languages/05_Bagels/go/main.go @@ -0,0 +1,166 @@ +package main + +import ( + "bufio" + "fmt" + "math/rand" + "os" + "strconv" + "strings" + "time" +) + +const MAXGUESSES int = 20 + +func printWelcome() { + fmt.Println("\n Bagels") + fmt.Println("Creative Computing Morristown, New Jersey") + fmt.Println() +} +func printRules() { + fmt.Println() + fmt.Println("I am thinking of a three-digit number. Try to guess") + fmt.Println("my number and I will give you clues as follows:") + fmt.Println(" PICO - One digit correct but in the wrong position") + fmt.Println(" FERMI - One digit correct and in the right position") + fmt.Println(" BAGELS - No digits correct") +} + +func getNumber() []string { + numbers := []string{"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"} + rand.Shuffle(len(numbers), func(i, j int) { numbers[i], numbers[j] = numbers[j], numbers[i] }) + + return numbers[:3] +} + +func getValidGuess(guessNumber int) string { + var guess string + scanner := bufio.NewScanner(os.Stdin) + valid := false + for !valid { + fmt.Printf("Guess # %d?\n", guessNumber) + scanner.Scan() + guess = strings.TrimSpace(scanner.Text()) + + // guess must be 3 characters + if len(guess) == 3 { + // and should be numeric + _, err := strconv.Atoi(guess) + if err != nil { + fmt.Println("What?") + } else { + // and the numbers should be unique + if (guess[0:1] != guess[1:2]) && (guess[0:1] != guess[2:3]) && (guess[1:2] != guess[2:3]) { + valid = true + } else { + fmt.Println("Oh, I forgot to tell you that the number I have in mind") + fmt.Println("has no two digits the same.") + } + } + } else { + fmt.Println("Try guessing a three-digit number.") + } + } + + return guess +} + +func buildResultString(num []string, guess string) string { + result := "" + + // correct digits in wrong place + for i := 0; i < 2; i++ { + if num[i] == guess[i+1:i+2] { + result += "PICO " + } + if num[i+1] == guess[i:i+1] { + result += "PICO " + } + } + if num[0] == guess[2:3] { + result += "PICO " + } + if num[2] == guess[0:1] { + result += "PICO " + } + + // correct digits in right place + for i := 0; i < 3; i++ { + if num[i] == guess[i:i+1] { + result += "FERMI " + } + } + + // nothing right? + if result == "" { + result = "BAGELS" + } + + return result +} + +func main() { + rand.Seed(time.Now().UnixNano()) + scanner := bufio.NewScanner(os.Stdin) + + printWelcome() + + fmt.Println("Would you like the rules (Yes or No)? ") + scanner.Scan() + response := scanner.Text() + if len(response) > 0 { + if strings.ToUpper(response[0:1]) != "N" { + printRules() + } + } else { + printRules() + } + + gamesWon := 0 + stillRunning := true + + for stillRunning { + num := getNumber() + numStr := strings.Join(num, "") + guesses := 1 + + fmt.Println("\nO.K. I have a number in mind.") + guessing := true + for guessing { + guess := getValidGuess(guesses) + + if guess == numStr { + fmt.Println("You got it!!") + gamesWon++ + guessing = false + } else { + fmt.Println(buildResultString(num, guess)) + guesses++ + if guesses > MAXGUESSES { + fmt.Println("Oh well") + fmt.Printf("That's %d guesses. My number was %s\n", MAXGUESSES, numStr) + guessing = false + } + } + } + + validRespone := false + for !validRespone { + fmt.Println("Play again (Yes or No)?") + scanner.Scan() + response := scanner.Text() + if len(response) > 0 { + validRespone = true + if strings.ToUpper(response[0:1]) != "Y" { + stillRunning = false + } + } + } + } + + if gamesWon > 0 { + fmt.Printf("\nA %d point Bagels buff!!\n", gamesWon) + } + + fmt.Println("Hope you had fun. Bye") +} From 7a882ea31779f99105b243d108aa0718ee36dec5 Mon Sep 17 00:00:00 2001 From: Troy Campbell Date: Wed, 19 Oct 2022 12:21:29 +1000 Subject: [PATCH 02/17] Added go version of Batnum --- 00_Alternate_Languages/08_Batnum/go/main.go | 248 ++++++++++++++++++++ 1 file changed, 248 insertions(+) create mode 100644 00_Alternate_Languages/08_Batnum/go/main.go diff --git a/00_Alternate_Languages/08_Batnum/go/main.go b/00_Alternate_Languages/08_Batnum/go/main.go new file mode 100644 index 00000000..10334799 --- /dev/null +++ b/00_Alternate_Languages/08_Batnum/go/main.go @@ -0,0 +1,248 @@ +package main + +import ( + "bufio" + "fmt" + "os" + "strconv" + "strings" +) + +type StartOption int8 + +const ( + StartUndefined StartOption = iota + ComputerFirst + PlayerFirst +) + +type WinOption int8 + +const ( + WinUndefined WinOption = iota + TakeLast + AvoidLast +) + +type GameOptions struct { + pileSize int + winOption WinOption + startOption StartOption + minSelect int + maxSelect int +} + +func NewOptions() *GameOptions { + g := GameOptions{} + + g.pileSize = getPileSize() + if g.pileSize < 0 { + return &g + } + + g.winOption = getWinOption() + g.minSelect, g.maxSelect = getMinMax() + g.startOption = getStartOption() + + return &g +} + +func getPileSize() int { + ps := 0 + var err error + scanner := bufio.NewScanner(os.Stdin) + + for { + fmt.Println("Enter Pile Size ") + scanner.Scan() + ps, err = strconv.Atoi(scanner.Text()) + if err == nil { + break + } + } + return ps +} + +func getWinOption() WinOption { + scanner := bufio.NewScanner(os.Stdin) + + for { + fmt.Println("ENTER WIN OPTION - 1 TO TAKE LAST, 2 TO AVOID LAST:") + scanner.Scan() + w, err := strconv.Atoi(scanner.Text()) + if err == nil && (w == 1 || w == 2) { + return WinOption(w) + } + } +} + +func getStartOption() StartOption { + scanner := bufio.NewScanner(os.Stdin) + + for { + fmt.Println("ENTER START OPTION - 1 COMPUTER FIRST, 2 YOU FIRST ") + scanner.Scan() + s, err := strconv.Atoi(scanner.Text()) + if err == nil && (s == 1 || s == 2) { + return StartOption(s) + } + } +} + +func getMinMax() (int, int) { + minSelect := 0 + maxSelect := 0 + var minErr error + var maxErr error + scanner := bufio.NewScanner(os.Stdin) + + for { + fmt.Println("ENTER MIN AND MAX ") + scanner.Scan() + enteredValues := scanner.Text() + vals := strings.Split(enteredValues, " ") + minSelect, minErr = strconv.Atoi(vals[0]) + maxSelect, maxErr = strconv.Atoi(vals[1]) + if (minErr == nil) && (maxErr == nil) && (minSelect > 0) && (maxSelect > 0) && (maxSelect > minSelect) { + return minSelect, maxSelect + } + } +} + +// This handles the player's turn - asking the player how many objects +// to take and doing some basic validation around that input. Then it +// checks for any win conditions. +// Returns a boolean indicating whether the game is over and the new pile_size. +func playerMove(pile, min, max int, win WinOption) (bool, int) { + scanner := bufio.NewScanner(os.Stdin) + done := false + for !done { + fmt.Println("YOUR MOVE") + scanner.Scan() + m, err := strconv.Atoi(scanner.Text()) + if err != nil { + continue + } + + if m == 0 { + fmt.Println("I TOLD YOU NOT TO USE ZERO! COMPUTER WINS BY FORFEIT.") + return true, pile + } + + if m > max || m < min { + fmt.Println("ILLEGAL MOVE, REENTER IT") + continue + } + + pile -= m + done = true + + if pile <= 0 { + if win == AvoidLast { + fmt.Println("TOUGH LUCK, YOU LOSE.") + } else { + fmt.Println("CONGRATULATIONS, YOU WIN.") + } + return true, pile + } + } + return false, pile +} + +// This handles the logic to determine how many objects the computer +// will select on its turn. +func computerPick(pile, min, max int, win WinOption) int { + var q int + if win == AvoidLast { + q = pile - 1 + } else { + q = pile + } + c := min + max + + pick := q - (c * int(q/c)) + + if pick < min { + pick = min + } else if pick > max { + pick = max + } + + return pick +} + +// This handles the computer's turn - first checking for the various +// win/lose conditions and then calculating how many objects +// the computer will take. +// Returns a boolean indicating whether the game is over and the new pile_size. +func computerMove(pile, min, max int, win WinOption) (bool, int) { + // first check for end-game conditions + if win == TakeLast && pile <= max { + fmt.Printf("COMPUTER TAKES %d AND WINS\n", pile) + return true, pile + } + + if win == AvoidLast && pile <= min { + fmt.Printf("COMPUTER TAKES %d AND LOSES\n", pile) + return true, pile + } + + // otherwise determine the computer's selection + selection := computerPick(pile, min, max, win) + pile -= selection + fmt.Printf("COMPUTER TAKES %d AND LEAVES %d\n", selection, pile) + return false, pile +} + +// This is the main game loop - repeating each turn until one +// of the win/lose conditions is met. +func play(pile, min, max int, start StartOption, win WinOption) { + gameOver := false + playersTurn := (start == PlayerFirst) + + for !gameOver { + if playersTurn { + gameOver, pile = playerMove(pile, min, max, win) + playersTurn = false + if gameOver { + return + } + } + + if !playersTurn { + gameOver, pile = computerMove(pile, min, max, win) + playersTurn = true + } + } +} + +// Print out the introduction and rules of the game +func printIntro() { + fmt.Printf("%33s%s\n", " ", "BATNUM") + fmt.Printf("%15s%s\n", " ", "CREATIVE COMPUTING MORRISSTOWN, NEW JERSEY") + fmt.Printf("\n\n\n") + fmt.Println("THIS PROGRAM IS A 'BATTLE OF NUMBERS' GAME, WHERE THE") + fmt.Println("COMPUTER IS YOUR OPPONENT.") + fmt.Println() + fmt.Println("THE GAME STARTS WITH AN ASSUMED PILE OF OBJECTS. YOU") + fmt.Println("AND YOUR OPPONENT ALTERNATELY REMOVE OBJECTS FROM THE PILE.") + fmt.Println("WINNING IS DEFINED IN ADVANCE AS TAKING THE LAST OBJECT OR") + fmt.Println("NOT. YOU CAN ALSO SPECIFY SOME OTHER BEGINNING CONDITIONS.") + fmt.Println("DON'T USE ZERO, HOWEVER, IN PLAYING THE GAME.") + fmt.Println("ENTER A NEGATIVE NUMBER FOR NEW PILE SIZE TO STOP PLAYING.") + fmt.Println() +} + +func main() { + for { + printIntro() + + g := NewOptions() + + if g.pileSize < 0 { + return + } + + play(g.pileSize, g.minSelect, g.maxSelect, g.startOption, g.winOption) + } +} From b8aa3daaa03498f7cd4721c639e0ca4e49cb0f2f Mon Sep 17 00:00:00 2001 From: Troy Campbell Date: Thu, 20 Oct 2022 12:13:27 +1000 Subject: [PATCH 03/17] Added go for Battle --- 00_Alternate_Languages/09_Battle/go/main.go | 266 ++++++++++++++++++++ 1 file changed, 266 insertions(+) create mode 100644 00_Alternate_Languages/09_Battle/go/main.go diff --git a/00_Alternate_Languages/09_Battle/go/main.go b/00_Alternate_Languages/09_Battle/go/main.go new file mode 100644 index 00000000..c0f911f4 --- /dev/null +++ b/00_Alternate_Languages/09_Battle/go/main.go @@ -0,0 +1,266 @@ +package main + +import ( + "bufio" + "fmt" + "math/rand" + "os" + "strconv" + "strings" + "time" +) + +const ( + SEA_WIDTH = 6 + DESTROYER_LENGTH = 2 + CRUISER_LENGTH = 3 + CARRIER_LENGTH = 4 +) + +type Point [2]int +type Vector Point +type Sea [][]int + +func NewSea() Sea { + s := make(Sea, 6) + for r := 0; r < SEA_WIDTH; r++ { + c := make([]int, 6) + s[r] = c + } + + return s +} + +func getRandomVector() Vector { + v := Vector{} + + for { + v[0] = rand.Intn(3) - 1 + v[1] = rand.Intn(3) - 1 + + if !(v[0] == 0 && v[1] == 0) { + break + } + } + return v +} + +func addVector(p Point, v Vector) Point { + newPoint := Point{} + + newPoint[0] = p[0] + v[0] + newPoint[1] = p[1] + v[1] + + return newPoint +} + +func isWithinSea(p Point, s Sea) bool { + return (1 <= p[0] && p[0] <= len(s)) && (1 <= p[1] && p[1] <= len(s)) +} + +func valueAt(p Point, s Sea) int { + return s[p[1]-1][p[0]-1] +} + +func reportInputError() { + fmt.Printf("INVALID. SPECIFY TWO NUMBERS FROM 1 TO %d, SEPARATED BY A COMMA.\n", SEA_WIDTH) +} + +func getNextTarget(s Sea) Point { + scanner := bufio.NewScanner(os.Stdin) + + for { + fmt.Println("\n?") + scanner.Scan() + + vals := strings.Split(scanner.Text(), ",") + + if len(vals) != 2 { + reportInputError() + continue + } + + x, xErr := strconv.Atoi(strings.TrimSpace(vals[0])) + y, yErr := strconv.Atoi(strings.TrimSpace(vals[1])) + + if (len(vals) != 2) || (xErr != nil) || (yErr != nil) { + reportInputError() + continue + } + + p := Point{} + p[0] = x + p[1] = y + if isWithinSea(p, s) { + return p + } + } +} + +func setValueAt(value int, p Point, s Sea) { + s[p[1]-1][p[0]-1] = value +} + +func hasShip(s Sea, code int) bool { + hasShip := false + for r := 0; r < SEA_WIDTH; r++ { + for c := 0; c < SEA_WIDTH; c++ { + if s[r][c] == code { + hasShip = true + break + } + } + } + return hasShip +} + +func countSunk(s Sea, codes []int) int { + sunk := 0 + + for _, c := range codes { + if !hasShip(s, c) { + sunk += 1 + } + } + + return sunk +} + +func placeShip(s Sea, size, code int) { + for { + start := Point{} + start[0] = rand.Intn(SEA_WIDTH) + 1 + start[1] = rand.Intn(SEA_WIDTH) + 1 + vector := getRandomVector() + + point := start + points := []Point{} + + for i := 0; i < size; i++ { + point = addVector(point, vector) + points = append(points, point) + } + + clearPosition := true + for _, p := range points { + if !isWithinSea(p, s) { + clearPosition = false + break + } + if valueAt(p, s) > 0 { + clearPosition = false + break + } + } + if !clearPosition { + continue + } + + for _, p := range points { + setValueAt(code, p, s) + } + break + } +} + +func setupShips(s Sea) { + placeShip(s, DESTROYER_LENGTH, 1) + placeShip(s, DESTROYER_LENGTH, 2) + placeShip(s, CRUISER_LENGTH, 3) + placeShip(s, CRUISER_LENGTH, 4) + placeShip(s, CARRIER_LENGTH, 5) + placeShip(s, CARRIER_LENGTH, 6) +} + +func printIntro() { + fmt.Println(" BATTLE") + fmt.Println("CREATIVE COMPUTING MORRISTOWN, NEW JERSEY") + fmt.Println() + fmt.Println("THE FOLLOWING CODE OF THE BAD GUYS' FLEET DISPOSITION") + fmt.Println("HAS BEEN CAPTURED BUT NOT DECODED: ") + fmt.Println() +} + +func printInstructions() { + fmt.Println() + fmt.Println() + fmt.Println("DE-CODE IT AND USE IT IF YOU CAN") + fmt.Println("BUT KEEP THE DE-CODING METHOD A SECRET.") + fmt.Println() + fmt.Println("START GAME") +} + +func printEncodedSea(s Sea) { + for x := 0; x < SEA_WIDTH; x++ { + fmt.Println() + for y := SEA_WIDTH - 1; y > -1; y-- { + fmt.Printf(" %d", s[y][x]) + } + } + fmt.Println() +} + +func wipeout(s Sea) bool { + for c := 1; c <= 7; c++ { + if hasShip(s, c) { + return false + } + } + return true +} + +func main() { + rand.Seed(time.Now().UnixNano()) + + s := NewSea() + + setupShips(s) + + printIntro() + + printEncodedSea(s) + + printInstructions() + + splashes := 0 + hits := 0 + + for { + target := getNextTarget(s) + targetValue := valueAt(target, s) + + if targetValue < 0 { + fmt.Printf("YOU ALREADY PUT A HOLE IN SHIP NUMBER %d AT THAT POINT.\n", targetValue) + } + + if targetValue <= 0 { + fmt.Println("SPLASH! TRY AGAIN.") + splashes += 1 + continue + } + + fmt.Printf("A DIRECT HIT ON SHIP NUMBER %d\n", targetValue) + hits += 1 + setValueAt(targetValue*-1, target, s) + + if !hasShip(s, targetValue) { + fmt.Println("AND YOU SUNK IT. HURRAH FOR THE GOOD GUYS.") + fmt.Println("SO FAR, THE BAD GUYS HAVE LOST") + fmt.Printf("%d DESTROYER(S), %d CRUISER(S), AND %d AIRCRAFT CARRIER(S).\n", countSunk(s, []int{1, 2}), countSunk(s, []int{3, 4}), countSunk(s, []int{5, 6})) + } + + if !wipeout(s) { + fmt.Printf("YOUR CURRENT SPLASH/HIT RATIO IS %2f\n", float32(splashes)/float32(hits)) + continue + } + + fmt.Printf("YOU HAVE TOTALLY WIPED OUT THE BAD GUYS' FLEET WITH A FINAL SPLASH/HIT RATIO OF %2f\n", float32(splashes)/float32(hits)) + + if splashes == 0 { + fmt.Println("CONGRATULATIONS -- A DIRECT HIT EVERY TIME.") + } + + fmt.Println("\n****************************") + break + } +} From 5e4430409a68a1c6a13c7677889fc81b6d9cca9f Mon Sep 17 00:00:00 2001 From: Troy Campbell Date: Tue, 25 Oct 2022 09:07:16 +1000 Subject: [PATCH 04/17] Added go implementation of Bombardment --- .../11_Bombardment/go/main.go | 181 ++++++++++++++++++ 1 file changed, 181 insertions(+) create mode 100644 00_Alternate_Languages/11_Bombardment/go/main.go diff --git a/00_Alternate_Languages/11_Bombardment/go/main.go b/00_Alternate_Languages/11_Bombardment/go/main.go new file mode 100644 index 00000000..e69ff3ea --- /dev/null +++ b/00_Alternate_Languages/11_Bombardment/go/main.go @@ -0,0 +1,181 @@ +package main + +import ( + "bufio" + "fmt" + "math/rand" + "os" + "strconv" + "strings" + "time" +) + +// Messages correspond to outposts remaining (3, 2, 1, 0) +var PLAYER_PROGRESS_MESSAGES = []string{ + "YOU GOT ME, I'M GOING FAST. BUT I'LL GET YOU WHEN\nMY TRANSISTO&S RECUP%RA*E!", + "THREE DOWN, ONE TO GO.\n\n", + "TWO DOWN, TWO TO GO.\n\n", + "ONE DOWN, THREE TO GO.\n\n", +} + +var ENEMY_PROGRESS_MESSAGES = []string{ + "YOU'RE DEAD. YOUR LAST OUTPOST WAS AT %d. HA, HA, HA.\nBETTER LUCK NEXT TIME.", + "YOU HAVE ONLY ONE OUTPOST LEFT.\n\n", + "YOU HAVE ONLY TWO OUTPOSTS LEFT.\n\n", + "YOU HAVE ONLY THREE OUTPOSTS LEFT.\n\n", +} + +func displayField() { + for r := 0; r < 5; r++ { + initial := r*5 + 1 + for c := 0; c < 5; c++ { + //x := strconv.Itoa(initial + c) + fmt.Printf("\t%d", initial+c) + } + fmt.Println() + } + fmt.Print("\n\n\n\n\n\n\n\n\n") +} + +func printIntro() { + fmt.Println(" BOMBARDMENT") + fmt.Println(" CREATIVE COMPUTING MORRISTOWN, NEW JERSEY") + fmt.Println() + fmt.Println() + fmt.Println("YOU ARE ON A BATTLEFIELD WITH 4 PLATOONS AND YOU") + fmt.Println("HAVE 25 OUTPOSTS AVAILABLE WHERE THEY MAY BE PLACED.") + fmt.Println("YOU CAN ONLY PLACE ONE PLATOON AT ANY ONE OUTPOST.") + fmt.Println("THE COMPUTER DOES THE SAME WITH ITS FOUR PLATOONS.") + fmt.Println() + fmt.Println("THE OBJECT OF THE GAME IS TO FIRE MISSLES AT THE") + fmt.Println("OUTPOSTS OF THE COMPUTER. IT WILL DO THE SAME TO YOU.") + fmt.Println("THE ONE WHO DESTROYS ALL FOUR OF THE ENEMY'S PLATOONS") + fmt.Println("FIRST IS THE WINNER.") + fmt.Println() + fmt.Println("GOOD LUCK... AND TELL US WHERE YOU WANT THE BODIES SENT!") + fmt.Println() + fmt.Println("TEAR OFF MATRIX AND USE IT TO CHECK OFF THE NUMBERS.") + fmt.Print("\n\n\n\n") +} + +func positionList() []int { + positions := make([]int, 25) + for i := 0; i < 25; i++ { + positions[i] = i + 1 + } + return positions +} + +// Randomly choose 4 'positions' out of a range of 1 to 25 +func generateEnemyPositions() []int { + positions := positionList() + rand.Shuffle(len(positions), func(i, j int) { positions[i], positions[j] = positions[j], positions[i] }) + return positions[:4] +} + +func isValidPosition(p int) bool { + return p >= 1 && p <= 25 +} + +func promptForPlayerPositions() []int { + scanner := bufio.NewScanner(os.Stdin) + var positions []int + + for { + fmt.Println("\nWHAT ARE YOUR FOUR POSITIONS (1-25)?") + scanner.Scan() + rawPositions := strings.Split(scanner.Text(), " ") + + if len(rawPositions) != 4 { + fmt.Println("PLEASE ENTER FOUR UNIQUE POSITIONS") + goto there + } + + for _, p := range rawPositions { + pos, err := strconv.Atoi(p) + if (err != nil) || !isValidPosition(pos) { + fmt.Println("ALL POSITIONS MUST RANGE (1-25)") + goto there + } + positions = append(positions, pos) + } + if len(positions) == 4 { + return positions + } + + there: + } +} + +func promptPlayerForTarget() int { + scanner := bufio.NewScanner(os.Stdin) + + for { + fmt.Println("\nWHERE DO YOU WISH TO FIRE YOUR MISSILE?") + scanner.Scan() + target, err := strconv.Atoi(scanner.Text()) + + if (err != nil) || !isValidPosition(target) { + fmt.Println("POSITIONS MUST RANGE (1-25)") + continue + } + return target + } +} + +func generateAttackSequence() []int { + positions := positionList() + rand.Shuffle(len(positions), func(i, j int) { positions[i], positions[j] = positions[j], positions[i] }) + return positions +} + +// Performs attack procedure returning True if we are to continue. +func attack(target int, positions *[]int, hitMsg, missMsg string, progressMsg []string) bool { + for i := 0; i < len(*positions); i++ { + if target == (*positions)[i] { + fmt.Print(hitMsg) + + // remove the target just hit + (*positions)[i] = (*positions)[len((*positions))-1] + (*positions)[len((*positions))-1] = 0 + (*positions) = (*positions)[:len((*positions))-1] + + if len((*positions)) != 0 { + fmt.Print(progressMsg[len((*positions))]) + } else { + fmt.Printf(progressMsg[len((*positions))], target) + } + return len((*positions)) > 0 + } + } + fmt.Print(missMsg) + return len((*positions)) > 0 +} + +func main() { + rand.Seed(time.Now().UnixNano()) + + printIntro() + displayField() + + enemyPositions := generateEnemyPositions() + enemyAttacks := generateAttackSequence() + enemyAttackCounter := 0 + + playerPositions := promptForPlayerPositions() + + for { + // player attacks + if !attack(promptPlayerForTarget(), &enemyPositions, "YOU GOT ONE OF MY OUTPOSTS!\n\n", "HA, HA YOU MISSED. MY TURN NOW:\n\n", PLAYER_PROGRESS_MESSAGES) { + break + } + // computer attacks + hitMsg := fmt.Sprintf("I GOT YOU. IT WON'T BE LONG NOW. POST %d WAS HIT.\n", enemyAttacks[enemyAttackCounter]) + missMsg := fmt.Sprintf("I MISSED YOU, YOU DIRTY RAT. I PICKED %d. YOUR TURN:\n\n", enemyAttacks[enemyAttackCounter]) + if !attack(enemyAttacks[enemyAttackCounter], &playerPositions, hitMsg, missMsg, ENEMY_PROGRESS_MESSAGES) { + break + } + enemyAttackCounter += 1 + } + +} From 5d3bd244607933c126d5aa03774b32b6813ebfa4 Mon Sep 17 00:00:00 2001 From: Troy Campbell Date: Tue, 25 Oct 2022 13:56:16 +1000 Subject: [PATCH 05/17] Added go version of Bombs_Away --- .../12_Bombs_Away/go/main.go | 188 ++++++++++++++++++ 1 file changed, 188 insertions(+) create mode 100644 00_Alternate_Languages/12_Bombs_Away/go/main.go diff --git a/00_Alternate_Languages/12_Bombs_Away/go/main.go b/00_Alternate_Languages/12_Bombs_Away/go/main.go new file mode 100644 index 00000000..616f4451 --- /dev/null +++ b/00_Alternate_Languages/12_Bombs_Away/go/main.go @@ -0,0 +1,188 @@ +package main + +import ( + "bufio" + "fmt" + "math/rand" + "os" + "strconv" + "strings" + "time" +) + +type Choice struct { + idx string + msg string +} + +func playerSurvived() { + fmt.Println("YOU MADE IT THROUGH TREMENDOUS FLAK!!") +} + +func playerDeath() { + fmt.Println("* * * * BOOM * * * *") + fmt.Println("YOU HAVE BEEN SHOT DOWN.....") + fmt.Println("DEARLY BELOVED, WE ARE GATHERED HERE TODAY TO PAY OUR") + fmt.Println("LAST TRIBUTE...") +} + +func missionSuccess() { + fmt.Printf("DIRECT HIT!!!! %d KILLED.\n", int(100*rand.Int())) + fmt.Println("MISSION SUCCESSFUL.") +} + +// Takes a float between 0 and 1 and returns a boolean +// if the player has survived (based on random chance) +// Returns True if death, False if survived +func deathWithChance(probability float64) bool { + return probability > rand.Float64() +} + +func startNonKamikaziAttack() { + numMissions := getIntInput("HOW MANY MISSIONS HAVE YOU FLOWN? ") + + for numMissions > 160 { + fmt.Println("MISSIONS, NOT MILES...") + fmt.Println("150 MISSIONS IS HIGH EVEN FOR OLD-TIMERS") + numMissions = getIntInput("HOW MANY MISSIONS HAVE YOU FLOWN? ") + } + + if numMissions > 100 { + fmt.Println("THAT'S PUSHING THE ODDS!") + } + + if numMissions < 25 { + fmt.Println("FRESH OUT OF TRAINING, EH?") + } + + fmt.Println() + + if float32(numMissions) > (160 * rand.Float32()) { + missionSuccess() + } else { + missionFailure() + } +} + +func missionFailure() { + fmt.Printf("MISSED TARGET BY %d MILES!\n", int(2+30*rand.Float32())) + fmt.Println("NOW YOU'RE REALLY IN FOR IT !!") + fmt.Println() + + enemyWeapons := getInputFromList("DOES THE ENEMY HAVE GUNS(1), MISSILES(2), OR BOTH(3)? ", []Choice{{idx: "1", msg: "GUNS"}, {idx: "2", msg: "MISSILES"}, {idx: "3", msg: "BOTH"}}) + + // If there are no gunners (i.e. weapon choice 2) then + // we say that the gunners have 0 accuracy for the purposes + // of calculating probability of player death + enemyGunnerAccuracy := 0.0 + if enemyWeapons.idx != "2" { + enemyGunnerAccuracy = float64(getIntInput("WHAT'S THE PERCENT HIT RATE OF ENEMY GUNNERS (10 TO 50)? ")) + if enemyGunnerAccuracy < 10.0 { + fmt.Println("YOU LIE, BUT YOU'LL PAY...") + playerDeath() + } + } + + missileThreatWeighting := 35.0 + if enemyWeapons.idx == "1" { + missileThreatWeighting = 0 + } + + death := deathWithChance((enemyGunnerAccuracy + missileThreatWeighting) / 100) + + if death { + playerDeath() + } else { + playerSurvived() + } +} + +func playItaly() { + targets := []Choice{{idx: "1", msg: "SHOULD BE EASY -- YOU'RE FLYING A NAZI-MADE PLANE."}, {idx: "2", msg: "BE CAREFUL!!!"}, {idx: "3", msg: "YOU'RE GOING FOR THE OIL, EH?"}} + target := getInputFromList("YOUR TARGET -- ALBANIA(1), GREECE(2), NORTH AFRICA(3)", targets) + fmt.Println(target.msg) + startNonKamikaziAttack() +} + +func playAllies() { + aircraftMessages := []Choice{{idx: "1", msg: "YOU'VE GOT 2 TONS OF BOMBS FLYING FOR PLOESTI."}, {idx: "2", msg: "YOU'RE DUMPING THE A-BOMB ON HIROSHIMA."}, {idx: "3", msg: "YOU'RE CHASING THE BISMARK IN THE NORTH SEA."}, {idx: "4", msg: "YOU'RE BUSTING A GERMAN HEAVY WATER PLANT IN THE RUHR."}} + aircraft := getInputFromList("AIRCRAFT -- LIBERATOR(1), B-29(2), B-17(3), LANCASTER(4): ", aircraftMessages) + fmt.Println(aircraft.msg) + startNonKamikaziAttack() +} + +func playJapan() { + acknowledgeMessage := []Choice{{idx: "Y", msg: "Y"}, {idx: "N", msg: "N"}} + firstMission := getInputFromList("YOU'RE FLYING A KAMIKAZE MISSION OVER THE USS LEXINGTON.\nYOUR FIRST KAMIKAZE MISSION? (Y OR N): ", acknowledgeMessage) + if firstMission.msg == "N" { + playerDeath() + } + if rand.Float64() > 0.65 { + missionSuccess() + } else { + playerDeath() + } +} + +func playGermany() { + targets := []Choice{{idx: "1", msg: "YOU'RE NEARING STALINGRAD."}, {idx: "2", msg: "NEARING LONDON. BE CAREFUL, THEY'VE GOT RADAR."}, {idx: "3", msg: "NEARING VERSAILLES. DUCK SOUP. THEY'RE NEARLY DEFENSELESS."}} + target := getInputFromList("A NAZI, EH? OH WELL. ARE YOU GOING FOR RUSSIA(1),\nENGLAND(2), OR FRANCE(3)? ", targets) + fmt.Println(target.msg) + startNonKamikaziAttack() +} + +func playGame() { + fmt.Println("YOU ARE A PILOT IN A WORLD WAR II BOMBER.") + side := getInputFromList("WHAT SIDE -- ITALY(1), ALLIES(2), JAPAN(3), GERMANY(4): ", []Choice{{idx: "1", msg: "ITALY"}, {idx: "2", msg: "ALLIES"}, {idx: "3", msg: "JAPAN"}, {idx: "4", msg: "GERMANY"}}) + switch side.idx { + case "1": + playItaly() + case "2": + playAllies() + case "3": + playJapan() + case "4": + playGermany() + } +} + +func main() { + rand.Seed(time.Now().UnixNano()) + + for { + playGame() + if getInputFromList("ANOTHER MISSION (Y OR N):", []Choice{{idx: "Y", msg: "Y"}, {idx: "N", msg: "N"}}).msg == "N" { + break + } + } +} + +func getInputFromList(prompt string, choices []Choice) Choice { + scanner := bufio.NewScanner(os.Stdin) + for { + fmt.Println(prompt) + scanner.Scan() + choice := scanner.Text() + for _, c := range choices { + if strings.EqualFold(strings.ToUpper(choice), strings.ToUpper(c.idx)) { + return c + } + } + fmt.Println("TRY AGAIN...") + } +} + +func getIntInput(prompt string) int { + scanner := bufio.NewScanner(os.Stdin) + for { + fmt.Println(prompt) + scanner.Scan() + choice, err := strconv.Atoi(scanner.Text()) + if err != nil { + fmt.Println("TRY AGAIN...") + continue + } else { + return choice + } + } +} From be464fb38704c1d8cf3356d693aaa85bba466ff9 Mon Sep 17 00:00:00 2001 From: Troy Campbell Date: Thu, 27 Oct 2022 09:03:10 +1000 Subject: [PATCH 06/17] Added go version of Depth_Charge --- .../31_Depth_Charge/go/main.go | 156 ++++++++++++++++++ 1 file changed, 156 insertions(+) create mode 100644 00_Alternate_Languages/31_Depth_Charge/go/main.go diff --git a/00_Alternate_Languages/31_Depth_Charge/go/main.go b/00_Alternate_Languages/31_Depth_Charge/go/main.go new file mode 100644 index 00000000..0ab3f876 --- /dev/null +++ b/00_Alternate_Languages/31_Depth_Charge/go/main.go @@ -0,0 +1,156 @@ +package main + +import ( + "bufio" + "fmt" + "math" + "math/rand" + "os" + "strconv" + "strings" + "time" +) + +type Position []int + +func NewPosition() Position { + p := make([]int, 3) + return Position(p) +} + +func showWelcome() { + fmt.Print("\033[H\033[2J") + fmt.Println(" DEPTH CHARGE") + fmt.Println(" Creative Computing Morristown, New Jersey") + fmt.Println() +} + +func getNumCharges() (int, int) { + scanner := bufio.NewScanner(os.Stdin) + + for { + fmt.Println("Dimensions of search area?") + scanner.Scan() + dim, err := strconv.Atoi(scanner.Text()) + if err != nil { + fmt.Println("Must enter an integer number. Please try again...") + continue + } + return dim, int(math.Log2(float64(dim))) + 1 + } +} + +func askForNewGame() { + scanner := bufio.NewScanner(os.Stdin) + + fmt.Println("Another game (Y or N): ") + scanner.Scan() + if strings.ToUpper(scanner.Text()) == "Y" { + main() + } + fmt.Println("OK. Hope you enjoyed yourself") + os.Exit(1) +} + +func showShotResult(shot, location Position) { + result := "Sonar reports shot was " + + if shot[1] > location[1] { // y-direction + result += "north" + } else if shot[1] < location[1] { // y-direction + result += "south" + } + + if shot[0] > location[0] { // x-direction + result += "east" + } else if shot[0] < location[0] { // x-direction + result += "west" + } + + if shot[1] != location[1] || shot[0] != location[0] { + result += " and " + } + if shot[2] > location[2] { + result += "too low." + } else if shot[2] < location[2] { + result += "too high." + } else { + result += "depth OK." + } + + fmt.Println(result) +} + +func getShot() Position { + scanner := bufio.NewScanner(os.Stdin) + + for { + shotPos := NewPosition() + fmt.Println("Enter coordinates: ") + scanner.Scan() + rawGuess := strings.Split(scanner.Text(), " ") + if len(rawGuess) != 3 { + goto there + } + for i := 0; i < 3; i++ { + val, err := strconv.Atoi(rawGuess[i]) + if err != nil { + goto there + } + shotPos[i] = val + } + return shotPos + there: + fmt.Println("Please enter coordinates separated by spaces") + fmt.Println("Example: 3 2 1") + } +} + +func getRandomPosition(searchArea int) Position { + pos := NewPosition() + for i := 0; i < 3; i++ { + pos[i] = rand.Intn(searchArea) + } + return pos +} + +func playGame(searchArea, numCharges int) { + rand.Seed(time.Now().UTC().UnixNano()) + fmt.Println("\nYou are the captain of the destroyer USS Computer.") + fmt.Println("An enemy sub has been causing you trouble. Your") + fmt.Printf("mission is to destroy it. You have %d shots.\n", numCharges) + fmt.Println("Specify depth charge explosion point with a") + fmt.Println("trio of numbers -- the first two are the") + fmt.Println("surface coordinates; the third is the depth.") + fmt.Println("\nGood luck!") + fmt.Println() + + subPos := getRandomPosition(searchArea) + + for c := 0; c < numCharges; c++ { + fmt.Printf("\nTrial #%d\n", c+1) + + shot := getShot() + + if shot[0] == subPos[0] && shot[1] == subPos[1] && shot[2] == subPos[2] { + fmt.Printf("\nB O O M ! ! You found it in %d tries!\n", c+1) + askForNewGame() + } else { + showShotResult(shot, subPos) + } + } + + // out of depth charges + fmt.Println("\nYou have been torpedoed! Abandon ship!") + fmt.Printf("The submarine was at %d %d %d\n", subPos[0], subPos[1], subPos[2]) + askForNewGame() + +} + +func main() { + showWelcome() + + searchArea, numCharges := getNumCharges() + + playGame(searchArea, numCharges) +} From 65ea4be550f1911f148f92f5a6701fc9f572ea32 Mon Sep 17 00:00:00 2001 From: Troy Campbell Date: Thu, 27 Oct 2022 09:42:24 +1000 Subject: [PATCH 07/17] Added go version of Dice --- 00_Alternate_Languages/33_Dice/go/main.go | 64 +++++++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 00_Alternate_Languages/33_Dice/go/main.go diff --git a/00_Alternate_Languages/33_Dice/go/main.go b/00_Alternate_Languages/33_Dice/go/main.go new file mode 100644 index 00000000..75bef387 --- /dev/null +++ b/00_Alternate_Languages/33_Dice/go/main.go @@ -0,0 +1,64 @@ +package main + +import ( + "bufio" + "fmt" + "math/rand" + "os" + "strconv" + "strings" +) + +func printWelcome() { + fmt.Println("\n Dice") + fmt.Println("Creative Computing Morristown, New Jersey") + fmt.Println() + fmt.Println() + fmt.Println("This program simulates the rolling of a") + fmt.Println("pair of dice.") + fmt.Println("You enter the number of times you want the computer to") + fmt.Println("'roll' the dice. Watch out, very large numbers take") + fmt.Println("a long time. In particular, numbers over 5000.") + fmt.Println() +} + +func main() { + printWelcome() + scanner := bufio.NewScanner(os.Stdin) + + for { + fmt.Println("\nHow many rolls? ") + scanner.Scan() + numRolls, err := strconv.Atoi(scanner.Text()) + if err != nil { + fmt.Println("Invalid input, try again...") + continue + } + + // We'll track counts of roll outcomes in a 13-element list. + // The first two indices (0 & 1) are ignored, leaving just + // the indices that match the roll values (2 through 12). + results := make([]int, 13) + + for n := 0; n < numRolls; n++ { + d1 := rand.Intn(6) + 1 + d2 := rand.Intn(6) + 1 + results[d1+d2] += 1 + } + + // Display final results + fmt.Println("\nTotal Spots Number of Times") + for i := 2; i < 13; i++ { + fmt.Printf(" %-14d%d\n", i, results[i]) + } + + fmt.Println("\nTry again? ") + scanner.Scan() + if strings.ToUpper(scanner.Text()) == "Y" { + continue + } else { + os.Exit(1) + } + + } +} From 7b813d5bdb3e4b6a14c3bf47fdac2a4bf335a40a Mon Sep 17 00:00:00 2001 From: Troy Campbell Date: Thu, 27 Oct 2022 12:45:57 +1000 Subject: [PATCH 08/17] Added go version of Digits --- 00_Alternate_Languages/34_Digits/go/main.go | 171 ++++++++++++++++++++ 1 file changed, 171 insertions(+) create mode 100644 00_Alternate_Languages/34_Digits/go/main.go diff --git a/00_Alternate_Languages/34_Digits/go/main.go b/00_Alternate_Languages/34_Digits/go/main.go new file mode 100644 index 00000000..64326d53 --- /dev/null +++ b/00_Alternate_Languages/34_Digits/go/main.go @@ -0,0 +1,171 @@ +package main + +import ( + "bufio" + "fmt" + "math/rand" + "os" + "strconv" + "time" +) + +func printIntro() { + fmt.Println(" DIGITS") + fmt.Println(" CREATIVE COMPUTING MORRISTOWN, NEW JERSEY") + fmt.Println() + fmt.Println() + fmt.Println("THIS IS A GAME OF GUESSING.") +} + +func readInteger(prompt string) int { + scanner := bufio.NewScanner(os.Stdin) + for { + fmt.Println(prompt) + scanner.Scan() + response, err := strconv.Atoi(scanner.Text()) + + if err != nil { + fmt.Println("INVALID INPUT, TRY AGAIN... ") + continue + } + + return response + } +} + +func printInstructions() { + fmt.Println() + fmt.Println("PLEASE TAKE A PIECE OF PAPER AND WRITE DOWN") + fmt.Println("THE DIGITS '0', '1', OR '2' THIRTY TIMES AT RANDOM.") + fmt.Println("ARRANGE THEM IN THREE LINES OF TEN DIGITS EACH.") + fmt.Println("I WILL ASK FOR THEN TEN AT A TIME.") + fmt.Println("I WILL ALWAYS GUESS THEM FIRST AND THEN LOOK AT YOUR") + fmt.Println("NEXT NUMBER TO SEE IF I WAS RIGHT. BY PURE LUCK,") + fmt.Println("I OUGHT TO BE RIGHT TEN TIMES. BUT I HOPE TO DO BETTER") + fmt.Println("THAN THAT *****") + fmt.Println() +} + +func readTenNumbers() []int { + numbers := make([]int, 10) + + numbers[0] = readInteger("FIRST NUMBER: ") + for i := 1; i < 10; i++ { + numbers[i] = readInteger("NEXT NUMBER:") + } + + return numbers +} + +func printSummary(correct int) { + fmt.Println() + + if correct > 10 { + fmt.Println() + fmt.Println("I GUESSED MORE THAN 1/3 OF YOUR NUMBERS.") + fmt.Println("I WIN.\u0007") + } else if correct < 10 { + fmt.Println("I GUESSED LESS THAN 1/3 OF YOUR NUMBERS.") + fmt.Println("YOU BEAT ME. CONGRATULATIONS *****") + } else { + fmt.Println("I GUESSED EXACTLY 1/3 OF YOUR NUMBERS.") + fmt.Println("IT'S A TIE GAME.") + } +} + +func buildArray(val, row, col int) [][]int { + a := make([][]int, row) + for r := 0; r < row; r++ { + b := make([]int, col) + for c := 0; c < col; c++ { + b[c] = val + } + a[r] = b + } + return a +} + +func main() { + rand.Seed(time.Now().UnixNano()) + + printIntro() + if readInteger("FOR INSTRUCTIONS, TYPE '1', ELSE TYPE '0' ? ") == 1 { + printInstructions() + } + + a := 0 + b := 1 + c := 3 + + m := buildArray(1, 27, 3) + k := buildArray(9, 3, 3) + l := buildArray(3, 9, 3) + + for { + l[0][0] = 2 + l[4][1] = 2 + l[8][2] = 2 + + z := float64(26) + z1 := float64(8) + z2 := 2 + runningCorrect := 0 + + var numbers []int + for round := 1; round <= 4; round++ { + validNumbers := false + for !validNumbers { + numbers = readTenNumbers() + validNumbers = true + for _, n := range numbers { + if n < 0 || n > 2 { + fmt.Println("ONLY USE THE DIGITS '0', '1', OR '2'.") + fmt.Println("LET'S TRY AGAIN.") + validNumbers = false + break + } + } + } + + fmt.Printf("\n%-14s%-14s%-14s%-14s\n", "MY GUESS", "YOUR NO.", "RESULT", "NO. RIGHT") + + for _, n := range numbers { + s := 0 + myGuess := 0 + + for j := 0; j < 3; j++ { + s1 := a*k[z2][j] + b*l[int(z1)][j] + c*m[int(z)][j] + + if s < s1 { + s = s1 + myGuess = j + } else if s1 == s && rand.Float64() > 0.5 { + myGuess = j + } + } + result := "" + + if myGuess != n { + result = "WRONG" + } else { + runningCorrect += 1 + result = "RIGHT" + m[int(z)][n] = m[int(z)][n] + 1 + l[int(z1)][n] = l[int(z1)][n] + 1 + k[int(z2)][n] = k[int(z2)][n] + 1 + z = z - (z/9)*9 + z = 3.0*z + float64(n) + } + fmt.Printf("\n%-14d%-14d%-14s%-14d\n", myGuess, n, result, runningCorrect) + + z1 = z - (z/9)*9 + z2 = n + } + printSummary(runningCorrect) + if readInteger("\nDO YOU WANT TO TRY AGAIN (1 FOR YES, 0 FOR NO) ? ") != 1 { + fmt.Println("\nTHANKS FOR THE GAME.") + os.Exit(0) + } + } + } +} From 55b047acdf70d0408663e740855d310879535bb6 Mon Sep 17 00:00:00 2001 From: Troy Campbell Date: Thu, 27 Oct 2022 13:52:32 +1000 Subject: [PATCH 09/17] Added go version of Even Wins --- .../35_Even_Wins/go/evenwins.go | 197 ++++++++++++++++++ 1 file changed, 197 insertions(+) create mode 100644 00_Alternate_Languages/35_Even_Wins/go/evenwins.go diff --git a/00_Alternate_Languages/35_Even_Wins/go/evenwins.go b/00_Alternate_Languages/35_Even_Wins/go/evenwins.go new file mode 100644 index 00000000..7c65aacc --- /dev/null +++ b/00_Alternate_Languages/35_Even_Wins/go/evenwins.go @@ -0,0 +1,197 @@ +package main + +import ( + "bufio" + "fmt" + "os" + "strconv" + "strings" +) + +const MAXTAKE = 4 + +type PlayerType int8 + +const ( + HUMAN PlayerType = iota + COMPUTER +) + +type Game struct { + table int + human int + computer int +} + +func NewGame() Game { + g := Game{} + g.table = 27 + + return g +} + +func printIntro() { + fmt.Println("Welcome to Even Wins!") + fmt.Println("Based on evenwins.bas from Creative Computing") + fmt.Println() + fmt.Println("Even Wins is a two-person game. You start with") + fmt.Println("27 marbles in the middle of the table.") + fmt.Println() + fmt.Println("Players alternate taking marbles from the middle.") + fmt.Println("A player can take 1 to 4 marbles on their turn, and") + fmt.Println("turns cannot be skipped. The game ends when there are") + fmt.Println("no marbles left, and the winner is the one with an even") + fmt.Println("number of marbles.") + fmt.Println() +} + +func (g *Game) printBoard() { + fmt.Println() + fmt.Printf(" marbles in the middle: %d\n", g.table) + fmt.Printf(" # marbles you have: %d\n", g.human) + fmt.Printf("# marbles computer has: %d\n", g.computer) + fmt.Println() +} + +func (g *Game) gameOver() { + fmt.Println() + fmt.Println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!") + fmt.Println("!! All the marbles are taken: Game Over!") + fmt.Println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!") + fmt.Println() + g.printBoard() + if g.human%2 == 0 { + fmt.Println("You are the winner! Congratulations!") + } else { + fmt.Println("The computer wins: all hail mighty silicon!") + } + fmt.Println() +} + +func getPlural(count int) string { + m := "marble" + if count > 1 { + m += "s" + } + return m +} + +func (g *Game) humanTurn() { + scanner := bufio.NewScanner(os.Stdin) + maxAvailable := MAXTAKE + if g.table < MAXTAKE { + maxAvailable = g.table + } + + fmt.Println("It's your turn!") + for { + fmt.Printf("Marbles to take? (1 - %d) --> ", maxAvailable) + scanner.Scan() + n, err := strconv.Atoi(scanner.Text()) + if err != nil { + fmt.Printf("\n Please enter a whole number from 1 to %d\n", maxAvailable) + continue + } + if n < 1 { + fmt.Println("\n You must take at least 1 marble!") + continue + } + if n > maxAvailable { + fmt.Printf("\n You can take at most %d %s\n", maxAvailable, getPlural(maxAvailable)) + continue + } + fmt.Printf("\nOkay, taking %d %s ...\n", n, getPlural(n)) + g.table -= n + g.human += n + return + } +} + +func (g *Game) computerTurn() { + marblesToTake := 0 + + fmt.Println("It's the computer's turn ...") + r := float64(g.table - 6*int((g.table)/6)) + + if int(g.human/2) == g.human/2 { + if r < 1.5 || r > 5.3 { + marblesToTake = 1 + } else { + marblesToTake = int(r - 1) + } + } else if float64(g.table) < 4.2 { + marblesToTake = 4 + } else if r > 3.4 { + if r < 4.7 || r > 3.5 { + marblesToTake = 4 + } + } else { + marblesToTake = int(r + 1) + } + + fmt.Printf("Computer takes %d %s ...\n", marblesToTake, getPlural(marblesToTake)) + g.table -= marblesToTake + g.computer += marblesToTake +} + +func (g *Game) play(playersTurn PlayerType) { + g.printBoard() + + for { + if g.table == 0 { + g.gameOver() + return + } else if playersTurn == HUMAN { + g.humanTurn() + g.printBoard() + playersTurn = COMPUTER + } else { + g.computerTurn() + g.printBoard() + playersTurn = HUMAN + } + } +} + +func getFirstPlayer() PlayerType { + scanner := bufio.NewScanner(os.Stdin) + + for { + fmt.Println("Do you want to play first? (y/n) --> ") + scanner.Scan() + + if strings.ToUpper(scanner.Text()) == "Y" { + return HUMAN + } else if strings.ToUpper(scanner.Text()) == "N" { + return COMPUTER + } else { + fmt.Println() + fmt.Println("Please enter 'y' if you want to play first,") + fmt.Println("or 'n' if you want to play second.") + fmt.Println() + } + } +} + +func main() { + scanner := bufio.NewScanner(os.Stdin) + + printIntro() + + for { + g := NewGame() + + g.play(getFirstPlayer()) + + fmt.Println("\nWould you like to play again? (y/n) --> ") + scanner.Scan() + if strings.ToUpper(scanner.Text()) == "Y" { + fmt.Println("\nOk, let's play again ...") + } else { + fmt.Println("\nOk, thanks for playing ... goodbye!") + return + } + + } + +} From cbdeb50f22220dd0707f7a155670d3e018b5951c Mon Sep 17 00:00:00 2001 From: Troy Campbell Date: Fri, 28 Oct 2022 11:42:41 +1000 Subject: [PATCH 10/17] Added go version of Fur Trader --- .../38_Fur_Trader/go/main.go | 326 ++++++++++++++++++ 1 file changed, 326 insertions(+) create mode 100644 00_Alternate_Languages/38_Fur_Trader/go/main.go diff --git a/00_Alternate_Languages/38_Fur_Trader/go/main.go b/00_Alternate_Languages/38_Fur_Trader/go/main.go new file mode 100644 index 00000000..642d48f0 --- /dev/null +++ b/00_Alternate_Languages/38_Fur_Trader/go/main.go @@ -0,0 +1,326 @@ +package main + +import ( + "bufio" + "fmt" + "log" + "math/rand" + "os" + "strconv" + "strings" + "time" +) + +const ( + MAXFURS = 190 + STARTFUNDS = 600 +) + +type Fur int8 + +const ( + FUR_MINK Fur = iota + FUR_BEAVER + FUR_ERMINE + FUR_FOX +) + +type Fort int8 + +const ( + FORT_MONTREAL Fort = iota + FORT_QUEBEC + FORT_NEWYORK +) + +type GameState int8 + +const ( + STARTING GameState = iota + TRADING + CHOOSINGFORT + TRAVELLING +) + +func FURS() []string { + return []string{"MINK", "BEAVER", "ERMINE", "FOX"} +} + +func FORTS() []string { + return []string{"HOCHELAGA (MONTREAL)", "STADACONA (QUEBEC)", "NEW YORK"} +} + +type Player struct { + funds float32 + furs []int +} + +func NewPlayer() Player { + p := Player{} + p.funds = STARTFUNDS + p.furs = make([]int, 4) + return p +} + +func (p *Player) totalFurs() int { + f := 0 + for _, v := range p.furs { + f += v + } + return f +} + +func (p *Player) lostFurs() { + for f := 0; f < len(p.furs); f++ { + p.furs[f] = 0 + } +} + +func printTitle() { + fmt.Println(" FUR TRADER") + fmt.Println(" CREATIVE COMPUTING MORRISTOWN, NEW JERSEY") + fmt.Println() + fmt.Println() + fmt.Println() +} + +func printIntro() { + fmt.Println("YOU ARE THE LEADER OF A FRENCH FUR TRADING EXPEDITION IN ") + fmt.Println("1776 LEAVING THE LAKE ONTARIO AREA TO SELL FURS AND GET") + fmt.Println("SUPPLIES FOR THE NEXT YEAR. YOU HAVE A CHOICE OF THREE") + fmt.Println("FORTS AT WHICH YOU MAY TRADE. THE COST OF SUPPLIES") + fmt.Println("AND THE AMOUNT YOU RECEIVE FOR YOUR FURS WILL DEPEND") + fmt.Println("ON THE FORT THAT YOU CHOOSE.") + fmt.Println() +} + +func getFortChoice() Fort { + scanner := bufio.NewScanner(os.Stdin) + + for { + fmt.Println() + fmt.Println("YOU MAY TRADE YOUR FURS AT FORT 1, FORT 2,") + fmt.Println("OR FORT 3. FORT 1 IS FORT HOCHELAGA (MONTREAL)") + fmt.Println("AND IS UNDER THE PROTECTION OF THE FRENCH ARMY.") + fmt.Println("FORT 2 IS FORT STADACONA (QUEBEC) AND IS UNDER THE") + fmt.Println("PROTECTION OF THE FRENCH ARMY. HOWEVER, YOU MUST") + fmt.Println("MAKE A PORTAGE AND CROSS THE LACHINE RAPIDS.") + fmt.Println("FORT 3 IS FORT NEW YORK AND IS UNDER DUTCH CONTROL.") + fmt.Println("YOU MUST CROSS THROUGH IROQUOIS LAND.") + fmt.Println("ANSWER 1, 2, OR 3.") + fmt.Print(">> ") + scanner.Scan() + + f, err := strconv.Atoi(scanner.Text()) + if err != nil || f < 1 || f > 3 { + fmt.Println("Invalid input, Try again ... ") + continue + } + return Fort(f) + } +} + +func printFortComment(f Fort) { + fmt.Println() + switch f { + case FORT_MONTREAL: + fmt.Println("YOU HAVE CHOSEN THE EASIEST ROUTE. HOWEVER, THE FORT") + fmt.Println("IS FAR FROM ANY SEAPORT. THE VALUE") + fmt.Println("YOU RECEIVE FOR YOUR FURS WILL BE LOW AND THE COST") + fmt.Println("OF SUPPLIES HIGHER THAN AT FORTS STADACONA OR NEW YORK.") + case FORT_QUEBEC: + fmt.Println("YOU HAVE CHOSEN A HARD ROUTE. IT IS, IN COMPARSION,") + fmt.Println("HARDER THAN THE ROUTE TO HOCHELAGA BUT EASIER THAN") + fmt.Println("THE ROUTE TO NEW YORK. YOU WILL RECEIVE AN AVERAGE VALUE") + fmt.Println("FOR YOUR FURS AND THE COST OF YOUR SUPPLIES WILL BE AVERAGE.") + case FORT_NEWYORK: + fmt.Println("YOU HAVE CHOSEN THE MOST DIFFICULT ROUTE. AT") + fmt.Println("FORT NEW YORK YOU WILL RECEIVE THE HIGHEST VALUE") + fmt.Println("FOR YOUR FURS. THE COST OF YOUR SUPPLIES") + fmt.Println("WILL BE LOWER THAN AT ALL THE OTHER FORTS.") + } + fmt.Println() +} + +func getYesOrNo() string { + scanner := bufio.NewScanner(os.Stdin) + for { + fmt.Println("ANSWER YES OR NO") + scanner.Scan() + if strings.ToUpper(scanner.Text())[0:1] == "Y" { + return "Y" + } else if strings.ToUpper(scanner.Text())[0:1] == "N" { + return "N" + } + } +} + +func getFursPurchase() []int { + scanner := bufio.NewScanner(os.Stdin) + fmt.Printf("YOUR %d FURS ARE DISTRIBUTED AMONG THE FOLLOWING\n", MAXFURS) + fmt.Println("KINDS OF PELTS: MINK, BEAVER, ERMINE AND FOX.") + fmt.Println() + + purchases := make([]int, 4) + + for i, f := range FURS() { + retry: + fmt.Printf("HOW MANY %s DO YOU HAVE: ", f) + scanner.Scan() + count, err := strconv.Atoi(scanner.Text()) + if err != nil { + fmt.Println("INVALID INPUT, TRY AGAIN ...") + goto retry + } + purchases[i] = count + } + + return purchases +} + +func main() { + rand.Seed(time.Now().UnixNano()) + + printTitle() + + gameState := STARTING + whichFort := FORT_NEWYORK + var ( + minkPrice int + erminePrice int + beaverPrice int + foxPrice int + ) + player := NewPlayer() + + for { + switch gameState { + case STARTING: + printIntro() + fmt.Println("DO YOU WISH TO TRADE FURS?") + if getYesOrNo() == "N" { + os.Exit(0) + } + gameState = TRADING + case TRADING: + fmt.Println() + fmt.Printf("YOU HAVE $ %1.2f IN SAVINGS\n", player.funds) + fmt.Printf("AND %d FURS TO BEGIN THE EXPEDITION\n", MAXFURS) + player.furs = getFursPurchase() + + if player.totalFurs() > MAXFURS { + fmt.Println() + fmt.Println("YOU MAY NOT HAVE THAT MANY FURS.") + fmt.Println("DO NOT TRY TO CHEAT. I CAN ADD.") + fmt.Println("YOU MUST START AGAIN.") + gameState = STARTING + } else { + gameState = CHOOSINGFORT + } + case CHOOSINGFORT: + whichFort = getFortChoice() + printFortComment(whichFort) + fmt.Println("DO YOU WANT TO TRADE AT ANOTHER FORT?") + changeFort := getYesOrNo() + if changeFort == "N" { + gameState = TRAVELLING + } + case TRAVELLING: + switch whichFort { + case FORT_MONTREAL: + minkPrice = (int((0.2*rand.Float64()+0.70)*100+0.5) / 100) + erminePrice = (int((0.2*rand.Float64()+0.65)*100+0.5) / 100) + beaverPrice = (int((0.2*rand.Float64()+0.75)*100+0.5) / 100) + foxPrice = (int((0.2*rand.Float64()+0.80)*100+0.5) / 100) + + fmt.Println("SUPPLIES AT FORT HOCHELAGA COST $150.00.") + fmt.Println("YOUR TRAVEL EXPENSES TO HOCHELAGA WERE $10.00.") + player.funds -= 160 + case FORT_QUEBEC: + minkPrice = (int((0.30*rand.Float64()+0.85)*100+0.5) / 100) + erminePrice = (int((0.15*rand.Float64()+0.80)*100+0.5) / 100) + beaverPrice = (int((0.20*rand.Float64()+0.90)*100+0.5) / 100) + foxPrice = (int((0.25*rand.Float64()+1.10)*100+0.5) / 100) + + event := int(10*rand.Float64()) + 1 + if event <= 2 { + fmt.Println("YOUR BEAVER WERE TOO HEAVY TO CARRY ACROSS") + fmt.Println("THE PORTAGE. YOU HAD TO LEAVE THE PELTS, BUT FOUND") + fmt.Println("THEM STOLEN WHEN YOU RETURNED.") + player.furs[FUR_BEAVER] = 0 + } else if event <= 6 { + fmt.Println("YOU ARRIVED SAFELY AT FORT STADACONA.") + } else if event <= 8 { + fmt.Println("YOUR CANOE UPSET IN THE LACHINE RAPIDS. YOU") + fmt.Println("LOST ALL YOUR FURS.") + player.lostFurs() + } else if event <= 10 { + fmt.Println("YOUR FOX PELTS WERE NOT CURED PROPERLY.") + fmt.Println("NO ONE WILL BUY THEM.") + player.furs[FUR_FOX] = 0 + } else { + log.Fatal("Unexpected error") + } + + fmt.Println() + fmt.Println("SUPPLIES AT FORT STADACONA COST $125.00.") + fmt.Println("YOUR TRAVEL EXPENSES TO STADACONA WERE $15.00.") + player.funds -= 140 + case FORT_NEWYORK: + minkPrice = (int((0.15*rand.Float64()+1.05)*100+0.5) / 100) + erminePrice = (int((0.15*rand.Float64()+0.95)*100+0.5) / 100) + beaverPrice = (int((0.25*rand.Float64()+1.00)*100+0.5) / 100) + foxPrice = (int((0.25*rand.Float64()+1.05)*100+0.5) / 100) // not in original code + + event := int(10*rand.Float64()) + 1 + if event <= 2 { + fmt.Println("YOU WERE ATTACKED BY A PARTY OF IROQUOIS.") + fmt.Println("ALL PEOPLE IN YOUR TRADING GROUP WERE") + fmt.Println("KILLED. THIS ENDS THE GAME.") + os.Exit(0) + } else if event <= 6 { + fmt.Println("YOU WERE LUCKY. YOU ARRIVED SAFELY") + fmt.Println("AT FORT NEW YORK.") + } else if event <= 8 { + fmt.Println("YOU NARROWLY ESCAPED AN IROQUOIS RAIDING PARTY.") + fmt.Println("HOWEVER, YOU HAD TO LEAVE ALL YOUR FURS BEHIND.") + player.lostFurs() + } else if event <= 10 { + minkPrice /= 2 + foxPrice /= 2 + fmt.Println("YOUR MINK AND BEAVER WERE DAMAGED ON YOUR TRIP.") + fmt.Println("YOU RECEIVE ONLY HALF THE CURRENT PRICE FOR THESE FURS.") + } else { + log.Fatal("Unexpected error") + } + + fmt.Println() + fmt.Println("SUPPLIES AT NEW YORK COST $85.00.") + fmt.Println("YOUR TRAVEL EXPENSES TO NEW YORK WERE $25.00.") + player.funds -= 110 + } + + beaverValue := beaverPrice * player.furs[FUR_BEAVER] + foxValue := foxPrice * player.furs[FUR_FOX] + ermineValue := erminePrice * player.furs[FUR_ERMINE] + minkValue := minkPrice * player.furs[FUR_MINK] + + fmt.Println() + fmt.Printf("YOUR BEAVER SOLD FOR $%6.2f\n", float64(beaverValue)) + fmt.Printf("YOUR FOX SOLD FOR $%6.2f\n", float64(foxValue)) + fmt.Printf("YOUR ERMINE SOLD FOR $%6.2f\n", float64(ermineValue)) + fmt.Printf("YOUR MINK SOLD FOR $%6.2f\n", float64(minkValue)) + + player.funds += float32(beaverValue + foxValue + ermineValue + minkValue) + + fmt.Println() + fmt.Printf("YOU NOW HAVE $%1.2f INCLUDING YOUR PREVIOUS SAVINGS\n", player.funds) + fmt.Println("\nDO YOU WANT TO TRADE FURS NEXT YEAR?") + if getYesOrNo() == "N" { + os.Exit(0) + } else { + gameState = TRADING + } + } + } +} From 41c367e7bfc63a7a755355ef0839734844c4772f Mon Sep 17 00:00:00 2001 From: Troy Campbell Date: Fri, 28 Oct 2022 12:26:25 +1000 Subject: [PATCH 11/17] Added go version of Guess --- 00_Alternate_Languages/41_Guess/go/main.go | 95 ++++++++++++++++++++++ 1 file changed, 95 insertions(+) create mode 100644 00_Alternate_Languages/41_Guess/go/main.go diff --git a/00_Alternate_Languages/41_Guess/go/main.go b/00_Alternate_Languages/41_Guess/go/main.go new file mode 100644 index 00000000..eea6ad22 --- /dev/null +++ b/00_Alternate_Languages/41_Guess/go/main.go @@ -0,0 +1,95 @@ +package main + +import ( + "bufio" + "fmt" + "math" + "math/rand" + "os" + "strconv" + "time" +) + +func printIntro() { + fmt.Println(" Guess") + fmt.Println("Creative Computing Morristown, New Jersey") + fmt.Println() + fmt.Println() + fmt.Println() + fmt.Println("This is a number guessing game. I'll think") + fmt.Println("of a number between 1 and any limit you want.") + fmt.Println("Then you have to guess what it is") +} + +func getLimit() (int, int) { + scanner := bufio.NewScanner(os.Stdin) + + for { + fmt.Println("What limit do you want?") + scanner.Scan() + + limit, err := strconv.Atoi(scanner.Text()) + if err != nil || limit < 0 { + fmt.Println("Please enter a number greater or equal to 1") + continue + } + + limitGoal := int((math.Log(float64(limit)) / math.Log(2)) + 1) + return limit, limitGoal + } + +} + +func main() { + rand.Seed(time.Now().UnixNano()) + printIntro() + + scanner := bufio.NewScanner(os.Stdin) + + limit, limitGoal := getLimit() + + guessCount := 1 + stillGuessing := true + won := false + myGuess := int(float64(limit)*rand.Float64() + 1) + + fmt.Printf("I'm thinking of a number between 1 and %d\n", limit) + fmt.Println("Now you try to guess what it is.") + + for stillGuessing { + scanner.Scan() + n, err := strconv.Atoi(scanner.Text()) + if err != nil { + fmt.Println("Please enter a number greater or equal to 1") + continue + } + + if n < 0 { + break + } + + fmt.Print("\n\n\n") + if n < myGuess { + fmt.Println("Too low. Try a bigger answer") + guessCount += 1 + } else if n > myGuess { + fmt.Println("Too high. Try a smaller answer") + guessCount += 1 + } else { + fmt.Printf("That's it! You got it in %d tries\n", guessCount) + won = true + stillGuessing = false + } + } + + if won { + if guessCount < limitGoal { + fmt.Println("Very good.") + } else if guessCount == limitGoal { + fmt.Println("Good.") + } else { + fmt.Printf("You should have been able to get it in only %d guesses.\n", limitGoal) + } + fmt.Print("\n\n\n") + } +} From 6085f9f4e2c79dc73dbd0aa8bebe3ef8269d47ac Mon Sep 17 00:00:00 2001 From: Troy Campbell Date: Fri, 28 Oct 2022 13:17:55 +1000 Subject: [PATCH 12/17] Added go version of Gunner --- 00_Alternate_Languages/42_Gunner/go/main.go | 125 ++++++++++++++++++++ 1 file changed, 125 insertions(+) create mode 100644 00_Alternate_Languages/42_Gunner/go/main.go diff --git a/00_Alternate_Languages/42_Gunner/go/main.go b/00_Alternate_Languages/42_Gunner/go/main.go new file mode 100644 index 00000000..8ea76cec --- /dev/null +++ b/00_Alternate_Languages/42_Gunner/go/main.go @@ -0,0 +1,125 @@ +package main + +import ( + "bufio" + "fmt" + "math" + "math/rand" + "os" + "strconv" + "strings" + "time" +) + +func printIntro() { + fmt.Println(" GUNNER") + fmt.Println(" CREATIVE COMPUTING MORRISTOWN, NEW JERSEY") + fmt.Print("\n\n\n") + fmt.Println("YOU ARE THE OFFICER-IN-CHARGE, GIVING ORDERS TO A GUN") + fmt.Println("CREW, TELLING THEM THE DEGREES OF ELEVATION YOU ESTIMATE") + fmt.Println("WILL PLACE A PROJECTILE ON TARGET. A HIT WITHIN 100 YARDS") + fmt.Println("OF THE TARGET WILL DESTROY IT.") + fmt.Println() +} + +func getFloat() float64 { + scanner := bufio.NewScanner(os.Stdin) + for { + scanner.Scan() + fl, err := strconv.ParseFloat(scanner.Text(), 64) + + if err != nil { + fmt.Println("Invalid input") + continue + } + + return fl + } +} + +func play() { + gunRange := int(40000*rand.Float64() + 20000) + fmt.Printf("\nMAXIMUM RANGE OF YOUR GUN IS %d YARDS\n", gunRange) + + killedEnemies := 0 + S1 := 0 + + for { + targetDistance := int(float64(gunRange) * (0.1 + 0.8*rand.Float64())) + shots := 0 + + fmt.Printf("\nDISTANCE TO THE TARGET IS %d YARDS\n", targetDistance) + + for { + fmt.Print("\n\nELEVATION? ") + elevation := getFloat() + + if elevation > 89 { + fmt.Println("MAXIMUM ELEVATION IS 89 DEGREES") + continue + } + + if elevation < 1 { + fmt.Println("MINIMUM ELEVATION IS 1 DEGREE") + continue + } + + shots += 1 + + if shots < 6 { + B2 := 2 * elevation / 57.3 + shotImpact := int(float64(gunRange) * math.Sin(B2)) + shotProximity := int(targetDistance - shotImpact) + + if math.Abs(float64(shotProximity)) < 100 { // hit + fmt.Printf("*** TARGET DESTROYED *** %d ROUNDS OF AMMUNITION EXPENDED.\n", shots) + S1 += shots + + if killedEnemies == 4 { + fmt.Printf("\n\nTOTAL ROUNDS EXPENDED WERE: %d\n", S1) + if S1 > 18 { + print("BETTER GO BACK TO FORT SILL FOR REFRESHER TRAINING!") + return + } else { + print("NICE SHOOTING !!") + return + } + } else { + killedEnemies += 1 + fmt.Println("\nTHE FORWARD OBSERVER HAS SIGHTED MORE ENEMY ACTIVITY...") + break + } + } else { // missed + if shotProximity > 100 { + fmt.Printf("SHORT OF TARGET BY %d YARDS.\n", int(math.Abs(float64(shotProximity)))) + } else { + fmt.Printf("OVER TARGET BY %d YARDS.\n", int(math.Abs(float64(shotProximity)))) + } + } + } else { + fmt.Print("\nBOOM !!!! YOU HAVE JUST BEEN DESTROYED BY THE ENEMY.\n\n\n") + fmt.Println("BETTER GO BACK TO FORT SILL FOR REFRESHER TRAINING!") + return + } + } + } +} + +func main() { + rand.Seed(time.Now().UnixNano()) + scanner := bufio.NewScanner(os.Stdin) + + printIntro() + + for { + play() + + fmt.Print("TRY AGAIN (Y OR N)? ") + scanner.Scan() + + if strings.ToUpper(scanner.Text())[0:1] != "Y" { + fmt.Println("\nOK. RETURN TO BASE CAMP.") + break + } + } +} From 9198cb360df459bfd28ff379c3507fff5fd0d5e1 Mon Sep 17 00:00:00 2001 From: Troy Campbell Date: Mon, 31 Oct 2022 07:20:34 +1000 Subject: [PATCH 13/17] Added go version of Buzzword --- 00_Alternate_Languages/20_Buzzword/go/main.go | 91 +++++++++++++++++++ 1 file changed, 91 insertions(+) create mode 100644 00_Alternate_Languages/20_Buzzword/go/main.go diff --git a/00_Alternate_Languages/20_Buzzword/go/main.go b/00_Alternate_Languages/20_Buzzword/go/main.go new file mode 100644 index 00000000..fdab9afa --- /dev/null +++ b/00_Alternate_Languages/20_Buzzword/go/main.go @@ -0,0 +1,91 @@ +package main + +import ( + "bufio" + "fmt" + "math/rand" + "os" + "strings" + "time" +) + +func main() { + rand.Seed(time.Now().UnixNano()) + words := [][]string{ + { + "Ability", + "Basal", + "Behavioral", + "Child-centered", + "Differentiated", + "Discovery", + "Flexible", + "Heterogeneous", + "Homogenous", + "Manipulative", + "Modular", + "Tavistock", + "Individualized", + }, { + "learning", + "evaluative", + "objective", + "cognitive", + "enrichment", + "scheduling", + "humanistic", + "integrated", + "non-graded", + "training", + "vertical age", + "motivational", + "creative", + }, { + "grouping", + "modification", + "accountability", + "process", + "core curriculum", + "algorithm", + "performance", + "reinforcement", + "open classroom", + "resource", + "structure", + "facility", + "environment", + }, + } + + scanner := bufio.NewScanner(os.Stdin) + + // Display intro text + fmt.Println("\n Buzzword Generator") + fmt.Println("Creative Computing Morristown, New Jersey") + fmt.Println("\n\n") + fmt.Println("This program prints highly acceptable phrases in") + fmt.Println("'educator-speak' that you can work into reports") + fmt.Println("and speeches. Whenever a question mark is printed,") + fmt.Println("type a 'Y' for another phrase or 'N' to quit.") + fmt.Println("\n\nHere's the first phrase:") + + for { + phrase := "" + for _, section := range words { + if len(phrase) > 0 { + phrase += " " + } + phrase += section[rand.Intn(len(section))] + } + fmt.Println(phrase) + fmt.Println() + + // continue? + fmt.Println("?") + scanner.Scan() + if strings.ToUpper(scanner.Text())[0:1] != "Y" { + break + } + } + fmt.Println("Come back when you need help with another report!") +} From f6d53947f34dd9aae77ff56b49d153b44dae7471 Mon Sep 17 00:00:00 2001 From: Troy Campbell Date: Mon, 31 Oct 2022 08:08:25 +1000 Subject: [PATCH 14/17] Added go version of Change --- 00_Alternate_Languages/22_Change/go/main.go | 115 ++++++++++++++++++++ 1 file changed, 115 insertions(+) create mode 100644 00_Alternate_Languages/22_Change/go/main.go diff --git a/00_Alternate_Languages/22_Change/go/main.go b/00_Alternate_Languages/22_Change/go/main.go new file mode 100644 index 00000000..fabe4d4b --- /dev/null +++ b/00_Alternate_Languages/22_Change/go/main.go @@ -0,0 +1,115 @@ +package main + +import ( + "bufio" + "fmt" + "math" + "os" + "strconv" +) + +func printWelcome() { + fmt.Println(" CHANGE") + fmt.Println("CREATIVE COMPUTING MORRISTOWN, NEW JERSEY") + fmt.Println() + fmt.Println() + fmt.Println() + fmt.Println("I, YOUR FRIENDLY MICROCOMPUTER, WILL DETERMINE") + fmt.Println("THE CORRECT CHANGE FOR ITEMS COSTING UP TO $100.") + fmt.Println() +} + +func computeChange(cost, payment float64) { + change := int(math.Round((payment - cost) * 100)) + + if change == 0 { + fmt.Println("\nCORRECT AMOUNT, THANK YOU.") + return + } + + if change < 0 { + fmt.Printf("\nSORRY, YOU HAVE SHORT-CHANGED ME $%0.2f\n", float64(change)/-100.0) + print() + return + } + + fmt.Printf("\nYOUR CHANGE, $%0.2f:\n", float64(change)/100.0) + + d := change / 1000 + if d > 0 { + fmt.Printf(" %d TEN DOLLAR BILL(S)\n", d) + change -= d * 1000 + } + + d = change / 500 + if d > 0 { + fmt.Printf(" %d FIVE DOLLAR BILL(S)\n", d) + change -= d * 500 + } + + d = change / 100 + if d > 0 { + fmt.Printf(" %d ONE DOLLAR BILL(S)\n", d) + change -= d * 100 + } + + d = change / 50 + if d > 0 { + fmt.Println(" 1 HALF DOLLAR") + change -= d * 50 + } + + d = change / 25 + if d > 0 { + fmt.Printf(" %d QUARTER(S)\n", d) + change -= d * 25 + } + + d = change / 10 + if d > 0 { + fmt.Printf(" %d DIME(S)\n", d) + change -= d * 10 + } + + d = change / 5 + if d > 0 { + fmt.Printf(" %d NICKEL(S)\n", d) + change -= d * 5 + } + + if change > 0 { + fmt.Printf(" %d PENNY(S)\n", change) + } +} + +func main() { + scanner := bufio.NewScanner(os.Stdin) + + printWelcome() + + var cost, payment float64 + var err error + for { + fmt.Println("COST OF ITEM?") + scanner.Scan() + cost, err = strconv.ParseFloat(scanner.Text(), 64) + if err != nil || cost < 0.0 { + fmt.Println("INVALID INPUT. TRY AGAIN.") + continue + } + break + } + for { + fmt.Println("\nAMOUNT OF PAYMENT?") + scanner.Scan() + payment, err = strconv.ParseFloat(scanner.Text(), 64) + if err != nil { + fmt.Println("INVALID INPUT. TRY AGAIN.") + continue + } + break + } + + computeChange(cost, payment) + fmt.Println() +} From 1407289473a1b7b09660bac627d90560867bd610 Mon Sep 17 00:00:00 2001 From: Troy Campbell Date: Mon, 31 Oct 2022 09:19:47 +1000 Subject: [PATCH 15/17] Added go version of Chief --- 00_Alternate_Languages/25_Chief/go/main.go | 116 +++++++++++++++++++++ 1 file changed, 116 insertions(+) create mode 100644 00_Alternate_Languages/25_Chief/go/main.go diff --git a/00_Alternate_Languages/25_Chief/go/main.go b/00_Alternate_Languages/25_Chief/go/main.go new file mode 100644 index 00000000..19d3e97c --- /dev/null +++ b/00_Alternate_Languages/25_Chief/go/main.go @@ -0,0 +1,116 @@ +package main + +import ( + "bufio" + "fmt" + "os" + "strconv" + "strings" +) + +func printLightning() { + fmt.Println("************************************") + n := 24 + for n > 16 { + var b strings.Builder + b.Grow(n + 3) + for i := 0; i < n; i++ { + b.WriteString(" ") + } + b.WriteString("x x") + fmt.Println(b.String()) + n-- + } + fmt.Println(" x xxx") + fmt.Println(" x x") + fmt.Println(" xx xx") + n-- + for n > 8 { + var b strings.Builder + b.Grow(n + 3) + for i := 0; i < n; i++ { + b.WriteString(" ") + } + b.WriteString("x x") + fmt.Println(b.String()) + n-- + } + fmt.Println(" xx") + fmt.Println(" x") + fmt.Println("************************************") +} + +func printSolution(n float64) { + fmt.Printf("\n%f plus 3 gives %f. This divided by 5 equals %f\n", n, n+3, (n+3)/5) + fmt.Printf("This times 8 gives %f. If we divide 5 and add 5.\n", ((n+3)/5)*8) + fmt.Printf("We get %f, which, minus 1 equals %f\n", (((n+3)/5)*8)/5+5, ((((n+3)/5)*8)/5+5)-1) +} + +func play() { + fmt.Println("\nTake a Number and ADD 3. Now, Divide this number by 5 and") + fmt.Println("multiply by 8. Now, Divide by 5 and add the same. Subtract 1") + + youHave := getFloat("\nWhat do you have?") + compGuess := (((youHave-4)*5)/8)*5 - 3 + if getYesNo(fmt.Sprintf("\nI bet your number was %f was I right(Yes or No)? ", compGuess)) { + fmt.Println("\nHuh, I knew I was unbeatable") + fmt.Println("And here is how i did it") + printSolution(compGuess) + } else { + originalNumber := getFloat("\nHUH!! what was you original number? ") + if originalNumber == compGuess { + fmt.Println("\nThat was my guess, AHA i was right") + fmt.Println("Shamed to accept defeat i guess, don't worry you can master mathematics too") + fmt.Println("Here is how i did it") + printSolution(compGuess) + } else { + fmt.Println("\nSo you think you're so smart, EH?") + fmt.Println("Now, Watch") + printSolution(originalNumber) + + if getYesNo("\nNow do you believe me? ") { + print("\nOk, Lets play again sometime bye!!!!") + } else { + fmt.Println("\nYOU HAVE MADE ME VERY MAD!!!!!") + fmt.Println("BY THE WRATH OF THE MATHEMATICS AND THE RAGE OF THE GODS") + fmt.Println("THERE SHALL BE LIGHTNING!!!!!!!") + printLightning() + fmt.Println("\nI Hope you believe me now, for your own sake") + } + } + } +} + +func getFloat(prompt string) float64 { + scanner := bufio.NewScanner(os.Stdin) + + for { + fmt.Println(prompt) + scanner.Scan() + val, err := strconv.ParseFloat(scanner.Text(), 64) + if err != nil { + fmt.Println("INVALID INPUT, TRY AGAIN") + continue + } + return val + } +} + +func getYesNo(prompt string) bool { + scanner := bufio.NewScanner(os.Stdin) + fmt.Println(prompt) + scanner.Scan() + + return (strings.ToUpper(scanner.Text())[0:1] == "Y") + +} + +func main() { + fmt.Println("I am CHIEF NUMBERS FREEK, The GREAT INDIAN MATH GOD.") + + if getYesNo("\nAre you ready to take the test you called me out for(Yes or No)? ") { + play() + } else { + fmt.Println("Ok, Nevermind. Let me go back to my great slumber, Bye") + } +} From cb3e6ca83d2aea53ded2df71fa4a78f8d4dc6760 Mon Sep 17 00:00:00 2001 From: Troy Campbell Date: Mon, 31 Oct 2022 14:12:57 +1000 Subject: [PATCH 16/17] Added go version of Hello --- 00_Alternate_Languages/45_Hello/go/main.go | 240 +++++++++++++++++++++ 1 file changed, 240 insertions(+) create mode 100644 00_Alternate_Languages/45_Hello/go/main.go diff --git a/00_Alternate_Languages/45_Hello/go/main.go b/00_Alternate_Languages/45_Hello/go/main.go new file mode 100644 index 00000000..b0aeda58 --- /dev/null +++ b/00_Alternate_Languages/45_Hello/go/main.go @@ -0,0 +1,240 @@ +package main + +import ( + "bufio" + "fmt" + "os" + "strings" + "time" +) + +type PROBLEM_TYPE int8 + +const ( + SEX PROBLEM_TYPE = iota + HEALTH + MONEY + JOB + UKNOWN +) + +func getYesOrNo() (bool, bool, string) { + scanner := bufio.NewScanner(os.Stdin) + + scanner.Scan() + + if strings.ToUpper(scanner.Text()) == "YES" { + return true, true, scanner.Text() + } else if strings.ToUpper(scanner.Text()) == "NO" { + return true, false, scanner.Text() + } else { + return false, false, scanner.Text() + } +} + +func printTntro() { + fmt.Println(" HELLO") + fmt.Println(" CREATIVE COMPUTING MORRISTOWN, NEW JERSEY") + fmt.Print("\n\n\n") + fmt.Println("HELLO. MY NAME IS CREATIVE COMPUTER.") + fmt.Println("\nWHAT'S YOUR NAME?") +} + +func askEnjoyQuestion(user string) { + fmt.Printf("HI THERE %s, ARE YOU ENJOYING YOURSELF HERE?\n", user) + + for { + valid, value, msg := getYesOrNo() + + if valid { + if value { + fmt.Printf("I'M GLAD TO HEAR THAT, %s.\n", user) + fmt.Println() + } else { + fmt.Printf("OH, I'M SORRY TO HEAR THAT, %s. MAYBE WE CAN\n", user) + fmt.Println("BRIGHTEN UP YOUR VISIT A BIT.") + } + break + } else { + fmt.Printf("%s, I DON'T UNDERSTAND YOUR ANSWER OF '%s'.\n", user, msg) + fmt.Println("PLEASE ANSWER 'YES' OR 'NO'. DO YOU LIKE IT HERE?") + } + } +} + +func promptForProblems(user string) PROBLEM_TYPE { + scanner := bufio.NewScanner(os.Stdin) + fmt.Println() + fmt.Printf("SAY %s, I CAN SOLVE ALL KINDS OF PROBLEMS EXCEPT\n", user) + fmt.Println("THOSE DEALING WITH GREECE. WHAT KIND OF PROBLEMS DO") + fmt.Println("YOU HAVE? (ANSWER SEX, HEALTH, MONEY, OR JOB)") + for { + scanner.Scan() + + switch strings.ToUpper(scanner.Text()) { + case "SEX": + return SEX + case "HEALTH": + return HEALTH + case "MONEY": + return MONEY + case "JOB": + return JOB + default: + return UKNOWN + } + } +} + +func promptTooMuchOrTooLittle() (bool, bool) { + scanner := bufio.NewScanner(os.Stdin) + + scanner.Scan() + + if strings.ToUpper(scanner.Text()) == "TOO MUCH" { + return true, true + } else if strings.ToUpper(scanner.Text()) == "TOO LITTLE" { + return true, false + } else { + return false, false + } +} + +func solveSexProblem(user string) { + fmt.Println("IS YOUR PROBLEM TOO MUCH OR TOO LITTLE?") + for { + valid, tooMuch := promptTooMuchOrTooLittle() + if valid { + if tooMuch { + fmt.Println("YOU CALL THAT A PROBLEM?!! I SHOULD HAVE SUCH PROBLEMS!") + fmt.Printf("IF IT BOTHERS YOU, %s, TAKE A COLD SHOWER.\n", user) + } else { + fmt.Printf("WHY ARE YOU HERE IN SUFFERN, %s? YOU SHOULD BE\n", user) + fmt.Println("IN TOKYO OR NEW YORK OR AMSTERDAM OR SOMEPLACE WITH SOME") + fmt.Println("REAL ACTION.") + } + return + } else { + fmt.Printf("DON'T GET ALL SHOOK, %s, JUST ANSWER THE QUESTION\n", user) + fmt.Println("WITH 'TOO MUCH' OR 'TOO LITTLE'. WHICH IS IT?") + } + } +} + +func solveHealthProblem(user string) { + fmt.Printf("MY ADVICE TO YOU %s IS:\n", user) + fmt.Println(" 1. TAKE TWO ASPRIN") + fmt.Println(" 2. DRINK PLENTY OF FLUIDS (ORANGE JUICE, NOT BEER!)") + fmt.Println(" 3. GO TO BED (ALONE)") +} + +func solveMoneyProblem(user string) { + fmt.Printf("SORRY, %s, I'M BROKE TOO. WHY DON'T YOU SELL\n", user) + fmt.Println("ENCYCLOPEADIAS OR MARRY SOMEONE RICH OR STOP EATING") + fmt.Println("SO YOU WON'T NEED SO MUCH MONEY?") +} + +func solveJobProblem(user string) { + fmt.Printf("I CAN SYMPATHIZE WITH YOU %s. I HAVE TO WORK\n", user) + fmt.Println("VERY LONG HOURS FOR NO PAY -- AND SOME OF MY BOSSES") + fmt.Printf("REALLY BEAT ON MY KEYBOARD. MY ADVICE TO YOU, %s,\n", user) + fmt.Println("IS TO OPEN A RETAIL COMPUTER STORE. IT'S GREAT FUN.") +} + +func askQuestionLoop(user string) { + for { + problem := promptForProblems(user) + + switch problem { + case SEX: + solveSexProblem(user) + case HEALTH: + solveHealthProblem(user) + case MONEY: + solveMoneyProblem(user) + case JOB: + solveJobProblem(user) + case UKNOWN: + fmt.Printf("OH %s, YOUR ANSWER IS GREEK TO ME.\n", user) + } + + for { + fmt.Println() + fmt.Printf("ANY MORE PROBLEMS YOU WANT SOLVED, %s?\n", user) + + valid, value, _ := getYesOrNo() + if valid { + if value { + fmt.Println("WHAT KIND (SEX, MONEY, HEALTH, JOB)") + break + } else { + return + } + } + fmt.Printf("JUST A SIMPLE 'YES' OR 'NO' PLEASE, %s\n", user) + } + } +} + +func goodbyeUnhappy(user string) { + fmt.Println() + fmt.Printf("TAKE A WALK, %s.\n", user) + fmt.Println() + fmt.Println() +} + +func goodbyeHappy(user string) { + fmt.Printf("NICE MEETING YOU %s, HAVE A NICE DAY.\n", user) +} + +func askForFee(user string) { + fmt.Println() + fmt.Printf("THAT WILL BE $5.00 FOR THE ADVICE, %s.\n", user) + fmt.Println("PLEASE LEAVE THE MONEY ON THE TERMINAL.") + time.Sleep(4 * time.Second) + fmt.Print("\n\n\n") + fmt.Println("DID YOU LEAVE THE MONEY?") + + for { + valid, value, msg := getYesOrNo() + if valid { + if value { + fmt.Printf("HEY, %s, YOU LEFT NO MONEY AT ALL!\n", user) + fmt.Println("YOU ARE CHEATING ME OUT OF MY HARD-EARNED LIVING.") + fmt.Println() + fmt.Printf("WHAT A RIP OFF, %s!!!\n", user) + fmt.Println() + } else { + fmt.Printf("THAT'S HONEST, %s, BUT HOW DO YOU EXPECT\n", user) + fmt.Println("ME TO GO ON WITH MY PSYCHOLOGY STUDIES IF MY PATIENTS") + fmt.Println("DON'T PAY THEIR BILLS?") + } + return + } else { + fmt.Printf("YOUR ANSWER OF '%s' CONFUSES ME, %s.\n", msg, user) + fmt.Println("PLEASE RESPOND WITH 'YES' or 'NO'.") + } + } +} + +func main() { + scanner := bufio.NewScanner(os.Stdin) + + printTntro() + scanner.Scan() + userName := scanner.Text() + fmt.Println() + + askEnjoyQuestion(userName) + + askQuestionLoop(userName) + + askForFee(userName) + + if false { + goodbyeHappy(userName) // unreachable + } else { + goodbyeUnhappy(userName) + } + +} From 4ef4a7d7e8c1b9de9a5256d6b5f4946026b3be92 Mon Sep 17 00:00:00 2001 From: Troy Campbell Date: Mon, 31 Oct 2022 14:35:22 +1000 Subject: [PATCH 17/17] Added go version of Hilo --- 00_Alternate_Languages/47_Hi-Lo/go/main.go | 77 ++++++++++++++++++++++ 1 file changed, 77 insertions(+) create mode 100644 00_Alternate_Languages/47_Hi-Lo/go/main.go diff --git a/00_Alternate_Languages/47_Hi-Lo/go/main.go b/00_Alternate_Languages/47_Hi-Lo/go/main.go new file mode 100644 index 00000000..99bea1c3 --- /dev/null +++ b/00_Alternate_Languages/47_Hi-Lo/go/main.go @@ -0,0 +1,77 @@ +package main + +import ( + "bufio" + "fmt" + "math/rand" + "os" + "strconv" + "strings" + "time" +) + +const MAX_ATTEMPTS = 6 + +func printIntro() { + fmt.Println("HI LO") + fmt.Println("CREATIVE COMPUTING MORRISTOWN, NEW JERSEY") + fmt.Println("\n\n\nTHIS IS THE GAME OF HI LO.") + fmt.Println("\nYOU WILL HAVE 6 TRIES TO GUESS THE AMOUNT OF MONEY IN THE") + fmt.Println("HI LO JACKPOT, WHICH IS BETWEEN 1 AND 100 DOLLARS. IF YOU") + fmt.Println("GUESS THE AMOUNT, YOU WIN ALL THE MONEY IN THE JACKPOT!") + fmt.Println("THEN YOU GET ANOTHER CHANCE TO WIN MORE MONEY. HOWEVER,") + fmt.Println("IF YOU DO NOT GUESS THE AMOUNT, THE GAME ENDS.") + fmt.Println() + fmt.Println() +} + +func main() { + rand.Seed(time.Now().UnixNano()) + scanner := bufio.NewScanner(os.Stdin) + + printIntro() + + totalWinnings := 0 + + for { + fmt.Println() + secret := rand.Intn(1000) + 1 + + guessedCorrectly := false + + for attempt := 0; attempt < MAX_ATTEMPTS; attempt++ { + fmt.Println("YOUR GUESS?") + scanner.Scan() + guess, err := strconv.Atoi(scanner.Text()) + if err != nil { + fmt.Println("INVALID INPUT") + } + + if guess == secret { + fmt.Printf("GOT IT!!!!!!!!!! YOU WIN %d DOLLARS.\n", secret) + guessedCorrectly = true + break + } else if guess > secret { + fmt.Println("YOUR GUESS IS TOO HIGH.") + } else { + fmt.Println("YOUR GUESS IS TOO LOW.") + } + } + + if guessedCorrectly { + totalWinnings += secret + fmt.Printf("YOUR TOTAL WINNINGS ARE NOW $%d.\n", totalWinnings) + } else { + fmt.Printf("YOU BLEW IT...TOO BAD...THE NUMBER WAS %d\n", secret) + } + + fmt.Println() + fmt.Println("PLAYAGAIN (YES OR NO)?") + scanner.Scan() + + if strings.ToUpper(scanner.Text())[0:1] != "Y" { + break + } + } + fmt.Println("\nSO LONG. HOPE YOU ENJOYED YOURSELF!!!") +}