diff --git a/00_Alternate_Languages/01_Acey_Ducey/nim/aceyducey.nim b/00_Alternate_Languages/01_Acey_Ducey/nim/aceyducey.nim index a36aacf9..abc03def 100644 --- a/00_Alternate_Languages/01_Acey_Ducey/nim/aceyducey.nim +++ b/00_Alternate_Languages/01_Acey_Ducey/nim/aceyducey.nim @@ -4,66 +4,68 @@ var bet, cardA, cardB, cardC, stash: int retry: bool = true +randomize() # Seed the random number generator + proc printGreeting() = - echo(spaces(26),"ACEY DUCEY CARD GAME") - echo(spaces(15),"CREATIVE COMPUTING MORRISTOWN, NEW JERSEY") - echo("\n") - echo("ACEY-DUCEY IS PLAYED IN THE FOLLOWING MANNER ") - echo("THE DEALER (COMPUTER) DEALS TWO CARDS FACE UP") - echo("YOU HAVE AN OPTION TO BET OR NOT BET DEPENDING") - echo("ON WHETHER OR NOT YOU FEEL THE CARD WILL HAVE") - echo("A VALUE BETWEEN THE FIRST TWO.") - echo("IF YOU DO NOT WANT TO BET, INPUT A 0") - echo("") + echo spaces(26),"ACEY DUCEY CARD GAME" + echo spaces(15),"CREATIVE COMPUTING MORRISTOWN, NEW JERSEY" + echo """ + +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 + +""" proc printBalance() = - echo("YOU NOW HAVE ", stash," DOLLARS.") - echo("") + echo "YOU NOW HAVE ", stash," DOLLARS." + echo "" proc printCard(aCard: int) = case aCard: - of 11: echo("=== JACK ===") - of 12: echo("=== QUEEN ===") - of 13: echo("=== KING ===") - of 14: echo("=== ACE ===") - else: echo("=== ", aCard, " ===") + of 11: echo "=== JACK ===" + of 12: echo "=== QUEEN ===" + of 13: echo "=== KING ===" + of 14: echo "=== ACE ===" + else: echo "=== ", aCard, " ===" proc drawDealerCards() = - echo("HERE ARE YOUR NEXT TWO CARDS: ") - cardA = rand(2..14) + echo "HERE ARE YOUR NEXT TWO CARDS: " + cardA = rand 2..14 cardB = cardA # Copy cardA, so we can test cardB to be different while cardB == cardA: - cardB = rand(2..14) + cardB = rand 2..14 if cardA > cardB: # Make sure cardA is the smaller card - swap(cardA, cardB) - echo("") - printCard(cardA) - echo("") - printCard(cardB) - echo("") + swap cardA, cardB + echo "" + printCard cardA + echo "" + printCard cardB + echo "" proc drawPlayerCard() = - cardC = rand(2..14) - printCard(cardC) - echo("") + cardC = rand 2..14 + printCard cardC + echo "" proc getBet(): int = result = stash + 1 #ensure we enter the loop while (result < 0) or (result > stash): - echo("WHAT IS YOUR BET: ") + echo "WHAT IS YOUR BET: " result = readLine(stdin).parseInt() if result > stash: - echo("SORRY, MY FRIEND, BUT YOU BET TOO MUCH.") - echo("YOU HAVE ONLY ", stash," DOLLARS TO BET.") - if bet == 0: - echo("CHICKEN!!") + echo "SORRY, MY FRIEND, BUT YOU BET TOO MUCH." + echo "YOU HAVE ONLY ", stash, " DOLLARS TO BET." + if result == 0: + echo "CHICKEN!!" proc tryAgain(): bool = - echo("TRY AGAIN (YES OR NO)") + echo "TRY AGAIN (YES OR NO)" var answer = readLine(stdin).normalize() - case answer: - of "yes", "y": result = true - else: result = false + result = (answer == "y") or (answer == "yes") printGreeting() while retry: @@ -72,15 +74,16 @@ while retry: printBalance() drawDealerCards() bet = getBet() - echo("") + echo "" drawPlayerCard() if (cardC >= cardA) and (cardC <= cardB): - echo("YOU WIN!!!") + echo "YOU WIN!!!" stash += bet else: - echo("SORRY, YOU LOSE") - stash -= bet - echo("SORRY, FRIEND, BUT YOU BLEW YOUR WAD."); - echo("") + if bet > 0: + echo "SORRY, YOU LOSE" + stash -= bet + echo "SORRY, FRIEND, BUT YOU BLEW YOUR WAD." + echo "" retry = tryAgain() -echo("O.K., HOPE YOU HAD FUN!"); +echo "O.K., HOPE YOU HAD FUN!" diff --git a/00_Alternate_Languages/05_Bagels/nim/bagels.nim b/00_Alternate_Languages/05_Bagels/nim/bagels.nim index d1866913..f302b375 100644 --- a/00_Alternate_Languages/05_Bagels/nim/bagels.nim +++ b/00_Alternate_Languages/05_Bagels/nim/bagels.nim @@ -10,6 +10,8 @@ var prompt: string stillplaying: bool = true +randomize() # Seed the random number generator + # Seed 3 unique random numbers; indicate if they're all unique proc genSeed(): bool = for i in 1..3: @@ -24,19 +26,19 @@ proc playGame() = # We want 3 unique random numbers: loop until we get them! while unique == false: unique = genSeed() - echo("O.K. I HAVE A NUMBER IN MIND.") + echo "O.K. I HAVE A NUMBER IN MIND." for i in 1..20: var c, d: int = 0 - echo("GUESS #", i) + echo "GUESS #", i prompt = readLine(stdin).normalize() if (prompt.len() != 3): - echo("TRY GUESSING A THREE-DIGIT NUMBER.") + echo "TRY GUESSING A THREE-DIGIT NUMBER." continue for z in 1..3: b[z] = prompt.substr(z-1, z-1).parseInt() # Convert string digits to array ints if (b[1] == b[2]) or (b[2] == b[3]) or (b[3] == b[1]): - echo("OH, I FORGOT TO TELL YOU THAT THE NUMBER I HAVE IN MIND") - echo("HAS NO TWO DIGITS THE SAME.") + echo "OH, I FORGOT TO TELL YOU THAT THE NUMBER I HAVE IN MIND" + echo "HAS NO TWO DIGITS THE SAME." # Figure out the PICOs if (a[1] == b[2]): c += 1 if (a[1] == b[3]): c += 1 @@ -51,45 +53,45 @@ proc playGame() = if (d != 3): if (c != 0): for j in 1..c: - echo("PICO") + echo "PICO" if (d != 0): for j in 1..d: - echo("FERMI") + echo "FERMI" if (c == 0) and (d == 0): - echo("BAGELS") + echo "BAGELS" # If we have 3 FERMIs, we win! else: - echo("YOU GOT IT!!!") - echo("") + echo "YOU GOT IT!!!" + echo "" wincount += 1 youwin = true break # Only invoke if we've tried 20 guesses without winning - if (youwin == false): - echo("OH WELL.") - echo("THAT'S TWENTY GUESSES. MY NUMBER WAS ", a[1], a[2], a[3]) + if not youwin: + echo "OH WELL." + echo "THAT'S TWENTY GUESSES. MY NUMBER WAS ", a[1], a[2], a[3] # main program -echo(spaces(33), "BAGELS") -echo(spaces(15), "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY") -echo("\n\n") -echo("WOULD YOU LIKE THE RULES (YES OR NO)") +echo spaces(33), "BAGELS" +echo spaces(15), "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY" +echo "\n\n" +echo "WOULD YOU LIKE THE RULES (YES OR NO)" prompt = readLine(stdin).normalize() -if (prompt.substr(0, 0) == "y"): - echo("I AM THINKING OF A THREE-DIGIT NUMBER. TRY TO GUESS") - echo("MY NUMBER AND I WILL GIVE YOU CLUES AS FOLLOWS:") - echo(" PICO - ONE DIGIT CORRECT BUT IN THE WRONG POSITION") - echo(" FERMI - ONE DIGIT CORRECT AND IN THE RIGHT POSITION") - echo(" BAGELS - NO DIGITS CORRECT") - echo("") +if prompt.substr(0, 0) == "y": + echo "I AM THINKING OF A THREE-DIGIT NUMBER. TRY TO GUESS" + echo "MY NUMBER AND I WILL GIVE YOU CLUES AS FOLLOWS:" + echo " PICO - ONE DIGIT CORRECT BUT IN THE WRONG POSITION" + echo " FERMI - ONE DIGIT CORRECT AND IN THE RIGHT POSITION" + echo " BAGELS - NO DIGITS CORRECT" + echo "" while(stillplaying == true): playGame() - echo("PLAY AGAIN (YES OR NO)") + echo "PLAY AGAIN (YES OR NO)" prompt = readLine(stdin).normalize() - if (prompt.substr(0, 0) != "y"): + if prompt.substr(0, 0) != "y": stillplaying = false if wincount > 0: - echo("") - echo("A ", wincount, " POINT BAGELS BUFF!!") -echo("") -echo("HOPE YOU HAD FUN. BYE.") + echo "" + echo "A ", wincount, " POINT BAGELS BUFF!!" +echo "" +echo "HOPE YOU HAD FUN. BYE." diff --git a/00_Alternate_Languages/20_Buzzword/nim/buzzword.nim b/00_Alternate_Languages/20_Buzzword/nim/buzzword.nim new file mode 100644 index 00000000..dfba31c9 --- /dev/null +++ b/00_Alternate_Languages/20_Buzzword/nim/buzzword.nim @@ -0,0 +1,34 @@ +import std/[random,strutils] + +randomize() + +const + words1 = ["ABILITY","BASAL","BEHAVIORAL","CHILD-CENTERED","DIFFERENTIATED","DISCOVERY","FLEXIBLE", + "HETEROGENEOUS","HOMOGENEOUS","MANIPULATIVE","MODULAR","TAVISTOCK","INDIVIDUALIZED"] + words2 = ["LEARNING","EVALUATIVE","OBJECTIVE","COGNITIVE","ENRICHMENT","SCHEDULING","HUMANISTIC", + "INTEGRATED","NON-GRADED","TRAINING","VERTICAL AGE","MOTIVATIONAL","CREATIVE"] + words3 = ["GROUPING","MODIFICATION","ACCOUNTABILITY","PROCESS","CORE CURRICULUM","ALGORITHM", "PERFORMANCE", + "REINFORCEMENT","OPEN CLASSROOM","RESOURCE","STRUCTURE","FACILITY","ENVIRONMENT"] + +var + stillplaying: bool = true + prompt: string + +echo spaces(26), "BUZZWORD GENERATOR" +echo spaces(15), "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY" +echo "\n" +echo "THIS PROGRAM PRINTS HIGHLY ACCEPTABLE PHRASES IN" +echo "'EDUCATOR-SPEAK' THAT YOU CAN WORK INTO REPORTS" +echo "AND SPEECHES. AFTER EACH PHRASE, HIT 'ENTER' FOR" +echo "ANOTHER PHRASE, OR TYPE 'N' TO QUIT." +echo "\n" +echo "HERE'S THE FIRST PHRASE..." + +while stillplaying: + echo "" + echo words1[rand(0..12)], " ", words2[rand(0..12)], " ", words3[rand(0..12)] + prompt = readLine(stdin).normalize() + if prompt.substr(0, 0) == "n": + stillplaying = false + +echo "COME BACK WHEN YOU NEED HELP WITH ANOTHER REPORT!" diff --git a/00_Alternate_Languages/29_Craps/nim/craps.nim b/00_Alternate_Languages/29_Craps/nim/craps.nim new file mode 100644 index 00000000..770b6c0e --- /dev/null +++ b/00_Alternate_Languages/29_Craps/nim/craps.nim @@ -0,0 +1,68 @@ +import std/[random,strutils] + +var + wager, winnings, rollResult: int + stillplaying: bool = true + +randomize() # Seed the random number generator + +proc tryAgain(): bool = + echo "WANT TO PLAY AGAIN? (YES OR NO)" + var answer = readLine(stdin).normalize() + result = (answer == "y") or (answer == "yes") + +proc takePoint(point: int) = + var flag = true + while flag: + var pointRoll: int = (rand 1..6) + (rand 1..6) # roll dice, then add the sum + if pointRoll == 7: + echo pointRoll, "- CRAPS. YOU LOSE." + echo "YOU LOSE ", wager, " DOLLARS." + winnings -= wager + flag = false + if pointRoll == point: + echo point, "- A WINNER.........CONGRATS!!!!!!!!" + echo "AT 2 TO 1 ODDS PAYS YOU...LET ME SEE... ", 2*wager, " DOLLARS" + winnings += (2*wager) + flag = false + if flag: + echo pointRoll, " - NO POINT. I WILL ROLL AGAIN" + +echo spaces(33), "CRAPS" +echo spaces(15), "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY" +echo "\n" +echo "2,3,12 ARE LOSERS; 4,5,6,8,9,10 ARE POINTS; 7,11 ARE NATURAL WINNERS." +winnings = 0 + +# play the game +while stillplaying: + echo "" + echo "INPUT THE AMOUNT OF YOUR WAGER." + wager = readline(stdin).parseInt() + echo "I WILL NOW THROW THE DICE" + rollResult = (rand 1..6) + (rand 1..6) # roll dice, then add the sum + case rollResult: + of 7, 11: + echo rollResult, "- NATURAL....A WINNER!!!!" + echo rollResult, " PAYS EVEN MONEY, YOU WIN ", wager, " DOLLARS" + winnings += wager + of 2: + echo rollResult, "- SNAKE EYES....YOU LOSE." + echo "YOU LOSE ", wager, " DOLLARS." + winnings -= wager + of 3, 12: + echo rollResult, "- CRAPS...YOU LOSE." + echo "YOU LOSE ", wager, " DOLLARS." + winnings -= wager + else: + echo rollResult, " IS THE POINT. I WILL ROLL AGAIN" + takePoint(rollResult) + if winnings < 0: echo "YOU ARE NOW UNDER $", winnings + if winnings > 0: echo "YOU ARE NOW AHEAD $", winnings + if winnings == 0: echo "YOU ARE NOW EVEN AT 0" + stillplaying = tryAgain() + +# done playing +if winnings < 0: echo "TOO BAD, YOU ARE IN THE HOLE. COME AGAIN." +if winnings > 0: echo "CONGRATULATIONS---YOU CAME OUT A WINNER. COME AGAIN!" +if winnings == 0: echo "CONGRATULATIONS---YOU CAME OUT EVEN, NOT BAD FOR AN AMATEUR" diff --git a/00_Alternate_Languages/33_Dice/nim/dice.nim b/00_Alternate_Languages/33_Dice/nim/dice.nim index a1e5fa45..6564ae9b 100644 --- a/00_Alternate_Languages/33_Dice/nim/dice.nim +++ b/00_Alternate_Languages/33_Dice/nim/dice.nim @@ -6,17 +6,19 @@ var z: string retry: bool = true -echo(spaces(34), "DICE") -echo(spaces(15), "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY") -echo("\n") -echo("THIS PROGRAM SIMULATES THE ROLLING OF A PAIR OF DICE.") -echo("YOU ENTER THE NUMBER OF TIMES YOU WANT THE COMPUTER TO") -echo("'ROLL' THE DICE. WATCH OUT, VERY LARGE NUMBERS TAKE") -echo("A LONG TIME. IN PARTICULAR, NUMBERS OVER 5000.") +randomize() # Seed the random number generator + +echo spaces(34), "DICE" +echo spaces(15), "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY" +echo "\n" +echo "THIS PROGRAM SIMULATES THE ROLLING OF A PAIR OF DICE." +echo "YOU ENTER THE NUMBER OF TIMES YOU WANT THE COMPUTER TO" +echo "'ROLL' THE DICE. WATCH OUT, VERY LARGE NUMBERS TAKE" +echo "A LONG TIME. IN PARTICULAR, NUMBERS OVER 5000." while(retry): - echo("\n") - echo("HOW MANY ROLLS") + echo "\n" + echo "HOW MANY ROLLS" x = readLine(stdin).parseInt() for v in 2..12: f[v] = 0 # Initialize array to 0 @@ -25,14 +27,11 @@ while(retry): b = rand(1..6) # Die 2 r = a + b # Sum of dice f[r] += 1 # Increment array count of dice sum result - echo() - echo("TOTAL SPOTS: ", "NUMBER OF TIMES") + echo "" + echo "TOTAL SPOTS: ", "NUMBER OF TIMES" for v in 2..12: - echo(v, ": ", f[v]) # Print out counts for each possible result - echo("\n") - echo("TRY AGAIN?") + echo v, ": ", f[v] # Print out counts for each possible result + echo "\n" + echo "TRY AGAIN?" z = readLine(stdin).normalize() - if (z=="yes") or (z=="y"): - retry = true - else: - retry = false + retry = (z=="yes") or (z=="y") diff --git a/00_Alternate_Languages/74_Rock_Scissors_Paper/nim/rockscissors.nim b/00_Alternate_Languages/74_Rock_Scissors_Paper/nim/rockscissors.nim new file mode 100644 index 00000000..3c0cda0c --- /dev/null +++ b/00_Alternate_Languages/74_Rock_Scissors_Paper/nim/rockscissors.nim @@ -0,0 +1,68 @@ +import std/[random,strformat,strutils] + +type + symbol = enum + PAPER = 1, SCISSORS = 2, ROCK = 3 + +var + cpuChoice, playerChoice, turns: int + cpuWins, playerWins, ties: int = 0 + +randomize() + +# Function: player makes a choice +proc choose(): int = + echo "3=ROCK...2=SCISSORS...1=PAPER...WHAT'S YOUR CHOICE?" + result = readLine(stdin).parseInt() + +# Function: determine the outcome +proc outcome(p: symbol, c: symbol): string = + if p == c: + ties += 1 + result = "TIE GAME. NO WINNER." + else: + const + winTable = [ + PAPER: (ROCK, "COVERS"), + SCISSORS: (PAPER, "CUTS"), + ROCK: (SCISSORS, "CRUSHES") + ] + let (winCond, winVerb) = winTable[p] + if winCond == c: + playerWins += 1 + result = fmt"{p} {winVerb} {c}. YOU WIN." + else: + let (_, winVerb) = winTable[c] + cpuWins += 1 + result = fmt"{c} {winVerb} {p}. I WIN." + +# Start the game +echo spaces(21), "GAME OF ROCK, SCISSORS, PAPER" +echo spaces(15), "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY" +echo "\n" +echo "HOW MANY GAMES?" +turns = readLine(stdin).parseInt() +while turns > 10: + echo "SORRY, BUT WE AREN'T ALLOWED TO PLAY THAT MANY." + turns = readLine(stdin).parseInt() + +# Play the game +for i in 1..turns: + echo "" + echo "GAME NUMBER ", i + playerChoice = choose() + while playerChoice != 1 and playerChoice != 2 and playerChoice != 3: + echo "INVALID" + playerChoice = choose() + cpuChoice = rand(1..3) # match against range in symbol + echo "THIS IS MY CHOICE... ", symbol(cpuChoice) + echo outcome(symbol(playerChoice), symbol(cpuChoice)) + +# Results +echo "" +echo "HERE IS THE FINAL GAME SCORE:" +echo "I HAVE WON ", cpuWins," GAME(S)." +echo "YOU HAVE WON ", playerWins," GAME(S)." +echo "AND ", ties," GAME(S) ENDED IN A TIE." +echo "" +echo "THANKS FOR PLAYING!!" diff --git a/00_Alternate_Languages/91_Train/nim/train.nim b/00_Alternate_Languages/91_Train/nim/train.nim new file mode 100644 index 00000000..aa92c1a7 --- /dev/null +++ b/00_Alternate_Languages/91_Train/nim/train.nim @@ -0,0 +1,38 @@ +import std/[random,strutils] + +var + carSpeed, diff, err, guess, trainSpeed, carTime: int + stillplaying: bool = true + +randomize() # Seed the random number generator + +# Return a tuple that'll be carSpeed, diff, trainSpeed +proc randomNumbers(): (int,int,int) = + result = (rand(41..65), rand(6..20), rand(21..39)) + +# Do we want to play again? +proc tryAgain(): bool = + echo "ANOTHER PROBLEM (YES OR NO)" + var answer = readLine(stdin).normalize() + result = (answer == "y") or (answer == "yes") + +echo spaces(33), "TRAIN" +echo spaces(15), "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY" +echo "\n" +echo "TIME - SPEED DISTANCE EXERCISE" + +while stillplaying: + echo "" + (carSpeed, diff, trainSpeed) = randomNumbers() # Get random numbers for prompt + echo "A CAR TRAVELING ", carSpeed, " MPH CAN MAKE A CERTAIN TRIP IN" + echo diff, " HOURS LESS THAN A TRAIN TRAVELING AT ", trainSpeed, " MPH." + echo "HOW LONG DOES THE TRIP TAKE BY CAR?" + guess = readLine(stdin).parseInt() # Get guess + carTime = (diff * trainSpeed / (carSpeed - trainSpeed)).toInt() # Calculate answer + err = (((carTime - guess) * 100) / guess).toInt().abs() # Calculate error to an absolute value + if err > 5: # Error within 5%? + echo "SORRY. YOU WERE OFF BY ", err, " PERCENT." + else: + echo "GOOD! ANSWER WITHIN ", err, " PERCENT." + echo "CORRECT ANSWER IS ", carTime, " HOURS." + stillplaying = tryAgain() diff --git a/01_Acey_Ducey/elixir/acey_ducey.exs b/01_Acey_Ducey/elixir/acey_ducey.exs new file mode 100644 index 00000000..31308df7 --- /dev/null +++ b/01_Acey_Ducey/elixir/acey_ducey.exs @@ -0,0 +1,97 @@ +######################################################## +# +# Acey Ducey +# +# From: BASIC Computer Games (1978) +# Edited by David Ahl +# +# "This is a simulation of the Acey Ducey card game. +# In the game, the dealer (the computer) deals two +# cards face up. You have an option to bet or not to +# bet depending on whether or not you feel the next +# card dealt will have a value between the first two. +# +# "Your initial money is set to $100. The game keeps +# going on until you lose all your money or interrupt +# the program. +# +# "The original BASIC program author was Bill Palmby +# of Prairie View, Illinois." +# +# To run this file: +# > mix run acey_ducey.exs --no-mix-exs +# +# This uses the following techniques: +# +# - The `Game` module uses a recursive `play/1` function. +# - The `Game` module stores the game state in a `%Game{}` struct. +# - The classic 52 playing card deck is set as a module attribute generated via a comprehension. +# - The deck is automatically shuffled when there are less than 3 cards remaining in the deck. +# - The initial deck defaults to an empty list which triggers a shuffle when the game begins. +# - The initial funds defaults to 100 but it can be explicitly set in the `%Game{}` struct. +# - The prompt to place a bet will automatically re-prompt when given an invalid input. +# - The bets are assumed to be the whole integers for simplicity. +# +######################################################## + +defmodule Game do + @deck for suit <- [:spades, :hearts, :clubs, :diamonds], value <- 1..13, do: {suit, value} + + defstruct funds: 100, deck: [] + + def play(), do: play(%__MODULE__{}) # for convenience + + def play(%__MODULE__{funds: funds}) when funds <= 0, do: IO.puts("~~~ game over ~~~") + def play(%__MODULE__{deck: deck} = game) when length(deck) < 3, do: play(%{game | deck: Enum.shuffle(@deck)}) + def play(%__MODULE__{deck: deck, funds: funds} = game) do + IO.gets("\n") + + [first_card, second_card, third_card | remaining_deck] = deck + + IO.puts("~~~ new round ~~~") + IO.puts("first card: #{format(first_card)}") + IO.puts("second card: #{format(second_card)}\n") + IO.puts("funds: $#{funds}") + + bet = prompt_to_place_bet(funds) + new_funds = if win?(first_card, second_card, third_card), do: funds + bet, else: funds - bet + + IO.puts("\nthird card: #{format(third_card)}") + IO.puts("funds: $#{funds} => $#{new_funds}") + IO.puts("~~~ end round ~~~\n") + + play(%{game | deck: remaining_deck, funds: new_funds}) + end + + # re-prompt if invalid integer and/or out of bounds + defp prompt_to_place_bet(funds) do + input = IO.gets("place your bet: $") + case Integer.parse(input) do + {bet, _} when bet in 0..funds -> bet + _ -> prompt_to_place_bet(funds) + end + end + + # for a stricter win condition (non-inclusive) + defp win?({_, first}, {_, second}, {_, third}) do + [floor, ceiling] = Enum.sort([first, second]) + (floor < third) && (third < ceiling) + end + # for a looser win condition (inclusive) + #defp win?({_, first}, {_, second}, {_, third}) do + #[_, middle, _] = Enum.sort([first, second, third]) + #middle == third + #end + + defp format({suit, value}) do + case value do + 1 -> "ace of #{suit}" + 11 -> "prince of #{suit}" + 12 -> "queen of #{suit}" + 13 -> "king of #{suit}" + value -> "#{value} of #{suit}" + end + end +end + +Game.play() # equivalent to Game.play(%Game{funds: 100, deck: 100}) diff --git a/01_Acey_Ducey/python/acey_ducey.py b/01_Acey_Ducey/python/acey_ducey.py index 603e01af..8e353569 100755 --- a/01_Acey_Ducey/python/acey_ducey.py +++ b/01_Acey_Ducey/python/acey_ducey.py @@ -7,7 +7,6 @@ https://www.atariarchives.org/basicgames/showpage.php?page=2 import random cards = { - 1: "1", 2: "2", 3: "3", 4: "4", @@ -16,22 +15,25 @@ cards = { 7: "7", 8: "8", 9: "9", - 10: "Jack", - 11: "Queen", - 12: "King", - 13: "Ace", + 10: "10", + 11: "Jack", + 12: "Queen", + 13: "King", + 14: "Ace", } - def play_game() -> None: cash = 100 while cash > 0: print(f"You now have {cash} dollars\n") print("Here are you next two cards") - round_cards = list(cards.keys()) - random.shuffle(round_cards) - card_a, card_b, card_c = round_cards.pop(), round_cards.pop(), round_cards.pop() - if card_a > card_b: + round_cards = list(cards.keys()) # gather cards from dictionary + card_a = random.choice(round_cards) # choose a card + card_b = card_a # clone the first card, so we avoid the same number for the second card + while (card_a == card_b): # if the cards are the same, choose another card + card_b = random.choice(round_cards) + card_c = random.choice(round_cards) # choose last card + if card_a > card_b: # swap cards if card_a is greater than card_b card_a, card_b = card_b, card_a print(f" {cards[card_a]}") print(f" {cards[card_b]}\n") @@ -53,7 +55,7 @@ def play_game() -> None: print("Please enter a positive number") print(f" {cards[card_c]}") if bet > 0: - if card_a < card_c < card_b: + if card_a <= card_c <= card_b: print("You win!!!") cash += bet * 2 else: @@ -82,4 +84,5 @@ If you do not want to bet, input a 0 if __name__ == "__main__": + random.seed() main() diff --git a/01_Acey_Ducey/python/acey_ducey_oo.py b/01_Acey_Ducey/python/acey_ducey_oo.py index 35b26d84..cd5cad76 100644 --- a/01_Acey_Ducey/python/acey_ducey_oo.py +++ b/01_Acey_Ducey/python/acey_ducey_oo.py @@ -8,6 +8,7 @@ Python port by Aviyam Fischer, 2022 """ from typing import List, Literal, NamedTuple, TypeAlias, get_args +import random Suit: TypeAlias = Literal["\u2665", "\u2666", "\u2663", "\u2660"] Rank: TypeAlias = Literal[2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] @@ -34,8 +35,6 @@ class Deck: self.cards.append(Card(suit, rank)) def shuffle(self) -> None: - import random - random.shuffle(self.cards) def deal(self) -> Card: @@ -72,7 +71,7 @@ class Game: if 0 < bet <= self.money: print(f"Your deal:\t {player_card}") - if card_a.rank < player_card.rank < card_b.rank: + if card_a.rank <= player_card.rank <= card_b.rank: print("You Win!") self.money += bet else: @@ -87,9 +86,6 @@ class Game: else: print("You would lose, so it was wise of you to chicken out!") - self.not_done = False - break - if len(self.deck.cards) <= 3: print("You ran out of cards. Game over.") self.not_done = False @@ -129,4 +125,5 @@ def main() -> None: if __name__ == "__main__": + random.seed() main() diff --git a/25_Chief/rust/Cargo.toml b/25_Chief/rust/Cargo.toml new file mode 100644 index 00000000..1ec69633 --- /dev/null +++ b/25_Chief/rust/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "rust" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/25_Chief/rust/README.md b/25_Chief/rust/README.md new file mode 100644 index 00000000..8bdbf2e2 --- /dev/null +++ b/25_Chief/rust/README.md @@ -0,0 +1,3 @@ +Original source downloaded [from Vintage Basic](http://www.vintage-basic.net/games.html) + +Conversion to [Rust](https://www.rust-lang.org/) by [Jadi](https://github.com/jadijadi) \ No newline at end of file diff --git a/25_Chief/rust/src/main.rs b/25_Chief/rust/src/main.rs new file mode 100644 index 00000000..123f1a67 --- /dev/null +++ b/25_Chief/rust/src/main.rs @@ -0,0 +1,133 @@ +use std::io; + +fn print_center(text: String, width: usize) { + let pad_size: usize = if width > text.len() { + (width - text.len()) / 2 + } else { + 0 + }; + println!("{}{}", " ".repeat(pad_size), text); +} + +fn send_lightening() { + println!( + "YOU HAVE MADE ME MAD!!! +THERE MUST BE A GREAT LIGHTNING BOLT! + + X X + X X + X X + X X + X X + X X + X X + X X + X X + X XXX + X X + XX X + X X + X X + X X + X X + X X + X X + X X + X X + XX + X + * + +######################### + +I HOPE YOU BELIEVE ME NOW, FOR YOUR SAKE!!" + ); +} + +fn check_yes_answer() -> bool { + // reads from input and return true if it starts with Y or y + + let mut answer: String = String::new(); + io::stdin() + .read_line(&mut answer) + .expect("Error reading from stdin"); + + answer.to_uppercase().starts_with('Y') +} + +fn main() { + const PAGE_WIDTH: usize = 64; + print_center("CHIEF".to_string(), PAGE_WIDTH); + print_center( + "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY".to_string(), + PAGE_WIDTH, + ); + println!("\n\n\n"); + + println!("I AM CHIEF NUMBERS FREEK, THE GREAT INDIAN MATH GOD."); + println!("ARE YOU READY TO TAKE THE TEST YOU CALLED ME OUT FOR?"); + + if !check_yes_answer() { + println!("SHUT UP, PALE FACE WITH WISE TONGUE."); + } + + println!("TAKE A NUMBER AND ADD 3. DIVIDE THIS NUMBER BY 5 AND"); + println!("MULTIPLY BY 8. DIVIDE BY 5 AND ADD THE SAME. SUBTRACT 1."); + println!(" WHAT DO YOU HAVE?"); + + // read a float number + let mut answer: String = String::new(); + io::stdin() + .read_line(&mut answer) + .expect("Error reading from stdin"); + let guess: f32 = answer.trim().parse().expect("Input not a number"); + + let calculated_answer: f32 = (guess + 1.0 - 5.0) * 5.0 / 8.0 * 5.0 - 3.0; + + println!("I BET YOUR NUMBER WAS {calculated_answer}. AM I RIGHT?"); + + if check_yes_answer() { + println!("BYE!!!"); + } else { + println!("WHAT WAS YOUR ORIGINAL NUMBER?"); + + // read a float number + let mut answer: String = String::new(); + io::stdin() + .read_line(&mut answer) + .expect("Error reading from stdin"); + let claimed: f32 = answer.trim().parse().expect("Input not a number"); + + println!("SO YOU THINK YOU'RE SO SMART, EH?"); + println!("NOW WATCH."); + println!( + "{claimed} PLUS 3 EQUALS {}. THIS DIVIDED BY 5 EQUALS {};", + claimed + 3.0, + (claimed + 3.0) / 5.0 + ); + println!( + "THIS TIMES 8 EQUALS {}. IF WE DIVIDE BY 5 AND ADD 5,", + (claimed + 3.0) / 5.0 * 8.0 + ); + println!( + "WE GET {} , WHICH, MINUS 1, EQUALS {}.", + ((claimed + 3.0) / 5.0 * 8.0 / 5.0) + 5.0, + ((claimed + 3.0) / 5.0 * 8.0 / 5.0) + 4.0 + ); + println!("NOW DO YOU BELIEVE ME?"); + + if check_yes_answer() { + println!("BYE!!!"); + } else { + send_lightening(); + } + } +} + +//////////////////////////////////////////////////////////////////// +// Porting notes: +// In floating point arithmetics in "modern" languages we might see +// unfamiliar situations such as 6.9999999 instead of 7 and such. +// resolving this needs using specific mathematical libraries which +// IMO is out of scope in these basic programs +/////////////////////////////////////////////////////////////////// diff --git a/40_Gomoko/gomoko.bas b/40_Gomoko/gomoko.bas index 662cca13..d57c10a1 100644 --- a/40_Gomoko/gomoko.bas +++ b/40_Gomoko/gomoko.bas @@ -28,7 +28,7 @@ 440 A(I,J)=1 500 REM *** COMPUTER TRIES AN INTELLIGENT MOVE *** 510 FOR E=-1 TO 1: FOR F=-1 TO 1: IF E+F-E*F=0 THEN 590 -540 X=I+F: Y=J+F: GOSUB 910 +540 X=I+E: Y=J+F: GOSUB 910 570 IF L=0 THEN 590 580 IF A(X,Y)=1 THEN 710 590 NEXT F: NEXT E diff --git a/58_Love/rust/Cargo.toml b/58_Love/rust/Cargo.toml new file mode 100644 index 00000000..1ec69633 --- /dev/null +++ b/58_Love/rust/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "rust" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/58_Love/rust/README.md b/58_Love/rust/README.md new file mode 100644 index 00000000..4cd90430 --- /dev/null +++ b/58_Love/rust/README.md @@ -0,0 +1,3 @@ +Original source downloaded [from Vintage Basic](http://www.vintage-basic.net/games.html) + +Conversion to [Rust](https://www.rust-lang.org/) by Jadi. diff --git a/58_Love/rust/src/main.rs b/58_Love/rust/src/main.rs new file mode 100644 index 00000000..5e8e18d7 --- /dev/null +++ b/58_Love/rust/src/main.rs @@ -0,0 +1,92 @@ +use std::io; + +fn show_intro() { + // Displays the intro text + println!("\n Love"); + println!("Creative Computing Morristown, New Jersey"); + println!("\n\n"); + println!("A tribute to the great American artist, Robert Indiana."); + println!("His great work will be reproduced with a message of"); + println!("your choice up to 60 characters. If you can't think of"); + println!("a message, simple type the word 'love'\n"); // (sic) +} + +fn main() { + enum PrintOrPass { + Print, + Pass, + } + + let data = [ + vec![60], + vec![1, 12, 26, 9, 12], + vec![3, 8, 24, 17, 8], + vec![4, 6, 23, 21, 6], + vec![4, 6, 22, 12, 5, 6, 5], + vec![4, 6, 21, 11, 8, 6, 4], + vec![4, 6, 21, 10, 10, 5, 4], + vec![4, 6, 21, 9, 11, 5, 4], + vec![4, 6, 21, 8, 11, 6, 4], + vec![4, 6, 21, 7, 11, 7, 4], + vec![4, 6, 21, 6, 11, 8, 4], + vec![4, 6, 19, 1, 1, 5, 11, 9, 4], + vec![4, 6, 19, 1, 1, 5, 10, 10, 4], + vec![4, 6, 18, 2, 1, 6, 8, 11, 4], + vec![4, 6, 17, 3, 1, 7, 5, 13, 4], + vec![4, 6, 15, 5, 2, 23, 5], + vec![1, 29, 5, 17, 8], + vec![1, 29, 9, 9, 12], + vec![1, 13, 5, 40, 1], + vec![1, 13, 5, 40, 1], + vec![4, 6, 13, 3, 10, 6, 12, 5, 1], + vec![5, 6, 11, 3, 11, 6, 14, 3, 1], + vec![5, 6, 11, 3, 11, 6, 15, 2, 1], + vec![6, 6, 9, 3, 12, 6, 16, 1, 1], + vec![6, 6, 9, 3, 12, 6, 7, 1, 10], + vec![7, 6, 7, 3, 13, 6, 6, 2, 10], + vec![7, 6, 7, 3, 13, 14, 10], + vec![8, 6, 5, 3, 14, 6, 6, 2, 10], + vec![8, 6, 5, 3, 14, 6, 7, 1, 10], + vec![9, 6, 3, 3, 15, 6, 16, 1, 1], + vec![9, 6, 3, 3, 15, 6, 15, 2, 1], + vec![10, 6, 1, 3, 16, 6, 14, 3, 1], + vec![10, 10, 16, 6, 12, 5, 1], + vec![11, 8, 13, 27, 1], + vec![11, 8, 13, 27, 1], + vec![60], + ]; + + const ROW_LEN: usize = 60; + show_intro(); + + let mut input: String = String::new(); + io::stdin().read_line(&mut input).expect("No valid input"); + let input = if input.len() == 1 { + "LOVE" + } else { + input.trim() + }; + // repeat the answer to fill the whole line, we will show chunks of this when needed + let input = input.repeat(ROW_LEN / (input.len()) + 1); + + // Now lets display the Love + print!("{}", "\n".repeat(9)); + for row in data { + let mut print_or_pass = PrintOrPass::Print; + let mut current_start = 0; + for count in row { + match print_or_pass { + PrintOrPass::Print => { + print!("{}", &input[current_start..count + current_start]); + print_or_pass = PrintOrPass::Pass; + } + PrintOrPass::Pass => { + print!("{}", " ".repeat(count)); + print_or_pass = PrintOrPass::Print; + } + } + current_start += count; + } + println!(); + } +} diff --git a/84_Super_Star_Trek/python/superstartrek.py b/84_Super_Star_Trek/python/superstartrek.py index 2a86efba..805c9d93 100644 --- a/84_Super_Star_Trek/python/superstartrek.py +++ b/84_Super_Star_Trek/python/superstartrek.py @@ -335,7 +335,6 @@ class Game: " THE USS ENTERPRISE --- NCC-1701\n" "\n\n\n\n" ) - self.world = World() world = self.world print( "YOUR ORDERS ARE AS FOLLOWS:\n" diff --git a/85_Synonym/rust/Cargo.toml b/85_Synonym/rust/Cargo.toml new file mode 100644 index 00000000..3b1d02f5 --- /dev/null +++ b/85_Synonym/rust/Cargo.toml @@ -0,0 +1,9 @@ +[package] +name = "rust" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +rand = "0.8.5" diff --git a/85_Synonym/rust/README.md b/85_Synonym/rust/README.md new file mode 100644 index 00000000..4c54b94c --- /dev/null +++ b/85_Synonym/rust/README.md @@ -0,0 +1,3 @@ +Original source downloaded [from Vintage Basic](http://www.vintage-basic.net/games.html) + +Conversion to [Rust](https://www.rust-lang.org/) by [Jadi](https://github.com/jadijadi) diff --git a/85_Synonym/rust/src/main.rs b/85_Synonym/rust/src/main.rs new file mode 100644 index 00000000..184f51bd --- /dev/null +++ b/85_Synonym/rust/src/main.rs @@ -0,0 +1,102 @@ +use rand::seq::SliceRandom; +use rand::thread_rng; +use rand::Rng; +use std::io::{self, Write}; + +fn print_centered(text: &str, width: usize) { + let pad_size: usize = if width > text.len() { + (width - text.len()) / 2 + } else { + 0 + }; + println!("{}{}", " ".repeat(pad_size), text); +} + +fn print_instructions() { + println!("A SYNONYM OF A WORD MEANS ANOTHER WORD IN THE ENGLISH"); + println!("LANGUAGE WHICH HAS THE SAME OR VERY NEARLY THE SAME MEANING."); + println!("I CHOOSE A WORD -- YOU TYPE A SYNONYM."); + println!("IF YOU CAN'T THINK OF A SYNONYM, TYPE THE WORD 'HELP'"); + println!("AND I WILL TELL YOU A SYNONYM.\n"); +} + +fn ask_question(mut this_question: Vec<&str>) { + let right_words = ["RIGHT", "CORRECT", "FINE", "GOOD!", "CHECK"]; + + // use the first one in the main question + let base_word = this_question.remove(0); + + loop { + print!(" WHAT IS A SYNONYM OF {base_word}? "); + io::stdout().flush().unwrap(); + let mut answer: String = String::new(); + io::stdin() + .read_line(&mut answer) + .expect("Failed to read the line"); + let answer = answer.trim(); + if answer == "HELP" { + // remove one random from the answers and show it + let random_index = thread_rng().gen_range(0..this_question.len()); + println!( + "**** A SYNONYM OF {base_word} IS {}.", + this_question.remove(random_index) + ); + } else if this_question.contains(&answer) { + println!("{}", right_words.choose(&mut rand::thread_rng()).unwrap()); + break; + } + } +} + +fn main() { + const PAGE_WIDTH: usize = 64; + + let mut synonyms = vec![ + vec!["FIRST", "START", "BEGINNING", "ONSET", "INITIAL"], + vec!["SIMILAR", "ALIKE", "SAME", "LIKE", "RESEMBLING"], + vec!["MODEL", "PATTERN", "PROTOTYPE", "STANDARD", "CRITERION"], + vec!["SMALL", "INSIGNIFICANT", "LITTLE", "TINY", "MINUTE"], + vec!["STOP", "HALT", "STAY", "ARREST", "CHECK", "STANDSTILL"], + vec![ + "HOUSE", + "DWELLING", + "RESIDENCE", + "DOMICILE", + "LODGING", + "HABITATION", + ], + vec!["PIT", "HOLE", "HOLLOW", "WELL", "GULF", "CHASM", "ABYSS"], + vec!["PUSH", "SHOVE", "THRUST", "PROD", "POKE", "BUTT", "PRESS"], + vec!["RED", "ROUGE", "SCARLET", "CRIMSON", "FLAME", "RUBY"], + vec![ + "PAIN", + "SUFFERING", + "HURT", + "MISERY", + "DISTRESS", + "ACHE", + "DISCOMFORT", + ], + ]; + + synonyms.shuffle(&mut thread_rng()); + + print_centered("SYNONYM", PAGE_WIDTH); + print_centered("CREATIVE COMPUTING MORRISTOWN, NEW JERSEY", PAGE_WIDTH); + println!("\n\n\n"); + + print_instructions(); + + for this_question in synonyms { + ask_question(this_question) + } + println!("SYNONYM DRILL COMPLETED."); +} + +//////////////////////////////////////////////////////////// +// Poring Notes +// Poring Note: The "HELP" function .removes a variable +// from lists and shows it. This can lead to errors when +// the list becomes empty. But since the same issue happens +// on the original BASIC program, kept it intact +////////////////////////////////////////////////////////////