diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index f3827f657..b1e000fa1 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -4,7 +4,6 @@ repos: rev: v4.1.0 hooks: - id: check-ast - - id: check-byte-order-marker - id: check-case-conflict - id: check-docstring-first - id: check-executables-have-shebangs diff --git a/00_Utilities/DotnetUtils/.editorconfig b/00_Utilities/DotnetUtils/.editorconfig index 9e7a90d56..f48cda0a2 100644 --- a/00_Utilities/DotnetUtils/.editorconfig +++ b/00_Utilities/DotnetUtils/.editorconfig @@ -65,11 +65,11 @@ dotnet_naming_rule.private_members_should_be_pascal_case.style = camel_case dotnet_naming_symbols.interface.applicable_kinds = interface dotnet_naming_symbols.interface.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected -dotnet_naming_symbols.interface.required_modifiers = +dotnet_naming_symbols.interface.required_modifiers = dotnet_naming_symbols.types.applicable_kinds = class, struct, interface, enum, delegate dotnet_naming_symbols.types.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected -dotnet_naming_symbols.types.required_modifiers = +dotnet_naming_symbols.types.required_modifiers = dotnet_naming_symbols.non_private_members.applicable_kinds = property, method, field, event dotnet_naming_symbols.non_private_members.applicable_accessibilities = public, internal, protected, protected_internal, private_protected @@ -80,19 +80,19 @@ dotnet_naming_symbols.private_members.applicable_accessibilities = private # Naming styles -dotnet_naming_style.pascal_case.required_prefix = -dotnet_naming_style.pascal_case.required_suffix = -dotnet_naming_style.pascal_case.word_separator = +dotnet_naming_style.pascal_case.required_prefix = +dotnet_naming_style.pascal_case.required_suffix = +dotnet_naming_style.pascal_case.word_separator = dotnet_naming_style.pascal_case.capitalization = pascal_case dotnet_naming_style.begins_with_i.required_prefix = I -dotnet_naming_style.begins_with_i.required_suffix = -dotnet_naming_style.begins_with_i.word_separator = +dotnet_naming_style.begins_with_i.required_suffix = +dotnet_naming_style.begins_with_i.word_separator = dotnet_naming_style.begins_with_i.capitalization = pascal_case -dotnet_naming_style.camel_case.required_prefix = -dotnet_naming_style.camel_case.required_suffix = -dotnet_naming_style.camel_case.word_separator = +dotnet_naming_style.camel_case.required_prefix = +dotnet_naming_style.camel_case.required_suffix = +dotnet_naming_style.camel_case.word_separator = dotnet_naming_style.camel_case.capitalization = camel_case diff --git a/00_Utilities/DotnetUtils/DotnetUtils/PortInfo.cs b/00_Utilities/DotnetUtils/DotnetUtils/PortInfo.cs index 535c0ca02..c7a96147c 100644 --- a/00_Utilities/DotnetUtils/DotnetUtils/PortInfo.cs +++ b/00_Utilities/DotnetUtils/DotnetUtils/PortInfo.cs @@ -9,7 +9,7 @@ public record PortInfo( string LangPath, string Lang, string Ext, string ProjExt, string[] CodeFiles, string[] Slns, string[] Projs ) { - + private static readonly EnumerationOptions enumerationOptions = new() { RecurseSubdirectories = true, MatchType = MatchType.Simple, @@ -34,7 +34,7 @@ public record PortInfo( int.TryParse(parts[0], out var n) && n > 0 ? // ignore utilities folder n : (int?)null, - specialGameNames.TryGetValue(parts[1], out var specialName) ? + specialGameNames.TryGetValue(parts[1], out var specialName) ? specialName : parts[1].Replace("_", "").Replace("-", "") ); diff --git a/00_Utilities/DotnetUtils/DotnetUtils/Program.cs b/00_Utilities/DotnetUtils/DotnetUtils/Program.cs index 6e51d4f19..a9f5cac1d 100644 --- a/00_Utilities/DotnetUtils/DotnetUtils/Program.cs +++ b/00_Utilities/DotnetUtils/DotnetUtils/Program.cs @@ -180,7 +180,7 @@ void generateMissingSlns() { void generateMissingProjs() { foreach (var item in infos.Where(x => x.Projs.None())) { // We can't use the dotnet command to create a new project using the built-in console template, because part of that template - // is a Program.cs / Program.vb file. If there already are code files, there's no need to add a new empty one; and + // is a Program.cs / Program.vb file. If there already are code files, there's no need to add a new empty one; and // if there's already such a file, it might try to overwrite it. var projText = item.Lang switch { diff --git a/00_Utilities/bas2perl.pl b/00_Utilities/bas2perl.pl index 791d1b349..8ad136e37 100755 --- a/00_Utilities/bas2perl.pl +++ b/00_Utilities/bas2perl.pl @@ -8,7 +8,7 @@ my $Pedantic= 0; my $Indent= 0; -my %Vars; # num | str | anm | ast +my %Vars; # num | str | anm | ast my @Data; my %Code; open(FH, $File); @@ -278,7 +278,7 @@ sub PRINT { push @Out, $Par; } - my $Out= join(". ", @Out); + my $Out= join(". ", @Out); if ($Enter) { $Out.= qq|. "\\n"|; } return "print ".$Out; } @@ -347,7 +347,7 @@ sub FORMULA { if ($Vars{$Key}!~ /^a/) { next; } $Str=~ s/\$$Key\((.*?)\)/\$$Key\[$1\]/g; } - + if ($Cond==1) { $Str=~ s/<>/ ne /g; $Str=~ s/=/ eq /g; @@ -357,7 +357,7 @@ sub FORMULA { sub SMARPLIT { - my ($Str, $Sep, $Nin)= @_; + my ($Str, $Sep, $Nin)= @_; my @Parts; my $Text= ""; my $Flag= 0; @@ -373,8 +373,5 @@ sub SMARPLIT { $Text.= $Char; } if ($Text) { push @Parts, &TRIM($Text); } - return @Parts; + return @Parts; } - - - diff --git a/00_Utilities/find-unimplemented.js b/00_Utilities/find-unimplemented.js index 41641f528..e048d9ce2 100644 --- a/00_Utilities/find-unimplemented.js +++ b/00_Utilities/find-unimplemented.js @@ -1,9 +1,9 @@ /** - * Program to show unimplemented games by language, optionally filtered by + * Program to show unimplemented games by language, optionally filtered by * language - * + * * Usage: node find-unimplemented.js [[[lang1] lang2] ...] - * + * * Adapted from find-missing-implementtion.js */ diff --git a/00_Utilities/jvmTestUtils/kotlin/test/ConsoleTest.kt b/00_Utilities/jvmTestUtils/kotlin/test/ConsoleTest.kt index d58af1706..eba584d96 100644 --- a/00_Utilities/jvmTestUtils/kotlin/test/ConsoleTest.kt +++ b/00_Utilities/jvmTestUtils/kotlin/test/ConsoleTest.kt @@ -34,4 +34,4 @@ abstract class ConsoleTest { private fun String.trimWhiteSpace() = replace("[\\s]+".toRegex(), " ") -} \ No newline at end of file +} diff --git a/00_Utilities/yatol.pl b/00_Utilities/yatol.pl index 89bfbaef5..11825a65d 100755 --- a/00_Utilities/yatol.pl +++ b/00_Utilities/yatol.pl @@ -19,7 +19,7 @@ foreach my $Dir (@Langs) { printf("%$Tab\s", $Dir); - } + } print "\n"; my $Count; @@ -39,7 +39,7 @@ if ($Ret>1) { printf("%$Tab\s", "YES"); $Sum{$Dir}++; } else { printf("%$Tab\s", " ");} } - print "\n"; + print "\n"; } @@ -57,4 +57,3 @@ printf("%$Tab\s", "$Per"); } print "\n"; - diff --git a/01_Acey_Ducey/csharp/GameState.cs b/01_Acey_Ducey/csharp/GameState.cs index 5f8ccbcf8..0a4c587d7 100644 --- a/01_Acey_Ducey/csharp/GameState.cs +++ b/01_Acey_Ducey/csharp/GameState.cs @@ -9,7 +9,7 @@ namespace AceyDucey /// internal class GameState { - + /// /// How much money does the player have at the moment? /// diff --git a/01_Acey_Ducey/d/aceyducey.d b/01_Acey_Ducey/d/aceyducey.d index 036786c56..a2c6ba3f8 100644 --- a/01_Acey_Ducey/d/aceyducey.d +++ b/01_Acey_Ducey/d/aceyducey.d @@ -55,7 +55,7 @@ void main() { writeln("YOU WIN!!!"); cash += bet; - } + } else { writeln("Sorry, you lose."); diff --git a/01_Acey_Ducey/java/src/AceyDucey.java b/01_Acey_Ducey/java/src/AceyDucey.java index d53c0d050..d0cccb0a9 100644 --- a/01_Acey_Ducey/java/src/AceyDucey.java +++ b/01_Acey_Ducey/java/src/AceyDucey.java @@ -169,4 +169,4 @@ public void intro() { System.out.println("A VALUE BETWEEN THE FIRST TWO."); System.out.println("IF YOU DO NOT WANT TO BET, INPUT: 0"); } -} \ No newline at end of file +} diff --git a/01_Acey_Ducey/java/src/AceyDucey17.java b/01_Acey_Ducey/java/src/AceyDucey17.java index 6192fc14a..bb62fdafe 100644 --- a/01_Acey_Ducey/java/src/AceyDucey17.java +++ b/01_Acey_Ducey/java/src/AceyDucey17.java @@ -15,8 +15,8 @@ public static void main(String[] args) { System.out.println(""" ACEY DUCEY CARD GAME CREATIVE COMPUTING MORRISTOWN, NEW JERSEY - - + + 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 diff --git a/01_Acey_Ducey/java/src/AceyDuceyGame.java b/01_Acey_Ducey/java/src/AceyDuceyGame.java index 1ce08c284..787c92e67 100644 --- a/01_Acey_Ducey/java/src/AceyDuceyGame.java +++ b/01_Acey_Ducey/java/src/AceyDuceyGame.java @@ -18,4 +18,4 @@ public static void main(String[] args) { keepPlaying = game.playAgain(); } while (keepPlaying); } -} \ No newline at end of file +} diff --git a/01_Acey_Ducey/javascript/aceyducey.js b/01_Acey_Ducey/javascript/aceyducey.js index 9969ebbf5..89838f0a6 100644 --- a/01_Acey_Ducey/javascript/aceyducey.js +++ b/01_Acey_Ducey/javascript/aceyducey.js @@ -99,7 +99,7 @@ async function main() { } } } - if (bet == 0) + if (bet == 0) { // User chose not to bet. print('CHICKEN!!'); diff --git a/01_Acey_Ducey/pascal/object-pascal/aceyducey.pas b/01_Acey_Ducey/pascal/object-pascal/aceyducey.pas index 9e72952b6..a57df2cf0 100644 --- a/01_Acey_Ducey/pascal/object-pascal/aceyducey.pas +++ b/01_Acey_Ducey/pascal/object-pascal/aceyducey.pas @@ -16,4 +16,3 @@ Acey_Ducey:= TGame.Create; Acey_Ducey.Run; end. - diff --git a/01_Acey_Ducey/pascal/object-pascal/deck.pas b/01_Acey_Ducey/pascal/object-pascal/deck.pas index d5940fe28..c2f603c86 100644 --- a/01_Acey_Ducey/pascal/object-pascal/deck.pas +++ b/01_Acey_Ducey/pascal/object-pascal/deck.pas @@ -108,4 +108,3 @@ function TDeck.PlayerWins: Boolean; end; end. - diff --git a/01_Acey_Ducey/pascal/object-pascal/game.pas b/01_Acey_Ducey/pascal/object-pascal/game.pas index 1e983f7c0..e49615419 100644 --- a/01_Acey_Ducey/pascal/object-pascal/game.pas +++ b/01_Acey_Ducey/pascal/object-pascal/game.pas @@ -133,4 +133,3 @@ procedure TGame.Run; end; end. - diff --git a/01_Acey_Ducey/pascal/simple/aceyducey.pas b/01_Acey_Ducey/pascal/simple/aceyducey.pas index fa049eb0a..3fad87bf7 100644 --- a/01_Acey_Ducey/pascal/simple/aceyducey.pas +++ b/01_Acey_Ducey/pascal/simple/aceyducey.pas @@ -149,4 +149,3 @@ function TryAgain: Boolean; until not TryAgain; WriteLN('O.K., HOPE YOU HAD FUN!'); end. - diff --git a/01_Acey_Ducey/python/acey_ducey_oo.py b/01_Acey_Ducey/python/acey_ducey_oo.py index 3e05387f8..d7bed6059 100644 --- a/01_Acey_Ducey/python/acey_ducey_oo.py +++ b/01_Acey_Ducey/python/acey_ducey_oo.py @@ -11,6 +11,7 @@ # ###################################################### + class Card: def __init__(self, suit, rank): self.suit = suit @@ -19,14 +20,14 @@ def __init__(self, suit, rank): def __str__(self): r = self.rank if r == 11: - r = 'J' + r = "J" elif r == 12: - r = 'Q' + r = "Q" elif r == 13: - r = 'K' + r = "K" elif r == 14: - r = 'A' - return f'{r}{self.suit}' + r = "A" + return f"{r}{self.suit}" class Deck: @@ -35,12 +36,13 @@ def __init__(self): self.build() def build(self): - for suit in ['\u2665', '\u2666', '\u2663', '\u2660']: + for suit in ["\u2665", "\u2666", "\u2663", "\u2660"]: for rank in range(2, 15): self.cards.append(Card(suit, rank)) def shuffle(self): import random + random.shuffle(self.cards) def deal(self): @@ -69,34 +71,34 @@ def play(self): self.card_b = self.deck.deal() card_b = self.card_b - print(f'You have:\t ${self.money} ') - print(f'Your cards:\t {card_a} {card_b}') + print(f"You have:\t ${self.money} ") + print(f"Your cards:\t {card_a} {card_b}") - bet = int(input('What is your bet? ')) + bet = int(input("What is your bet? ")) player_card = self.deck.deal() if 0 < bet <= self.money: - print(f'Your deal:\t {player_card}') + print(f"Your deal:\t {player_card}") if card_a.rank < player_card.rank < card_b.rank: - print('You Win!') + print("You Win!") self.money += bet else: - print('You Lose!') + print("You Lose!") self.money -= bet self.not_done = False else: - print('Chicken!') - print(f'Your deal should have been: {player_card}') + print("Chicken!") + print(f"Your deal should have been: {player_card}") if card_a.rank < player_card.rank < card_b.rank: - print(f'You could have won!') + print(f"You could have won!") else: - print(f'You would lose, so it was wise of you to chicken out!') + print(f"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.') + print("You ran out of cards. Game over.") self.not_done = False break @@ -107,22 +109,24 @@ def play(self): self.not_done = False -if __name__ == '__main__': - print(''' +if __name__ == "__main__": + print( + """ Acey Ducey is a card game where you play against the computer. The Dealer(computer) will deal two cards facing up. - You have an option to bet or not bet depending on whether or not you + 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 - ''') + """ + ) GAME_OVER = False while not GAME_OVER: game = Game() game.play() - print(f'You have ${game.money} left') - print('Would you like to play again? (y/n)') - if input() == 'n': + print(f"You have ${game.money} left") + print("Would you like to play again? (y/n)") + if input() == "n": GAME_OVER = True - print('\nThanks for playing!') + print("\nThanks for playing!") diff --git a/01_Acey_Ducey/vbnet/AceyDucey.vb b/01_Acey_Ducey/vbnet/AceyDucey.vb index 8727e6b22..528d92750 100644 --- a/01_Acey_Ducey/vbnet/AceyDucey.vb +++ b/01_Acey_Ducey/vbnet/AceyDucey.vb @@ -1,7 +1,7 @@ Public Class AceyDucey ''' - ''' Create a single instance of the Random class to be used - ''' throughout the program. + ''' Create a single instance of the Random class to be used + ''' throughout the program. ''' Private ReadOnly Property Rnd As New Random() @@ -10,7 +10,7 @@ ''' Defaults to 0 ''' ''' - ''' Since is a value type, and no value + ''' Since is a value type, and no value ''' has been explicitly set, the default value of the type is used. ''' Private _balance As Integer @@ -51,7 +51,7 @@ ''' Play one turn of Acey Ducey ''' ''' - ''' A turn consists of displaying to cards, making a wager + ''' A turn consists of displaying to cards, making a wager ''' and determining the result (win/lose) ''' Private Sub PlayTurn() @@ -80,11 +80,11 @@ ''' '''The use of AndAlso is used to short-circuit the evaluation of the IF condition. '''Short-circuiting means that both sides of the condition do not need to be - '''evaluated. In this case, if the left criteria returns FALSE, the right criteria + '''evaluated. In this case, if the left criteria returns FALSE, the right criteria '''is ignored and the evaluation result is returned as FALSE. ''' - '''This works because AndAlso requires both condition to return TRUE in order to be - '''evaluated as TRUE. If the first condition is FALSE we already know the evaluation result. + '''This works because AndAlso requires both condition to return TRUE in order to be + '''evaluated as TRUE. If the first condition is FALSE we already know the evaluation result. If finalCard >= cards.First() AndAlso finalCard <= cards.Last() Then Console.WriteLine("YOU WIN!!!") _balance += wager 'Condensed version of _balance = _balance + wager @@ -99,14 +99,14 @@ ''' ''' ''' The original version generates two cards (A and B) - ''' If A is greater than or equal to B, both cards are regenerated. - '''

- ''' This version generates the two cards, but only regenerates A + ''' If A is greater than or equal to B, both cards are regenerated. + '''

+ ''' This version generates the two cards, but only regenerates A ''' if A is equal to B. The cards are then returned is ascending order, ''' ensuring that A is less than B (maintaining the original end result) '''
Private Function GetOrderedCards() As Integer() - '''When declaring fixed size arrays in VB.NET you declare the MAX INDEX of the array + '''When declaring fixed size arrays in VB.NET you declare the MAX INDEX of the array '''and NOT the SIZE (number of elements) of the array. '''As such, card(1) gives you and array with index 0 and index 1, which means '''the array stores two elements and not one @@ -133,7 +133,7 @@ End Function ''' - ''' Display the face value of the card + ''' Display the face value of the card ''' Private Sub DisplayCard(card As Integer) Dim output As String @@ -221,7 +221,7 @@ ''' Display the opening title and instructions ''' ''' - ''' Refer to + ''' Refer to ''' ''' Interpolated Strings ''' documentation for the use of $ and { } with strings diff --git a/01_Acey_Ducey/vbnet/Program.vb b/01_Acey_Ducey/vbnet/Program.vb index 2f82fd603..3275187c5 100644 --- a/01_Acey_Ducey/vbnet/Program.vb +++ b/01_Acey_Ducey/vbnet/Program.vb @@ -2,16 +2,16 @@ Imports System ''' ''' This is a modern adapation of Acey Ducey from BASIC Computer Games. -''' +''' ''' The structural changes primarily consist of replacing the many GOTOs with ''' Do/Loop constructs to force the continual execution of the program. -''' -''' Some modern improvements were added, primarily the inclusion of a multiple -''' subroutines and functions, which eliminates repeated logic and reduces -''' then need for nested loops. -''' +''' +''' Some modern improvements were added, primarily the inclusion of a multiple +''' subroutines and functions, which eliminates repeated logic and reduces +''' then need for nested loops. +''' ''' The archaic RND function is greatly simplified with the .NET Framework's Random class. -''' +''' ''' Elementary comments are provided for non-programmers or novices. ''' Module Program diff --git a/02_Amazing/csharp/Amazing.cs b/02_Amazing/csharp/Amazing.cs index 995b58d68..c556901b9 100644 --- a/02_Amazing/csharp/Amazing.cs +++ b/02_Amazing/csharp/Amazing.cs @@ -1,8 +1,8 @@ -using System; -using System.Collections.Generic; - -namespace Amazing -{ +using System; +using System.Collections.Generic; + +namespace Amazing +{ class AmazingGame { private const int FIRST_COL = 0; @@ -35,9 +35,9 @@ public static int Random(int min, int max) } public void Play() - { - Console.WriteLine(Tab(28) + "AMAZING PROGRAM"); - Console.WriteLine(Tab(15) + "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY"); + { + Console.WriteLine(Tab(28) + "AMAZING PROGRAM"); + Console.WriteLine(Tab(15) + "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY"); Console.WriteLine(); int width = 0; @@ -113,25 +113,25 @@ private void WriteMaze(int width, Grid grid, int enterCol) { if (i == enterCol) Console.Write(". "); else Console.Write(".--"); - } - Console.WriteLine("."); + } + Console.WriteLine("."); for (int i = 0; i < grid.Length; i++) - { + { Console.Write("I"); for (int j = 0; j < grid.Width; j++) { if (grid.Cells[i,j].ExitType == EXIT_UNSET || grid.Cells[i, j].ExitType == EXIT_DOWN) Console.Write(" I"); else Console.Write(" "); - } - Console.WriteLine(); + } + Console.WriteLine(); for (int j = 0; j < grid.Width; j++) { if (grid.Cells[i,j].ExitType == EXIT_UNSET || grid.Cells[i, j].ExitType == EXIT_RIGHT) Console.Write(":--"); else Console.Write(": "); - } + } Console.WriteLine("."); } } @@ -164,7 +164,7 @@ private List GetPossibleDirs(Grid grid, Cell cell) } private String DisplayTextAndGetInput(String text) - { + { Console.WriteLine(text); return Console.ReadLine(); } @@ -308,13 +308,13 @@ public Cell GetFirstUnset(Cell cell) return newCell; } } - } - - class Program - { - static void Main(string[] args) + } + + class Program + { + static void Main(string[] args) { - new AmazingGame().Play(); - } - } -} + new AmazingGame().Play(); + } + } +} diff --git a/02_Amazing/java/Amazing.java b/02_Amazing/java/Amazing.java index 5188f14f5..c5963715d 100644 --- a/02_Amazing/java/Amazing.java +++ b/02_Amazing/java/Amazing.java @@ -259,4 +259,4 @@ public Cell getFirstUnset(Cell cell) { return newCell; } } -} \ No newline at end of file +} diff --git a/02_Amazing/javascript/amazing.js b/02_Amazing/javascript/amazing.js index 427e07935..ee06816ee 100644 --- a/02_Amazing/javascript/amazing.js +++ b/02_Amazing/javascript/amazing.js @@ -12,10 +12,10 @@ function input() { var input_element; var input_str; - + return new Promise(function (resolve) { input_element = document.createElement("INPUT"); - + print("? "); input_element.setAttribute("type", "text"); input_element.setAttribute("length", "50"); diff --git a/02_Amazing/pascal/object-pascal/amazing.pas b/02_Amazing/pascal/object-pascal/amazing.pas index 716bd1da3..1833076c6 100644 --- a/02_Amazing/pascal/object-pascal/amazing.pas +++ b/02_Amazing/pascal/object-pascal/amazing.pas @@ -14,4 +14,3 @@ AmazingApp:= TAmazingApplication.Create; AmazingApp.Run; end. - diff --git a/02_Amazing/pascal/object-pascal/amazingapplication.pas b/02_Amazing/pascal/object-pascal/amazingapplication.pas index 1431fd67b..4dc791bf8 100644 --- a/02_Amazing/pascal/object-pascal/amazingapplication.pas +++ b/02_Amazing/pascal/object-pascal/amazingapplication.pas @@ -101,4 +101,3 @@ procedure TAmazingApplication.Run; end; end. - diff --git a/02_Amazing/pascal/object-pascal/maze.pas b/02_Amazing/pascal/object-pascal/maze.pas index 1f5b32474..e4355c49c 100644 --- a/02_Amazing/pascal/object-pascal/maze.pas +++ b/02_Amazing/pascal/object-pascal/maze.pas @@ -277,4 +277,3 @@ procedure TMaze.Print; end; end. - diff --git a/02_Amazing/pascal/object-pascal/room.pas b/02_Amazing/pascal/object-pascal/room.pas index f0b741032..201f40937 100644 --- a/02_Amazing/pascal/object-pascal/room.pas +++ b/02_Amazing/pascal/object-pascal/room.pas @@ -68,4 +68,3 @@ procedure TRoom.PrintWall; end; end. - diff --git a/02_Amazing/pascal/simple/amazing.pas b/02_Amazing/pascal/simple/amazing.pas index dc5d7610b..285fafa1e 100644 --- a/02_Amazing/pascal/simple/amazing.pas +++ b/02_Amazing/pascal/simple/amazing.pas @@ -281,4 +281,3 @@ procedure PrintMaze; //DebugWalls; PrintMaze; end. - diff --git a/02_Amazing/perl/amazing.pl b/02_Amazing/perl/amazing.pl index c7cb5f44e..70b1c2321 100755 --- a/02_Amazing/perl/amazing.pl +++ b/02_Amazing/perl/amazing.pl @@ -79,7 +79,7 @@ sub input_dimensions { print 'WHAT ARE YOUR WIDTH AND LENGTH? '; ($w, $h) = =~ / \d+ /xg; - + if ($w < 1 || $h < 1) { say "MEANINGLESS DIMENSIONS. TRY AGAIN." } diff --git a/02_Amazing/python/amazing.py b/02_Amazing/python/amazing.py index dc9da3806..56123c714 100644 --- a/02_Amazing/python/amazing.py +++ b/02_Amazing/python/amazing.py @@ -1,20 +1,20 @@ import random - + # Python translation by Frank Palazzolo - 2/2021 - -print(' '*28+'AMAZING PROGRAM') -print(' '*15+'CREATIVE COMPUTING MORRISTOWN, NEW JERSEY') + +print(" " * 28 + "AMAZING PROGRAM") +print(" " * 15 + "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY") print() print() print() while True: - width, length = input('What are your width and length?').split(',') + width, length = input("What are your width and length?").split(",") width = int(width) length = int(length) if width != 1 and length != 1: break - print('Meaningless dimensions. Try again.') + print("Meaningless dimensions. Try again.") # Build two 2D arrays # @@ -32,90 +32,87 @@ used = [] walls = [] for i in range(length): - used.append([0]*width) - walls.append([0]*width) + used.append([0] * width) + walls.append([0] * width) # Use direction variables with nice names -GO_LEFT,GO_UP,GO_RIGHT,GO_DOWN=[0,1,2,3] +GO_LEFT, GO_UP, GO_RIGHT, GO_DOWN = [0, 1, 2, 3] # Give Exit directions nice names EXIT_DOWN = 1 EXIT_RIGHT = 2 # Pick a random entrance, mark as used -enter_col=random.randint(0,width-1) -row,col=0,enter_col -count=1 -used[row][col]=count -count=count+1 +enter_col = random.randint(0, width - 1) +row, col = 0, enter_col +count = 1 +used[row][col] = count +count = count + 1 -while count!=width*length+1: +while count != width * length + 1: # remove possible directions that are blocked or # hit cells that we have already processed - possible_dirs = [GO_LEFT,GO_UP,GO_RIGHT,GO_DOWN] - if col==0 or used[row][col-1]!=0: + possible_dirs = [GO_LEFT, GO_UP, GO_RIGHT, GO_DOWN] + if col == 0 or used[row][col - 1] != 0: possible_dirs.remove(GO_LEFT) - if row==0 or used[row-1][col]!=0: + if row == 0 or used[row - 1][col] != 0: possible_dirs.remove(GO_UP) - if col==width-1 or used[row][col+1]!=0: + if col == width - 1 or used[row][col + 1] != 0: possible_dirs.remove(GO_RIGHT) - if row==length-1 or used[row+1][col]!=0: - possible_dirs.remove(GO_DOWN) + if row == length - 1 or used[row + 1][col] != 0: + possible_dirs.remove(GO_DOWN) # If we can move in a direction, move and make opening - if len(possible_dirs)!=0: - direction=random.choice(possible_dirs) - if direction==GO_LEFT: - col=col-1 - walls[row][col]=EXIT_RIGHT - elif direction==GO_UP: - row=row-1 - walls[row][col]=EXIT_DOWN - elif direction==GO_RIGHT: - walls[row][col]=walls[row][col]+EXIT_RIGHT - col=col+1 - elif direction==GO_DOWN: - walls[row][col]=walls[row][col]+EXIT_DOWN - row=row+1 - used[row][col]=count - count=count+1 + if len(possible_dirs) != 0: + direction = random.choice(possible_dirs) + if direction == GO_LEFT: + col = col - 1 + walls[row][col] = EXIT_RIGHT + elif direction == GO_UP: + row = row - 1 + walls[row][col] = EXIT_DOWN + elif direction == GO_RIGHT: + walls[row][col] = walls[row][col] + EXIT_RIGHT + col = col + 1 + elif direction == GO_DOWN: + walls[row][col] = walls[row][col] + EXIT_DOWN + row = row + 1 + used[row][col] = count + count = count + 1 # otherwise, move to the next used cell, and try again else: while True: - if col!=width-1: - col=col+1 - elif row!=length-1: - row,col=row+1,0 + if col != width - 1: + col = col + 1 + elif row != length - 1: + row, col = row + 1, 0 else: - row,col=0,0 - if used[row][col]!=0: + row, col = 0, 0 + if used[row][col] != 0: break # Add a random exit -col=random.randint(0,width-1) -row=length-1 -walls[row][col]=walls[row][col]+1 - +col = random.randint(0, width - 1) +row = length - 1 +walls[row][col] = walls[row][col] + 1 + # Print the maze for col in range(width): - if col==enter_col: - print('. ',end='') + if col == enter_col: + print(". ", end="") else: - print('.--',end='') -print('.') + print(".--", end="") +print(".") for row in range(length): - print('I',end='') + print("I", end="") for col in range(width): - if walls[row][col]<2: - print(' I',end='') + if walls[row][col] < 2: + print(" I", end="") else: - print(' ',end='') + print(" ", end="") print() for col in range(width): - if walls[row][col]==0 or walls[row][col]==2: - print(':--',end='') + if walls[row][col] == 0 or walls[row][col] == 2: + print(":--", end="") else: - print(': ',end='') - print('.') - - - \ No newline at end of file + print(": ", end="") + print(".") diff --git a/02_Amazing/ruby/amazing.rb b/02_Amazing/ruby/amazing.rb index d9a4f9d09..e8325bbc2 100644 --- a/02_Amazing/ruby/amazing.rb +++ b/02_Amazing/ruby/amazing.rb @@ -213,4 +213,4 @@ def ask_dimensions end end -Amazing.new.run \ No newline at end of file +Amazing.new.run diff --git a/02_Amazing/vbnet/program.vb b/02_Amazing/vbnet/program.vb index d39eb4508..0983c5b28 100644 --- a/02_Amazing/vbnet/program.vb +++ b/02_Amazing/vbnet/program.vb @@ -145,7 +145,7 @@ Module Program Return SelectRandomDirection(Directions.Up, Directions.Down) ElseIf SolutionCompleted Then 'We're on the bottom row, can only go up Return GoUp() - Else 'We're on the bottom row, can only go up, but there's no solution + Else 'We're on the bottom row, can only go up, but there's no solution Return SelectRandomDirection(Directions.Up, Directions.SolveAndReset) End If '== Definitely can go Up and Right == diff --git a/03_Animal/csharp/Branch.cs b/03_Animal/csharp/Branch.cs index 52c130372..ca7b66c57 100644 --- a/03_Animal/csharp/Branch.cs +++ b/03_Animal/csharp/Branch.cs @@ -15,4 +15,4 @@ public override string ToString() return $"{Text} : IsEnd {IsEnd}"; } } -} \ No newline at end of file +} diff --git a/03_Animal/java/src/Animal.java b/03_Animal/java/src/Animal.java index 1e4895592..0a3875430 100644 --- a/03_Animal/java/src/Animal.java +++ b/03_Animal/java/src/Animal.java @@ -244,4 +244,3 @@ public String toString() { } } - diff --git a/03_Animal/java/test/AnimalJavaTest.kt b/03_Animal/java/test/AnimalJavaTest.kt index 013655a35..0327a1d61 100644 --- a/03_Animal/java/test/AnimalJavaTest.kt +++ b/03_Animal/java/test/AnimalJavaTest.kt @@ -28,16 +28,16 @@ class AnimalJavaTest : ConsoleTest() { DOES IT SWIM ? {NO} IS IT A BIRD ? {NO} THE ANIMAL YOU WERE THINKING OF WAS A ? {COW} - PLEASE TYPE IN A QUESTION THAT WOULD DISTINGUISH A + PLEASE TYPE IN A QUESTION THAT WOULD DISTINGUISH A COW FROM A BIRD ? {DOES IT EAT GRASS} FOR A COW THE ANSWER WOULD BE ? {YES} ARE YOU THINKING OF AN ANIMAL ? {YES} DOES IT SWIM ? {NO} - DOES IT EAT GRASS ? {YES} + DOES IT EAT GRASS ? {YES} IS IT A COW ? {YES} WHY NOT TRY ANOTHER ANIMAL? - ARE YOU THINKING OF AN ANIMAL ? {QUIT} + ARE YOU THINKING OF AN ANIMAL ? {QUIT} """ ) { Animal.main(emptyArray()) @@ -47,9 +47,8 @@ class AnimalJavaTest : ConsoleTest() { private val title = """ ANIMAL CREATIVE COMPUTING MORRISTOWN, NEW JERSEY - + PLAY 'GUESS THE ANIMAL' THINK OF AN ANIMAL AND THE COMPUTER WILL TRY TO GUESS IT. """ } - diff --git a/03_Animal/javascript/animal.js b/03_Animal/javascript/animal.js index a9deae8cd..ed539d27c 100644 --- a/03_Animal/javascript/animal.js +++ b/03_Animal/javascript/animal.js @@ -12,10 +12,10 @@ function input() { var input_element; var input_str; - + return new Promise(function (resolve) { input_element = document.createElement("INPUT"); - + print("? "); input_element.setAttribute("type", "text"); input_element.setAttribute("length", "50"); @@ -70,7 +70,7 @@ n = animals.length; function show_animals() { var x; - + print("\n"); print("ANIMALS I ALREADY KNOW ARE:\n"); str = ""; @@ -108,7 +108,7 @@ async function main() if (str[0] == "Y") break; } - + k = 0; do { // Subroutine to print questions @@ -119,7 +119,7 @@ async function main() if (q[z] == "\\") break; str += q[z]; - } + } print(str); c = await input(); if (c[0] == "Y" || c[0] == "N") @@ -127,9 +127,9 @@ async function main() } t = "\\" + c[0]; x = q.indexOf(t); - k = parseInt(q.substr(x + 2)); + k = parseInt(q.substr(x + 2)); } while (animals[k].substr(0,2) == "\\Q") ; - + print("IS IT A " + animals[k].substr(2)); a = await input(); if (a[0] == "Y") { diff --git a/03_Animal/kotlin/test/AnimalKtTest.kt b/03_Animal/kotlin/test/AnimalKtTest.kt index e93857ea4..354efad6a 100644 --- a/03_Animal/kotlin/test/AnimalKtTest.kt +++ b/03_Animal/kotlin/test/AnimalKtTest.kt @@ -28,16 +28,16 @@ class AnimalKtTest : ConsoleTest() { DOES IT SWIM? {NO} IS IT A BIRD? {NO} THE ANIMAL YOU WERE THINKING OF WAS A? {COW} - PLEASE TYPE IN A QUESTION THAT WOULD DISTINGUISH A + PLEASE TYPE IN A QUESTION THAT WOULD DISTINGUISH A COW FROM A BIRD ? {DOES IT EAT GRASS} FOR A COW THE ANSWER WOULD BE? {YES} ARE YOU THINKING OF AN ANIMAL? {YES} DOES IT SWIM? {NO} - DOES IT EAT GRASS? {YES} + DOES IT EAT GRASS? {YES} IS IT A COW? {YES} WHY NOT TRY ANOTHER ANIMAL? - ARE YOU THINKING OF AN ANIMAL? {QUIT} + ARE YOU THINKING OF AN ANIMAL? {QUIT} """ ) { main() @@ -47,9 +47,8 @@ class AnimalKtTest : ConsoleTest() { private val title = """ ANIMAL CREATIVE COMPUTING MORRISTOWN, NEW JERSEY - + PLAY 'GUESS THE ANIMAL' THINK OF AN ANIMAL AND THE COMPUTER WILL TRY TO GUESS IT. """ } - diff --git a/03_Animal/python/animal.py b/03_Animal/python/animal.py index 65263917e..63d4813ee 100644 --- a/03_Animal/python/animal.py +++ b/03_Animal/python/animal.py @@ -61,7 +61,7 @@ def update_node(self, new_question, answer_new_ques, new_animal): # we replace the animal with a new question self.text = new_question - if answer_new_ques == 'y': + if answer_new_ques == "y": self.yes_node = Node(new_animal, None, None) self.no_node = Node(old_animal, None, None) else: @@ -79,7 +79,7 @@ def list_known_animals(root_node): return if root_node.is_leaf(): - print(root_node.text, end=' '*11) + print(root_node.text, end=" " * 11) return if root_node.yes_node: @@ -96,13 +96,13 @@ def parse_input(message, check_list, root_node): try: inp = input(message) - if check_list and inp.lower() == 'list': - print('Animals I already know are:') + if check_list and inp.lower() == "list": + print("Animals I already know are:") list_known_animals(root_node) - print('\n') + print("\n") token = inp[0].lower() - if token == 'y' or token == 'n': + if token == "y" or token == "n": correct_input = True except IndexError: pass @@ -111,28 +111,27 @@ def parse_input(message, check_list, root_node): def avoid_void_input(message): - answer = '' - while answer == '': + answer = "" + while answer == "": answer = input(message) return answer def initial_message(): - print(' '*32 + 'Animal') - print(' '*15 + 'Creative Computing Morristown, New Jersey\n') - print('Play ´Guess the Animal´') - print('Think of an animal and the computer will try to guess it.\n') + print(" " * 32 + "Animal") + print(" " * 15 + "Creative Computing Morristown, New Jersey\n") + print("Play ´Guess the Animal´") + print("Think of an animal and the computer will try to guess it.\n") # Initial tree -yes_child = Node('Fish', None, None) -no_child = Node('Bird', None, None) -root = Node('Does it swim?', yes_child, no_child) +yes_child = Node("Fish", None, None) +no_child = Node("Bird", None, None) +root = Node("Does it swim?", yes_child, no_child) # Main loop of game initial_message() -keep_playing = parse_input( - 'Are you thinking of an animal? ', True, root) == 'y' +keep_playing = parse_input("Are you thinking of an animal? ", True, root) == "y" while keep_playing: keep_asking = True # Start traversing the tree by the root @@ -144,33 +143,37 @@ def initial_message(): # we have to keep asking i.e. traversing nodes answer = parse_input(actual_node.text, False, None) - if answer == 'y': + if answer == "y": actual_node = actual_node.yes_node else: actual_node = actual_node.no_node else: # we have reached a possible answer - answer = parse_input('Is it a {}? '.format( - actual_node.text), False, None) - if answer == 'n': + answer = parse_input(f"Is it a {actual_node.text}? ", False, None) + if answer == "n": # add the new animal to the tree new_animal = avoid_void_input( - 'The animal you were thinking of was a ? ') + "The animal you were thinking of was a ? " + ) new_question = avoid_void_input( - 'Please type in a question that would distinguish a {} from a {}: '.format(new_animal, actual_node.text)) + "Please type in a question that would distinguish a {} from a {}: ".format( + new_animal, actual_node.text + ) + ) answer_new_question = parse_input( - 'for a {} the answer would be: '.format(new_animal), False, None) + f"for a {new_animal} the answer would be: ", False, None + ) actual_node.update_node( - new_question+'?', answer_new_question, new_animal) + new_question + "?", answer_new_question, new_animal + ) else: print("Why not try another animal?") keep_asking = False - keep_playing = parse_input( - 'Are you thinking of an animal? ', True, root) == 'y' + keep_playing = parse_input("Are you thinking of an animal? ", True, root) == "y" ######################################################## diff --git a/03_Animal/ruby/animal.rb b/03_Animal/ruby/animal.rb index 5100b2aa3..bedf55248 100644 --- a/03_Animal/ruby/animal.rb +++ b/03_Animal/ruby/animal.rb @@ -92,4 +92,4 @@ def main trap "SIGINT" do puts; exit 130 end -main \ No newline at end of file +main diff --git a/03_Animal/vbnet/README.md b/03_Animal/vbnet/README.md index 9ac8afe5e..5d8a43bfb 100644 --- a/03_Animal/vbnet/README.md +++ b/03_Animal/vbnet/README.md @@ -4,6 +4,6 @@ Conversion to [Visual Basic .NET](https://en.wikipedia.org/wiki/Visual_Basic_.NE This takes some inspiration from the [C# port of Animal](https://github.com/zspitz/basic-computer-games/tree/main/03_Animal/csharp). -The `Game` class takes a console abstraction (`ConsoleAdapterBase`), which could also be used for different UIs, such as WinForms or a web page. -This solution also has an xUnit tests project. +The `Game` class takes a console abstraction (`ConsoleAdapterBase`), which could also be used for different UIs, such as WinForms or a web page. +This solution also has an xUnit tests project. Responses can be entered in any capitalization, but animals and the distinguishing question will be converted to uppercase. diff --git a/04_Awari/csharp/Game.cs b/04_Awari/csharp/Game.cs index 8a673dea2..f4325cf78 100644 --- a/04_Awari/csharp/Game.cs +++ b/04_Awari/csharp/Game.cs @@ -261,4 +261,4 @@ public enum GameWinner Draw, } -public record struct GameOutcome(GameWinner Winner, int Difference); \ No newline at end of file +public record struct GameOutcome(GameWinner Winner, int Difference); diff --git a/04_Awari/csharp/Program.cs b/04_Awari/csharp/Program.cs index 750787e79..e97cfdfef 100644 --- a/04_Awari/csharp/Program.cs +++ b/04_Awari/csharp/Program.cs @@ -95,4 +95,4 @@ void ComputerTurn() Console.WriteLine($"MY MOVE IS {movesString}"); } -string Tab(int n) => new(' ', n); \ No newline at end of file +string Tab(int n) => new(' ', n); diff --git a/04_Awari/javascript/awari.js b/04_Awari/javascript/awari.js index cda27c08b..0a6b47c2e 100644 --- a/04_Awari/javascript/awari.js +++ b/04_Awari/javascript/awari.js @@ -12,10 +12,10 @@ function input() { var input_element; var input_str; - + return new Promise(function (resolve) { input_element = document.createElement("INPUT"); - + print("? "); input_element.setAttribute("type", "text"); input_element.setAttribute("length", "50"); @@ -65,7 +65,7 @@ function show_number(number) function show_board() { var i; - + print("\n"); print(" "); for (i = 12; i >= 7; i--) @@ -184,12 +184,12 @@ async function main() e = 0; for (i = 0; i <= 12; i++) b[i] = 3; - + c = 0; f[n] = 0; b[13] = 0; b[6] = 0; - + while (1) { show_board(); print("YOUR MOVE"); diff --git a/05_Bagels/csharp/BagelNumber.cs b/05_Bagels/csharp/BagelNumber.cs index 2fd660e9a..86a048f24 100644 --- a/05_Bagels/csharp/BagelNumber.cs +++ b/05_Bagels/csharp/BagelNumber.cs @@ -54,7 +54,7 @@ public BagelNumber(string number) _digits = number.Select(d => d - '0').ToArray(); } - + //public BagelNumber(long number) //{ // var digits = new List(); @@ -118,4 +118,4 @@ private static void Shuffle(int[] digits) return (pico, fermi); } } -} \ No newline at end of file +} diff --git a/05_Bagels/csharp/Game.cs b/05_Bagels/csharp/Game.cs index f6885464d..7015d20f6 100644 --- a/05_Bagels/csharp/Game.cs +++ b/05_Bagels/csharp/Game.cs @@ -121,4 +121,4 @@ private void DisplayIntroText() Console.ReadKey(true); } } -} \ No newline at end of file +} diff --git a/05_Bagels/csharp/GameBase.cs b/05_Bagels/csharp/GameBase.cs index db8af5ae3..2591c0f97 100644 --- a/05_Bagels/csharp/GameBase.cs +++ b/05_Bagels/csharp/GameBase.cs @@ -36,4 +36,4 @@ protected bool TryAgain() } } -} \ No newline at end of file +} diff --git a/05_Bagels/java/BagelGame.java b/05_Bagels/java/BagelGame.java index 19a621c93..d299dec5e 100644 --- a/05_Bagels/java/BagelGame.java +++ b/05_Bagels/java/BagelGame.java @@ -16,34 +16,34 @@ import java.util.Set; public class BagelGame { - + public static final String CORRECT = "FERMI FERMI FERMI"; public static final int MAX_GUESSES = 20; - + enum GameState { RUNNING, WON, LOST } - + private GameState state = GameState.RUNNING; private List secretNum; private int guessNum = 1; - + public BagelGame() { // No-arg constructor for when you don't need to set the seed this(new Random()); } - + public BagelGame(long seed) { // Setting the seed as a long value this(new Random(seed)); } - + public BagelGame(Random rand) { // This is the "real" constructor, which expects an instance of // Random to use for shuffling the digits of the secret number. - + // Since the digits cannot repeat in our "number", we can't just // pick three random 0-9 integers. Instead, we'll treat it like // a deck of ten cards, numbered 0-9. @@ -57,23 +57,23 @@ public BagelGame(Random rand) { // uses a fresh Random class PRNG, but we're supplying our own // to give us controll over whether or not we set the seed Collections.shuffle(digits, rand); - + // Just take the first three digits secretNum = digits.subList(0, 3); } - + public boolean isOver() { return state != GameState.RUNNING; } - + public boolean isWon() { return state == GameState.WON; } - + public int getGuessNum() { return guessNum; } - + public String getSecretAsString() { // Convert the secret number to a three-character string String secretString = ""; @@ -82,7 +82,7 @@ public String getSecretAsString() { } return secretString; } - + @Override public String toString() { // Quick report of game state for debugging purposes @@ -91,13 +91,13 @@ public String toString() { s += "Secret Number: " + secretNum; return s; } - + public String validateGuess(String guess) { // Checks the passed string and returns null if it's a valid guess // (i.e., exactly three numeric characters) // If not valid, returns an "error" string to display to user. String error = ""; - + if (guess.length() == 3) { // Correct length. Are all the characters numbers? try { @@ -122,20 +122,20 @@ public String validateGuess(String guess) { return error; } - + public String makeGuess(String s) throws IllegalArgumentException { // Processes the passed guess string (which, ideally, should be // validated by previously calling validateGuess) // Return a response string (PICO, FERMI, etc.) if valid // Also sets game state accordingly (sets win state or increments // number of guesses) - + // Convert string to integer list, just to keep things civil List guess = new ArrayList(3); for (int i = 0; i < 3; i++) { guess.add((int)s.charAt(i) - 48); } - + // Build response string... String response = ""; // Correct digit, but in wrong place? @@ -177,5 +177,5 @@ public String makeGuess(String s) throws IllegalArgumentException { } return response; } - -} \ No newline at end of file + +} diff --git a/05_Bagels/java/Bagels.java b/05_Bagels/java/Bagels.java index 435b5644c..8b4174ac3 100644 --- a/05_Bagels/java/Bagels.java +++ b/05_Bagels/java/Bagels.java @@ -35,7 +35,7 @@ public class Bagels { public static void main(String[] args) { - + int gamesWon = 0; // Intro text @@ -43,7 +43,7 @@ public static void main(String[] args) { System.out.println("Creative Computing Morristown, New Jersey"); System.out.println("\n\n"); System.out.print("Would you like the rules (Yes or No)? "); - + // Need instructions? Scanner scan = new Scanner(System.in); String s = scan.nextLine(); @@ -55,15 +55,15 @@ public static void main(String[] args) { System.out.println(" FERMI - One digit correct and in the right position"); System.out.println(" BAGELS - No digits correct"); } - + // Loop for playing multiple games boolean stillPlaying = true; while(stillPlaying) { - + // Set up a new game BagelGame game = new BagelGame(); System.out.println("\nO.K. I have a number in mind."); - + // Loop guess and responsses until game is over while (!game.isOver()) { String guess = getValidGuess(game); @@ -73,7 +73,7 @@ public static void main(String[] args) { System.out.println(response); } } - + // Game is over. But did we win or lose? if (game.isWon()) { System.out.println("You got it!!!\n"); @@ -83,24 +83,24 @@ public static void main(String[] args) { System.out.print("That's " + BagelGame.MAX_GUESSES + " guesses. "); System.out.println("My number was " + game.getSecretAsString()); } - + stillPlaying = getReplayResponse(); } - + // Print goodbye message if (gamesWon > 0) { System.out.println("\nA " + gamesWon + " point Bagels buff!!"); } System.out.println("Hope you had fun. Bye.\n"); } - + private static String getValidGuess(BagelGame game) { // Keep asking for a guess until valid Scanner scan = new Scanner(System.in); boolean valid = false; String guess = ""; String error; - + while (!valid) { System.out.print("Guess # " + game.getGuessNum() + " ? "); guess = scan.nextLine().trim(); @@ -113,7 +113,7 @@ private static String getValidGuess(BagelGame game) { } return guess; } - + private static boolean getReplayResponse() { // keep asking for response until valid Scanner scan = new Scanner(System.in); @@ -126,8 +126,5 @@ private static boolean getReplayResponse() { } } } - -} - - +} diff --git a/05_Bagels/javascript/bagels.js b/05_Bagels/javascript/bagels.js index 37fa36652..5a62a751a 100644 --- a/05_Bagels/javascript/bagels.js +++ b/05_Bagels/javascript/bagels.js @@ -12,10 +12,10 @@ function input() { var input_element; var input_str; - + return new Promise(function (resolve) { input_element = document.createElement("INPUT"); - + print("? "); input_element.setAttribute("type", "text"); input_element.setAttribute("length", "50"); @@ -154,7 +154,7 @@ async function main() print("HOPE YOU HAD FUN. BYE.\n"); else print("\nA " + y + " POINT BAGELS BUFF!!\n"); - + } main(); diff --git a/05_Bagels/perl/bagels.pl b/05_Bagels/perl/bagels.pl index 739ded0e0..94a7744bd 100755 --- a/05_Bagels/perl/bagels.pl +++ b/05_Bagels/perl/bagels.pl @@ -20,7 +20,7 @@ sub yes_input { print ' 'x32; print "Bagels\n"; print ' 'x14; print "Creative Computing Morristown, New Jersey\n\n"; -# Provide instructions if requested +# Provide instructions if requested print "Would you like the rules (yes or no)? "; if (yes_input()) { @@ -39,7 +39,7 @@ sub yes_input { # There are three code loops here. The outermost one, labeled 'PLAY', # performs one game start to finish every time it runs. # The next loop is a for loop that implements the required 20 guesses. -# And the innermost loop, labeled 'CHECK', does the game logic of +# And the innermost loop, labeled 'CHECK', does the game logic of # checking the user's guess to make sure it's valid, figuring out # the response, and rewarding the user if they won. @@ -59,7 +59,7 @@ sub yes_input { # Note that the CHECK loop will automatically loop to ask # for the user's input, and it's only with the 'next' and - # 'last' statements that this loop is exited. So if the + # 'last' statements that this loop is exited. So if the # user's input is somehow invalid, we just print out an # appropriate message. Execution will by default return # to the start of the loop, and only leaves the loop if @@ -75,15 +75,15 @@ sub yes_input { if ($A !~ m{^(\d)(\d)(\d)$}) { print "What?\n"; # Program execution will now pass through the rest - # of the logic below and loop back to the start + # of the logic below and loop back to the start # of the CHECK loop. } else { - # As a side effect of the regex match above, the + # As a side effect of the regex match above, the # $1, $2, and $3 variables are each of the digits # of the user's guess. Perl treats numbers and # strings interchangably, so we will not have to - # use the ASC() conversion functions required + # use the ASC() conversion functions required # by the BASIC program. my @B = ($1,$2,$3); @@ -134,11 +134,11 @@ sub yes_input { # Print out the clues. The 'x' operator # prints out the string the indicated number - # of times. The "BAGELS" line uses Perl's - # ternary operator to print the word if + # of times. The "BAGELS" line uses Perl's + # ternary operator to print the word if # the expression ($C + $D) is equal to 0. - printf("%s%s%s\n", + printf("%s%s%s\n", "PICO " x$C, "FERMI "x$D, ($C+$D==0 ? "BAGELS" : '') @@ -152,11 +152,11 @@ sub yes_input { } # end of regex match else block # If program execution reaches this particular point, - # then the user's input has not been accepted (the + # then the user's input has not been accepted (the # only ways out of this loop are the "next PLAY" statement # when the user wins, and the "last CHECK" statement # when the user's input is successfully parsed). - # So the program execution goes back to the top of the + # So the program execution goes back to the top of the # CHECK loop, printing the request for user input # again. @@ -183,7 +183,7 @@ sub yes_input { # This 'continue' loop is reached either when the PLAY loop has completed # or via the 'next PLAY' statement when the user wins a game. In either - # case we ask if the player wants to go again, and use the 'last' + # case we ask if the player wants to go again, and use the 'last' # statement to exit the loop if the response is not yes. print "Play again (yes or no) ? "; last unless yes_input(); diff --git a/05_Bagels/python/bagels.py b/05_Bagels/python/bagels.py index b56a75d02..cc392eb22 100644 --- a/05_Bagels/python/bagels.py +++ b/05_Bagels/python/bagels.py @@ -37,7 +37,6 @@ MAX_GUESSES = 20 - def print_rules(): print("\nI am thinking of a three-digit number. Try to guess") print("my number and I will give you clues as follows:") @@ -46,18 +45,16 @@ def print_rules(): print(" BAGELS - No digits correct") - def pick_number(): # Note that this returns a list of individual digits # as separate strings, not a single integer or string numbers = [i for i in range(10)] random.shuffle(numbers) num = numbers[0:3] - num = [str(i) for i in num] + num = [str(i) for i in num] return num - def get_valid_guess(): valid = False while not valid: @@ -71,8 +68,9 @@ def get_valid_guess(): if len(set(guess)) == 3: valid = True else: - print("Oh, I forgot to tell you that " + - "the number I have in mind") + print( + "Oh, I forgot to tell you that " + "the number I have in mind" + ) print("has no two digits the same.") else: print("What?") @@ -82,16 +80,15 @@ def get_valid_guess(): return guess - def build_result_string(num, guess): result = "" # Correct digits in wrong place for i in range(2): - if num[i] == guess[i+1]: + if num[i] == guess[i + 1]: result += "PICO " - if num[i+1] == guess[i]: + if num[i + 1] == guess[i]: result += "PICO " if num[0] == guess[2]: result += "PICO " @@ -110,8 +107,6 @@ def build_result_string(num, guess): return result - - ###################################################################### @@ -123,7 +118,7 @@ def build_result_string(num, guess): # Anything other than N* will show the rules response = input("Would you like the rules (Yes or No)? ") if len(response) > 0: - if response.upper()[0] != 'N': + if response.upper()[0] != "N": print_rules() else: print_rules() @@ -134,7 +129,7 @@ def build_result_string(num, guess): # New round num = pick_number() - num_str = ''.join(num) + num_str = "".join(num) guesses = 1 print("\nO.K. I have a number in mind.") @@ -147,15 +142,13 @@ def build_result_string(num, guess): print("You got it!!!\n") games_won += 1 guessing = False - else: + else: print(build_result_string(num, guess)) guesses += 1 if guesses > MAX_GUESSES: print("Oh well") - print(f"That's {MAX_GUESSES} guesses. " + - "My number was " + num_str) - guessing = False - + print(f"That's {MAX_GUESSES} guesses. " + "My number was " + num_str) + guessing = False valid_response = False while not valid_response: @@ -172,7 +165,6 @@ def build_result_string(num, guess): print("Hope you had fun. Bye.\n") - ###################################################################### # # Porting Notes @@ -180,7 +172,7 @@ def build_result_string(num, guess): # The original program did an unusually good job of validating the # player's input (compared to many of the other programs in the # book). Those checks and responses have been exactly reproduced. -# +# # # Ideas for Modifications # @@ -192,10 +184,3 @@ def build_result_string(num, guess): # that creates the "result" string? # ###################################################################### - - - - - - - diff --git a/06_Banner/csharp/banner.cs b/06_Banner/csharp/banner.cs index e3e59b4b2..f037d489a 100644 --- a/06_Banner/csharp/banner.cs +++ b/06_Banner/csharp/banner.cs @@ -162,7 +162,7 @@ private void PrintChar(char ch) // numSections decides how many 'sections' need to be printed // for a given line of each character int[] numSections = new int[7]; - // fillInSection decides whether each 'section' of the + // fillInSection decides whether each 'section' of the // character gets filled in with the character or with blanks int[] fillInSection = new int[9]; diff --git a/06_Banner/java/Banner.java b/06_Banner/java/Banner.java index 8c4e1c61d..be1d74fc0 100644 --- a/06_Banner/java/Banner.java +++ b/06_Banner/java/Banner.java @@ -11,21 +11,21 @@ *

* Note: The idea was to create a version of the 1970's BASIC game in Java, without introducing * new features - no additional text, error checking, etc has been added. - * + * * Converted from BASIC to Java by Darren Cardenas. */ - -public class Banner { + +public class Banner { private final Scanner scan; // For user input - + public Banner() { - + scan = new Scanner(System.in); - - } // End of constructor Banner - public void play() { + } // End of constructor Banner + + public void play() { int bitIndex = 0; int centerFlag = 0; @@ -38,19 +38,19 @@ public void play() { int vertical = 0; int vIndex = 0; int writeIndex = 0; - + int[] writerMap = new int[10]; - int[] writeLimit = new int[10]; - + int[] writeLimit = new int[10]; + String centerResponse = ""; String characters = ""; String letter = ""; - String lineContent = ""; + String lineContent = ""; String setPage = ""; String statement = ""; String token = ""; // Print token - - Map symbolData = new HashMap(); + + Map symbolData = new HashMap(); symbolData.put(" ", new int[]{0,0,0,0,0,0,0,0 }); symbolData.put("A", new int[]{0,505,37,35,34,35,37,505 }); symbolData.put("G", new int[]{0,125,131,258,258,290,163,101}); @@ -92,133 +92,133 @@ public void play() { symbolData.put("=", new int[]{0,41,41,41,41,41,41,41 }); symbolData.put("!", new int[]{0,1,1,1,384,1,1,1 }); symbolData.put("0", new int[]{0,57,69,131,258,131,69,57 }); - symbolData.put(".", new int[]{0,1,1,129,449,129,1,1 }); + symbolData.put(".", new int[]{0,1,1,129,449,129,1,1 }); - System.out.print("HORIZONTAL? "); + System.out.print("HORIZONTAL? "); horizontal = Integer.parseInt(scan.nextLine()); - System.out.print("VERTICAL? "); - vertical = Integer.parseInt(scan.nextLine()); - - System.out.print("CENTERED? "); + System.out.print("VERTICAL? "); + vertical = Integer.parseInt(scan.nextLine()); + + System.out.print("CENTERED? "); centerResponse = scan.nextLine().toUpperCase(); - + centerFlag = 0; - + // Lexicographical comparison if (centerResponse.compareTo("P") > 0) { - centerFlag = 1; + centerFlag = 1; } - - System.out.print("CHARACTER (TYPE 'ALL' IF YOU WANT CHARACTER BEING PRINTED)? "); + + System.out.print("CHARACTER (TYPE 'ALL' IF YOU WANT CHARACTER BEING PRINTED)? "); characters = scan.nextLine().toUpperCase(); - + System.out.print("STATEMENT? "); statement = scan.nextLine().toUpperCase(); - + // Initiates the print System.out.print("SET PAGE? "); - setPage = scan.nextLine(); - + setPage = scan.nextLine(); + // Begin loop through statement letters - for (letterIndex = 1; letterIndex <= statement.length(); letterIndex++) { - + for (letterIndex = 1; letterIndex <= statement.length(); letterIndex++) { + // Extract a letter letter = String.valueOf(statement.charAt(letterIndex - 1)); - - // Begin loop through all symbol data - for (String symbolString: symbolData.keySet()) { - + + // Begin loop through all symbol data + for (String symbolString: symbolData.keySet()) { + // Begin letter handling - if (letter.equals(" ")) { - for (index = 1; index <= (7 * horizontal); index++) { + if (letter.equals(" ")) { + for (index = 1; index <= (7 * horizontal); index++) { System.out.println(""); - } + } break; - - } else if (letter.equals(symbolString)) { + + } else if (letter.equals(symbolString)) { token = characters; - if (characters.equals("ALL")) { + if (characters.equals("ALL")) { token = symbolString; - } - + } + for (dataIndex = 1; dataIndex <= 7; dataIndex++) { - + // Avoid overwriting symbol data tempVal = symbolData.get(symbolString)[dataIndex]; - + for (bitIndex = 8; bitIndex >= 0; bitIndex--) { if (Math.pow(2, bitIndex) < tempVal) { writerMap[9 - bitIndex] = 1; tempVal -= Math.pow(2, bitIndex); - if (tempVal == 1) { - writeLimit[dataIndex] = 9 - bitIndex; + if (tempVal == 1) { + writeLimit[dataIndex] = 9 - bitIndex; break; } - + } else { - - writerMap[9 - bitIndex] = 0; + + writerMap[9 - bitIndex] = 0; } } // End of bitIndex loop - + for (hIndex = 1; hIndex <= horizontal; hIndex++) { - - // Add whitespace for centering + + // Add whitespace for centering lineContent = " ".repeat((int)((63 - 4.5 * vertical) * centerFlag / token.length())); - + for (writeIndex = 1; writeIndex <= writeLimit[dataIndex]; writeIndex++) { - - if (writerMap[writeIndex] == 0) { - - for (vIndex = 1; vIndex <= vertical; vIndex++) { - - for (index = 1; index <= token.length(); index++) { - lineContent += " "; - } - } - + + if (writerMap[writeIndex] == 0) { + + for (vIndex = 1; vIndex <= vertical; vIndex++) { + + for (index = 1; index <= token.length(); index++) { + lineContent += " "; + } + } + } else { - - for (vIndex = 1; vIndex <= vertical; vIndex++) { + + for (vIndex = 1; vIndex <= vertical; vIndex++) { lineContent += token; - } + } } } // End of writeIndex loop System.out.println(lineContent); - - } // End of hIndex loop + + } // End of hIndex loop } // End of dataIndex loop - + // Add padding between letters - for (index = 1; index <= 2 * horizontal; index++) { + for (index = 1; index <= 2 * horizontal; index++) { System.out.println(""); } - + } // End letter handling } // End loop through all symbol data - + } // End loop through statement letters // Add extra length to the banner - for (index = 1; index <= 75; index++) { + for (index = 1; index <= 75; index++) { System.out.println(""); - } + } + + } // End of method play - } // End of method play - public static void main(String[] args) { - + Banner game = new Banner(); game.play(); - + } // End of method main - + } // End of class Banner diff --git a/06_Banner/javascript/banner.js b/06_Banner/javascript/banner.js index ca3604873..c67a81515 100644 --- a/06_Banner/javascript/banner.js +++ b/06_Banner/javascript/banner.js @@ -12,10 +12,10 @@ function input() { var input_element; var input_str; - + return new Promise(function (resolve) { input_element = document.createElement("INPUT"); - + print("? "); input_element.setAttribute("type", "text"); input_element.setAttribute("length", "50"); @@ -107,7 +107,7 @@ async function main() as = await input(); print("SET PAGE"); // This means to prepare printer, just press Enter os = await input(); - + for (t = 0; t < as.length; t++) { ps = as.substr(t, 1); for (o = 0; o < 50 * 8; o += 8) { @@ -156,13 +156,13 @@ async function main() str += xs; } } - print(str + "\n"); + print(str + "\n"); } } - for (h = 1; h <= 2 * x; h++) + for (h = 1; h <= 2 * x; h++) print("\n"); } - } + } } main(); diff --git a/06_Banner/python/banner.py b/06_Banner/python/banner.py index 11f107666..33c9e846c 100644 --- a/06_Banner/python/banner.py +++ b/06_Banner/python/banner.py @@ -77,8 +77,7 @@ def print_banner(): g1 = 0 if input("Centered ").lower().startswith("y"): g1 = 1 - mStr = input( - "Character (type 'ALL' if you want character being printed) ").upper() + mStr = input("Character (type 'ALL' if you want character being printed) ").upper() aStr = input("Statement ") # This means to prepare printer, just press Enter oStr = input("Set page ") @@ -92,11 +91,11 @@ def print_banner(): else: for u in range(0, 7): for k in range(8, -1, -1): - if 2 ** k >= s[u]: + if 2**k >= s[u]: j[8 - k] = 0 else: j[8 - k] = 1 - s[u] = s[u] - 2 ** k + s[u] = s[u] - 2**k if s[u] == 1: f[u] = 8 - k break diff --git a/06_Banner/vbnet/banner.vb b/06_Banner/vbnet/banner.vb index 90e183b81..8187c0bce 100644 --- a/06_Banner/vbnet/banner.vb +++ b/06_Banner/vbnet/banner.vb @@ -146,7 +146,7 @@ Module Banner ' numSections decides how many 'sections' need to be printed ' for a given line of each character Dim numSections(7) As Integer - ' fillInSection decides whether each 'section' of the + ' fillInSection decides whether each 'section' of the ' character gets filled in with the character Or with blanks Dim fillInSection(9) As Integer diff --git a/07_Basketball/java/Basketball.java b/07_Basketball/java/Basketball.java index 3ff9e7ab6..50ca95744 100644 --- a/07_Basketball/java/Basketball.java +++ b/07_Basketball/java/Basketball.java @@ -1,5 +1,5 @@ import java.lang.Math; -import java.util.*; +import java.util.*; import java.util.Scanner; /* The basketball class is a computer game that allows you to play as @@ -15,7 +15,7 @@ public class Basketball { int shot = -1; List shot_choices = Arrays.asList(0, 1, 2, 3, 4); double opponent_chance = 0; - String opponent = null; + String opponent = null; public Basketball() { @@ -41,7 +41,7 @@ public Basketball() { else { scanner.next(); } - + // makes sure that input is legal while (!defense_choices.contains(defense)) { System.out.print("Your new defensive allignment is? "); @@ -57,7 +57,7 @@ public Basketball() { // takes input for opponent's name System.out.print("\nChoose your opponent? "); - opponent = scanner.next(); + opponent = scanner.next(); start_of_period(); } @@ -67,13 +67,13 @@ private void add_points(int team, int points) { score[team] += points; print_score(); } - + private void ball_passed_back() { System.out.print("Ball passed back to you. "); dartmouth_ball(); } - + // change defense, called when the user enters 0 for their shot private void change_defense() { defense = -1; @@ -82,13 +82,13 @@ private void change_defense() { while (!defense_choices.contains(defense)) { System.out.println("Your new defensive allignment is? "); if (scanner.hasNextDouble()) { - defense = (double)(scanner.nextDouble()); + defense = (double)(scanner.nextDouble()); } else { - continue; + continue; } } - + dartmouth_ball(); } @@ -102,15 +102,15 @@ private void foul_shots(int team) { } else { System.out.println("Shooter makes one shot and misses one."); - score[team] += 1; - } + score[team] += 1; + } } else { System.out.println("Shooter makes both shots."); score[team] += 2; } - - print_score(); + + print_score(); } // called when time = 50, starts a new period @@ -127,13 +127,13 @@ private void print_score() { // simulates a center jump for posession at the beginning of a period private void start_of_period() { - System.out.println("Center jump"); + System.out.println("Center jump"); if (Math.random() > .6) { - System.out.println("Dartmouth controls the tap.\n"); + System.out.println("Dartmouth controls the tap.\n"); dartmouth_ball(); } else { - System.out.println(opponent + " controls the tap.\n"); + System.out.println(opponent + " controls the tap.\n"); opponent_ball(); } } @@ -142,10 +142,10 @@ private void start_of_period() { private void two_minute_warning() { System.out.println(" *** Two minutes left in the game ***"); } - + // called when the user enters 1 or 2 for their shot private void dartmouth_jump_shot() { - time ++; + time ++; if (time == 50) { halftime(); } @@ -171,135 +171,135 @@ else if (time == 92) { else { if (Math.random() > .5) { System.out.println("Shot is blocked. Ball controlled by " + - opponent + ".\n"); - opponent_ball(); - } + opponent + ".\n"); + opponent_ball(); + } else { - System.out.println("Shot is blocked. Ball controlled by Dartmouth."); - dartmouth_ball(); - } + System.out.println("Shot is blocked. Ball controlled by Dartmouth."); + dartmouth_ball(); + } } } else { - System.out.println("Shot is off target."); + System.out.println("Shot is off target."); if (defense / 6 * Math.random() > .45) { - System.out.println("Rebound to " + opponent + "\n"); - opponent_ball(); - } + System.out.println("Rebound to " + opponent + "\n"); + opponent_ball(); + } else { - System.out.println("Dartmouth controls the rebound."); + System.out.println("Dartmouth controls the rebound."); if (Math.random() > .4) { if (defense == 6 && Math.random() > .6) { System.out.println("Pass stolen by " + opponent - + ", easy lay up"); - add_points(0, 2); - dartmouth_ball(); - } + + ", easy lay up"); + add_points(0, 2); + dartmouth_ball(); + } else { // ball is passed back to you - ball_passed_back(); - } + ball_passed_back(); + } } else { - System.out.println(""); - dartmouth_non_jump_shot(); + System.out.println(""); + dartmouth_non_jump_shot(); } } } - } + } else { - System.out.println("Shot is good."); - add_points(1, 2); - opponent_ball(); + System.out.println("Shot is good."); + add_points(1, 2); + opponent_ball(); } } - + // called when the user enters 0, 3, or 4 // lay up, set shot, or defense change private void dartmouth_non_jump_shot() { - time ++; + time ++; if (time == 50) { halftime(); } else if (time == 92) { two_minute_warning(); } - + if (shot == 4) { System.out.println("Set shot."); } else if (shot == 3) { - System.out.println("Lay up."); + System.out.println("Lay up."); } else if (shot == 0) { - change_defense(); + change_defense(); } - + // simulates different outcomes after a lay up or set shot if (7/defense*Math.random() > .4) { if (7/defense*Math.random() > .7) { if (7/defense*Math.random() > .875) { if (7/defense*Math.random() > .925) { - System.out.println("Charging foul. Dartmouth loses the ball.\n"); - opponent_ball(); + System.out.println("Charging foul. Dartmouth loses the ball.\n"); + opponent_ball(); } else { - System.out.println("Shot blocked. " + opponent + "'s ball.\n"); - opponent_ball(); + System.out.println("Shot blocked. " + opponent + "'s ball.\n"); + opponent_ball(); } } else { - foul_shots(1); - opponent_ball(); + foul_shots(1); + opponent_ball(); } } else { - System.out.println("Shot is off the rim."); + System.out.println("Shot is off the rim."); if (Math.random() > 2/3) { - System.out.println("Dartmouth controls the rebound."); + System.out.println("Dartmouth controls the rebound."); if (Math.random() > .4) { - System.out.println("Ball passed back to you.\n"); - dartmouth_ball(); + System.out.println("Ball passed back to you.\n"); + dartmouth_ball(); } else { - dartmouth_non_jump_shot(); + dartmouth_non_jump_shot(); } } else { - System.out.println(opponent + " controls the rebound.\n"); - opponent_ball(); + System.out.println(opponent + " controls the rebound.\n"); + opponent_ball(); } } } else { - System.out.println("Shot is good. Two points."); - add_points(1, 2); - opponent_ball(); + System.out.println("Shot is good. Two points."); + add_points(1, 2); + opponent_ball(); } } - - + + // plays out a Dartmouth posession, starting with your choice of shot private void dartmouth_ball() { Scanner scanner = new Scanner(System.in); // creates a scanner - System.out.print("Your shot? "); - shot = -1; + System.out.print("Your shot? "); + shot = -1; if (scanner.hasNextInt()) { - shot = scanner.nextInt(); + shot = scanner.nextInt(); } else { System.out.println(""); - scanner.next(); + scanner.next(); } - + while (!shot_choices.contains(shot)) { System.out.print("Incorrect answer. Retype it. Your shot?"); if (scanner.hasNextInt()) { - shot = scanner.nextInt(); + shot = scanner.nextInt(); } else { System.out.println(""); - scanner.next(); + scanner.next(); } } @@ -308,154 +308,154 @@ private void dartmouth_ball() { dartmouth_jump_shot(); } else { - dartmouth_non_jump_shot(); + dartmouth_non_jump_shot(); } } else { if (score[0] != score[1]) { - System.out.println("\n ***** End Of Game *****"); + System.out.println("\n ***** End Of Game *****"); System.out.println("Final Score: Dartmouth: " + score[1] + " " - + opponent + ": " + score[0]); + + opponent + ": " + score[0]); System.exit(0); } else { - System.out.println("\n ***** End Of Second Half *****"); - System.out.println("Score at end of regulation time:"); + System.out.println("\n ***** End Of Second Half *****"); + System.out.println("Score at end of regulation time:"); System.out.println(" Dartmouth: " + score[1] + " " + - opponent + ": " + score[0]); - System.out.println("Begin two minute overtime period"); - time = 93; - start_of_period(); + opponent + ": " + score[0]); + System.out.println("Begin two minute overtime period"); + time = 93; + start_of_period(); } } } - + // simulates the opponents jumpshot private void opponent_jumpshot() { - System.out.println("Jump Shot."); + System.out.println("Jump Shot."); if (8/defense*Math.random() > .35) { if (8/defense*Math.random() > .75) { if (8/defense*Math.random() > .9) { - System.out.println("Offensive foul. Dartmouth's ball.\n"); - dartmouth_ball(); + System.out.println("Offensive foul. Dartmouth's ball.\n"); + dartmouth_ball(); } else { - foul_shots(0); - dartmouth_ball(); + foul_shots(0); + dartmouth_ball(); } } else { - System.out.println("Shot is off the rim."); + System.out.println("Shot is off the rim."); if (defense/6*Math.random() > .5) { System.out.println(opponent + " controls the rebound."); if (defense == 6) { if (Math.random() > .75) { - System.out.println("Ball stolen. Easy lay up for Dartmouth."); - add_points(1, 2); - opponent_ball(); + System.out.println("Ball stolen. Easy lay up for Dartmouth."); + add_points(1, 2); + opponent_ball(); } else { if (Math.random() > .5) { - System.out.println(""); - opponent_non_jumpshot(); + System.out.println(""); + opponent_non_jumpshot(); } else { System.out.println("Pass back to " + opponent + - " guard.\n"); - opponent_ball(); + " guard.\n"); + opponent_ball(); } } } else { if (Math.random() > .5) { - opponent_non_jumpshot(); + opponent_non_jumpshot(); } else { System.out.println("Pass back to " + opponent + - " guard.\n"); - opponent_ball(); + " guard.\n"); + opponent_ball(); } } } else { - System.out.println("Dartmouth controls the rebound.\n"); - dartmouth_ball(); + System.out.println("Dartmouth controls the rebound.\n"); + dartmouth_ball(); } } - } + } else { - System.out.println("Shot is good."); - add_points(0, 2); - dartmouth_ball(); + System.out.println("Shot is good."); + add_points(0, 2); + dartmouth_ball(); } } // simulates opponents lay up or set shot private void opponent_non_jumpshot() { if (opponent_chance > 3) { - System.out.println("Set shot."); + System.out.println("Set shot."); } else { - System.out.println("Lay up"); + System.out.println("Lay up"); } if (7/defense*Math.random() > .413) { - System.out.println("Shot is missed."); + System.out.println("Shot is missed."); if (defense/6*Math.random() > .5) { - System.out.println(opponent + " controls the rebound."); + System.out.println(opponent + " controls the rebound."); if (defense == 6) { if (Math.random() > .75) { - System.out.println("Ball stolen. Easy lay up for Dartmouth."); - add_points(1, 2); - opponent_ball(); + System.out.println("Ball stolen. Easy lay up for Dartmouth."); + add_points(1, 2); + opponent_ball(); } else { if (Math.random() > .5) { - System.out.println(""); - opponent_non_jumpshot(); + System.out.println(""); + opponent_non_jumpshot(); } else { System.out.println("Pass back to " + opponent + - " guard.\n"); - opponent_ball(); + " guard.\n"); + opponent_ball(); } } } else { if (Math.random() > .5) { - System.out.println(""); - opponent_non_jumpshot(); + System.out.println(""); + opponent_non_jumpshot(); } else { - System.out.println("Pass back to " + opponent + " guard\n"); - opponent_ball(); + System.out.println("Pass back to " + opponent + " guard\n"); + opponent_ball(); } } } else { - System.out.println("Dartmouth controls the rebound.\n"); - dartmouth_ball(); + System.out.println("Dartmouth controls the rebound.\n"); + dartmouth_ball(); } } else { - System.out.println("Shot is good."); - add_points(0, 2); - dartmouth_ball(); + System.out.println("Shot is good."); + add_points(0, 2); + dartmouth_ball(); } } // simulates an opponents possesion // #randomly picks jump shot or lay up / set shot. private void opponent_ball() { - time ++; + time ++; if (time == 50) { halftime(); } - opponent_chance = 10/4*Math.random()+1; + opponent_chance = 10/4*Math.random()+1; if (opponent_chance > 2) { - opponent_non_jumpshot(); + opponent_non_jumpshot(); } else { - opponent_jumpshot(); + opponent_jumpshot(); } } @@ -463,7 +463,3 @@ public static void main(String[] args) { Basketball new_game = new Basketball(); } } - - - - diff --git a/07_Basketball/javascript/basketball.js b/07_Basketball/javascript/basketball.js index 5b0b73e70..ed98fb0de 100644 --- a/07_Basketball/javascript/basketball.js +++ b/07_Basketball/javascript/basketball.js @@ -12,10 +12,10 @@ function input() { var input_element; var input_str; - + return new Promise(function (resolve) { input_element = document.createElement("INPUT"); - + print("? "); input_element.setAttribute("type", "text"); input_element.setAttribute("length", "50"); diff --git a/07_Basketball/python/basketball.py b/07_Basketball/python/basketball.py index 20a6cd94f..1137086c1 100644 --- a/07_Basketball/python/basketball.py +++ b/07_Basketball/python/basketball.py @@ -6,7 +6,7 @@ # You are able to choose your shot types as well as defensive formations -class Basketball(): +class Basketball: def __init__(self): self.time = 0 self.score = [0, 0] # first value is opponents score, second is home @@ -22,12 +22,14 @@ def __init__(self): print("This is Dartmouth College basketball. ") print("Υou will be Dartmouth captain and playmaker.") print("Call shots as follows:") - print("1. Long (30ft.) Jump Shot; 2. Short (15 ft.) Jump Shot; " - + "3. Lay up; 4. Set Shot") + print( + "1. Long (30ft.) Jump Shot; 2. Short (15 ft.) Jump Shot; " + + "3. Lay up; 4. Set Shot" + ) print("Both teams will use the same defense. Call Defense as follows:") print("6. Press; 6.5 Man-to-Man; 7. Zone; 7.5 None.") print("To change defense, just type 0 as your next shot.") - print("Your starting defense will be? ", end='') + print("Your starting defense will be? ", end="") # takes input for a defense try: @@ -38,7 +40,7 @@ def __init__(self): # if the input wasn't a valid defense, takes input again while self.defense not in self.defense_choices: - print("Your new defensive allignment is? ", end='') + print("Your new defensive allignment is? ", end="") try: self.defense = float(input()) @@ -46,7 +48,7 @@ def __init__(self): continue # takes input for opponent's name - print("\nChoose your opponent? ", end='') + print("\nChoose your opponent? ", end="") self.opponent = input() self.start_of_period() @@ -58,7 +60,7 @@ def add_points(self, team, points): self.print_score() def ball_passed_back(self): - print("Ball passed back to you. ", end='') + print("Ball passed back to you. ", end="") self.dartmouth_ball() # change defense, called when the user enters 0 for their shot @@ -77,8 +79,8 @@ def change_defense(self): # simulates two foul shots for a player and adds the points def foul_shots(self, team): print("Shooter fouled. Two shots.") - if random.random() > .49: - if random.random() > .75: + if random.random() > 0.49: + if random.random() > 0.75: print("Both shots missed.") else: print("Shooter makes one shot and misses one.") @@ -97,13 +99,12 @@ def halftime(self): # prints the current score def print_score(self): - print("Score: " + str(self.score[1]) - + " to " + str(self.score[0]) + "\n") + print("Score: " + str(self.score[1]) + " to " + str(self.score[0]) + "\n") # simulates a center jump for posession at the beginning of a period def start_of_period(self): print("Center jump") - if random.random() > .6: + if random.random() > 0.6: print("Dartmouth controls the tap.\n") self.dartmouth_ball() else: @@ -123,10 +124,10 @@ def dartmouth_jump_shot(self): self.two_minute_warning() print("Jump Shot.") # simulates chances of different possible outcomes - if random.random() > .341 * self.defense / 8: - if random.random() > .682 * self.defense / 8: - if random.random() > .782 * self.defense / 8: - if random.random() > .843 * self.defense / 8: + if random.random() > 0.341 * self.defense / 8: + if random.random() > 0.682 * self.defense / 8: + if random.random() > 0.782 * self.defense / 8: + if random.random() > 0.843 * self.defense / 8: print("Charging foul. Dartmouth loses ball.\n") self.opponent_ball() else: @@ -134,24 +135,26 @@ def dartmouth_jump_shot(self): self.foul_shots(1) self.opponent_ball() else: - if random.random() > .5: - print("Shot is blocked. Ball controlled by " + - self.opponent + ".\n") + if random.random() > 0.5: + print( + "Shot is blocked. Ball controlled by " + + self.opponent + + ".\n" + ) self.opponent_ball() else: print("Shot is blocked. Ball controlled by Dartmouth.") self.dartmouth_ball() else: print("Shot is off target.") - if self.defense / 6 * random.random() > .45: + if self.defense / 6 * random.random() > 0.45: print("Rebound to " + self.opponent + "\n") self.opponent_ball() else: print("Dartmouth controls the rebound.") - if random.random() > .4: - if self.defense == 6 and random.random() > .6: - print("Pass stolen by " + self.opponent - + ", easy lay up") + if random.random() > 0.4: + if self.defense == 6 and random.random() > 0.6: + print("Pass stolen by " + self.opponent + ", easy lay up") self.add_points(0, 2) self.dartmouth_ball() else: @@ -182,10 +185,10 @@ def dartmouth_non_jump_shot(self): self.change_defense() # simulates different outcomes after a lay up or set shot - if 7/self.defense*random.random() > .4: - if 7/self.defense*random.random() > .7: - if 7/self.defense*random.random() > .875: - if 7/self.defense*random.random() > .925: + if 7 / self.defense * random.random() > 0.4: + if 7 / self.defense * random.random() > 0.7: + if 7 / self.defense * random.random() > 0.875: + if 7 / self.defense * random.random() > 0.925: print("Charging foul. Dartmouth loses the ball.\n") self.opponent_ball() else: @@ -196,9 +199,9 @@ def dartmouth_non_jump_shot(self): self.opponent_ball() else: print("Shot is off the rim.") - if random.random() > 2/3: + if random.random() > 2 / 3: print("Dartmouth controls the rebound.") - if random.random() > .4: + if random.random() > 0.4: print("Ball passed back to you.\n") self.dartmouth_ball() else: @@ -213,7 +216,7 @@ def dartmouth_non_jump_shot(self): # plays out a Dartmouth posession, starting with your choice of shot def dartmouth_ball(self): - print("Your shot? ", end='') + print("Your shot? ", end="") self.shot = None try: self.shot = int(input()) @@ -221,13 +224,13 @@ def dartmouth_ball(self): self.shot = None while self.shot not in self.shot_choices: - print("Incorrect answer. Retype it. Your shot? ", end='') + print("Incorrect answer. Retype it. Your shot? ", end="") try: self.shot = int(input()) except: continue - if self.time < 100 or random.random() < .5: + if self.time < 100 or random.random() < 0.5: if self.shot == 1 or self.shot == 2: self.dartmouth_jump_shot() else: @@ -235,13 +238,25 @@ def dartmouth_ball(self): else: if self.score[0] != self.score[1]: print("\n ***** End Of Game *****") - print("Final Score: Dartmouth: " + str(self.score[1]) + " " - + self.opponent + ": " + str(self.score[0])) + print( + "Final Score: Dartmouth: " + + str(self.score[1]) + + " " + + self.opponent + + ": " + + str(self.score[0]) + ) else: print("\n ***** End Of Second Half *****") print("Score at end of regulation time:") - print(" Dartmouth: " + str(self.score[1]) + " " + - self.opponent + ": " + str(self.score[0])) + print( + " Dartmouth: " + + str(self.score[1]) + + " " + + self.opponent + + ": " + + str(self.score[0]) + ) print("Begin two minute overtime period") self.time = 93 self.start_of_period() @@ -249,9 +264,9 @@ def dartmouth_ball(self): # simulates the opponents jumpshot def opponent_jumpshot(self): print("Jump Shot.") - if 8/self.defense*random.random() > .35: - if 8/self.defense*random.random() > .75: - if 8/self.defense*random.random() > .9: + if 8 / self.defense * random.random() > 0.35: + if 8 / self.defense * random.random() > 0.75: + if 8 / self.defense * random.random() > 0.9: print("Offensive foul. Dartmouth's ball.\n") self.dartmouth_ball() else: @@ -259,27 +274,25 @@ def opponent_jumpshot(self): self.dartmouth_ball() else: print("Shot is off the rim.") - if self.defense/6*random.random() > .5: + if self.defense / 6 * random.random() > 0.5: print(self.opponent + " controls the rebound.") if self.defense == 6: - if random.random() > .75: + if random.random() > 0.75: print("Ball stolen. Easy lay up for Dartmouth.") self.add_points(1, 2) self.opponent_ball() else: - if random.random() > .5: + if random.random() > 0.5: print("") self.opponent_non_jumpshot() else: - print("Pass back to " + self.opponent + - " guard.\n") + print("Pass back to " + self.opponent + " guard.\n") self.opponent_ball() else: - if random.random() > .5: + if random.random() > 0.5: self.opponent_non_jumpshot() else: - print("Pass back to " + self.opponent + - " guard.\n") + print("Pass back to " + self.opponent + " guard.\n") self.opponent_ball() else: print("Dartmouth controls the rebound.\n") @@ -295,25 +308,24 @@ def opponent_non_jumpshot(self): print("Set shot.") else: print("Lay up") - if 7/self.defense*random.random() > .413: + if 7 / self.defense * random.random() > 0.413: print("Shot is missed.") - if self.defense/6*random.random() > .5: + if self.defense / 6 * random.random() > 0.5: print(self.opponent + " controls the rebound.") if self.defense == 6: - if random.random() > .75: + if random.random() > 0.75: print("Ball stolen. Easy lay up for Dartmouth.") self.add_points(1, 2) self.opponent_ball() else: - if random.random() > .5: + if random.random() > 0.5: print("") self.opponent_non_jumpshot() else: - print("Pass back to " + self.opponent + - " guard.\n") + print("Pass back to " + self.opponent + " guard.\n") self.opponent_ball() else: - if random.random() > .5: + if random.random() > 0.5: print("") self.opponent_non_jumpshot() else: @@ -333,7 +345,7 @@ def opponent_ball(self): self.time += 1 if self.time == 50: self.halftime() - self.z1 = 10/4*random.random()+1 + self.z1 = 10 / 4 * random.random() + 1 if self.z1 > 2: self.opponent_non_jumpshot() else: diff --git a/08_Batnum/batnum.bas b/08_Batnum/batnum.bas index 0f9e80c5f..40ec86161 100644 --- a/08_Batnum/batnum.bas +++ b/08_Batnum/batnum.bas @@ -3,7 +3,7 @@ 30 PRINT:PRINT:PRINT 110 PRINT "THIS PROGRAM IS A 'BATTLE OF NUMBERS' GAME, WHERE THE" 120 PRINT "COMPUTER IS YOUR OPPONENT." -130 PRINT +130 PRINT 140 PRINT "THE GAME STARTS WITH AN ASSUMED PILE OF OBJECTS. YOU" 150 PRINT "AND YOUR OPPONENT ALTERNATELY REMOVE OBJECTS FROM THE PILE." 160 PRINT "WINNING IS DEFINED IN ADVANCE AS TAKING THE LAST OBJECT OR" diff --git a/08_Batnum/csharp/BatnumGame.cs b/08_Batnum/csharp/BatnumGame.cs index 1c7028405..b00eaf99f 100644 --- a/08_Batnum/csharp/BatnumGame.cs +++ b/08_Batnum/csharp/BatnumGame.cs @@ -55,7 +55,7 @@ public BatnumGame(int pileSize, WinOptions winCriteria, int minTake, int maxtake /// A message to be displayed to the player public string TakeTurn() { - //Edge condition - can occur when minTake is more > 1 + //Edge condition - can occur when minTake is more > 1 if (pileSize < minTake) { pileSize = 0; diff --git a/08_Batnum/csharp/ConsoleUtilities.cs b/08_Batnum/csharp/ConsoleUtilities.cs index 2dd5f09bf..41097090d 100644 --- a/08_Batnum/csharp/ConsoleUtilities.cs +++ b/08_Batnum/csharp/ConsoleUtilities.cs @@ -10,7 +10,7 @@ public static class ConsoleUtilities { ///

/// Ask the user a question and expects a comma separated pair of numbers representing a number range in response - /// the range provided must have a maximum which is greater than the minimum + /// the range provided must have a maximum which is greater than the minimum /// /// The question to ask /// The minimum value expected diff --git a/08_Batnum/csharp/Program.cs b/08_Batnum/csharp/Program.cs index 08e6b3042..77a97ec26 100644 --- a/08_Batnum/csharp/Program.cs +++ b/08_Batnum/csharp/Program.cs @@ -27,4 +27,3 @@ } } - diff --git a/08_Batnum/csharp/Properties/Resources.Designer.cs b/08_Batnum/csharp/Properties/Resources.Designer.cs index 2c2fac7f3..c72b9ed2e 100644 --- a/08_Batnum/csharp/Properties/Resources.Designer.cs +++ b/08_Batnum/csharp/Properties/Resources.Designer.cs @@ -10,8 +10,8 @@ namespace Batnum.Properties { using System; - - + + /// /// A strongly-typed resource class, for looking up localized strings, etc. /// @@ -23,15 +23,15 @@ namespace Batnum.Properties { [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { - + private static global::System.Resources.ResourceManager resourceMan; - + private static global::System.Globalization.CultureInfo resourceCulture; - + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } - + /// /// Returns the cached ResourceManager instance used by this class. /// @@ -45,7 +45,7 @@ internal Resources() { return resourceMan; } } - + /// /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. @@ -59,7 +59,7 @@ internal Resources() { resourceCulture = value; } } - + /// /// Looks up a localized string similar to COMPUTER TAKES {0} AND LEAVES {1}. /// @@ -68,7 +68,7 @@ internal static string COMPTURN { return ResourceManager.GetString("COMPTURN", resourceCulture); } } - + /// /// Looks up a localized string similar to COMPUTER TAKES {0} AND LOSES. /// @@ -77,7 +77,7 @@ internal static string END_COMPLOSE { return ResourceManager.GetString("END_COMPLOSE", resourceCulture); } } - + /// /// Looks up a localized string similar to COMPUTER TAKES {0} AND WINS. /// @@ -86,7 +86,7 @@ internal static string END_COMPWIN { return ResourceManager.GetString("END_COMPWIN", resourceCulture); } } - + /// /// Looks up a localized string similar to ITS A DRAW, THERE ARE ONLY {0} PIECES LEFT. /// @@ -95,7 +95,7 @@ internal static string END_DRAW { return ResourceManager.GetString("END_DRAW", resourceCulture); } } - + /// /// Looks up a localized string similar to TOUGH LUCK, YOU LOSE.. /// @@ -104,7 +104,7 @@ internal static string END_PLAYERLOSE { return ResourceManager.GetString("END_PLAYERLOSE", resourceCulture); } } - + /// /// Looks up a localized string similar to CONGRATULATIONS, YOU WIN.. /// @@ -113,7 +113,7 @@ internal static string END_PLAYERWIN { return ResourceManager.GetString("END_PLAYERWIN", resourceCulture); } } - + /// /// Looks up a localized string similar to BATNUM. /// @@ -122,7 +122,7 @@ internal static string GAME_NAME { return ResourceManager.GetString("GAME_NAME", resourceCulture); } } - + /// /// Looks up a localized string similar to ILLEGAL MOVE, RENETER IT. /// @@ -131,7 +131,7 @@ internal static string INPUT_ILLEGAL { return ResourceManager.GetString("INPUT_ILLEGAL", resourceCulture); } } - + /// /// Looks up a localized string similar to YOUR MOVE ?. /// @@ -140,7 +140,7 @@ internal static string INPUT_TURN { return ResourceManager.GetString("INPUT_TURN", resourceCulture); } } - + /// /// Looks up a localized string similar to I TOLD YOU NOT TO USE ZERO! COMPUTER WINS BY FORFEIT.. /// @@ -149,7 +149,7 @@ internal static string INPUT_ZERO { return ResourceManager.GetString("INPUT_ZERO", resourceCulture); } } - + /// /// Looks up a localized string similar to CREATIVE COMPUTING MORRISTOWN, NEW JERSEY. /// @@ -158,7 +158,7 @@ internal static string INTRO_HEADER { return ResourceManager.GetString("INTRO_HEADER", resourceCulture); } } - + /// /// Looks up a localized string similar to THIS PROGRAM IS A 'BATTLE' OF NUMBERS GAME, WHERE THE COMPUTER IS YOUR OPPONENT. /// @@ -167,7 +167,7 @@ internal static string INTRO_PART1 { return ResourceManager.GetString("INTRO_PART1", resourceCulture); } } - + /// /// Looks up a localized string similar to THE GAME STARTS WITH AN ASSUMED PILE OF OBJECTS. YOU AND YOUR OPPONENT ALTERNATELY REMOVE OBJECTS FROM THE PILE. WINNNING IS DEFINED IN ADVANCE AS TAKING THE LAST OBJECT OR NOT. YOU CAN ALSO SPECIFY SOME OTHER BEGINING CONDITIONS. DON'T USER ZERO, HOWWEVER, IN PLAYING THE GAME.. /// @@ -176,7 +176,7 @@ internal static string INTRO_PART2 { return ResourceManager.GetString("INTRO_PART2", resourceCulture); } } - + /// /// Looks up a localized string similar to ENTER MIN AND MAX ?. /// @@ -185,7 +185,7 @@ internal static string START_QUESTION_DRAWMINMAX { return ResourceManager.GetString("START_QUESTION_DRAWMINMAX", resourceCulture); } } - + /// /// Looks up a localized string similar to ENTER PILE SIZE ?. /// @@ -194,7 +194,7 @@ internal static string START_QUESTION_PILESIZE { return ResourceManager.GetString("START_QUESTION_PILESIZE", resourceCulture); } } - + /// /// Looks up a localized string similar to ENTER START OPTION - 1 COMPUTER FIRST, 2 YOU FIRST ?. /// @@ -203,7 +203,7 @@ internal static string START_QUESTION_WHOSTARTS { return ResourceManager.GetString("START_QUESTION_WHOSTARTS", resourceCulture); } } - + /// /// Looks up a localized string similar to ENTER WIN OPTION - 1 TO TAKE LAST, 2 TO AVOID LAST: ?. /// diff --git a/08_Batnum/csharp/Properties/Resources.en.resx b/08_Batnum/csharp/Properties/Resources.en.resx index beed709aa..1d3be88c1 100644 --- a/08_Batnum/csharp/Properties/Resources.en.resx +++ b/08_Batnum/csharp/Properties/Resources.en.resx @@ -1,17 +1,17 @@  - @@ -168,4 +168,4 @@ ENTER WIN OPTION - 1 TO TAKE LAST, 2 TO AVOID LAST: ? - \ No newline at end of file + diff --git a/08_Batnum/csharp/Properties/Resources.fr.resx b/08_Batnum/csharp/Properties/Resources.fr.resx index 410562e27..5033ac929 100644 --- a/08_Batnum/csharp/Properties/Resources.fr.resx +++ b/08_Batnum/csharp/Properties/Resources.fr.resx @@ -1,17 +1,17 @@  - @@ -168,4 +168,4 @@ ENTRE LA CONDITION DE VICTOIRE - 1 PRENDRE LA DERNIERE PIECE, 2 EVITER LA DERNIERE PIECE ? - \ No newline at end of file + diff --git a/08_Batnum/csharp/Properties/Resources.resx b/08_Batnum/csharp/Properties/Resources.resx index beed709aa..1d3be88c1 100644 --- a/08_Batnum/csharp/Properties/Resources.resx +++ b/08_Batnum/csharp/Properties/Resources.resx @@ -1,17 +1,17 @@  - @@ -168,4 +168,4 @@ ENTER WIN OPTION - 1 TO TAKE LAST, 2 TO AVOID LAST: ? - \ No newline at end of file + diff --git a/08_Batnum/csharp/README.md b/08_Batnum/csharp/README.md index cd054abd4..9310c3483 100644 --- a/08_Batnum/csharp/README.md +++ b/08_Batnum/csharp/README.md @@ -8,4 +8,3 @@ Functional changes from Original - handle edge condition for end game where the minimum draw amount is greater than the number of items remaining in the pile - Takes into account the width of the console - Mulilingual Support (English/French currently) - diff --git a/08_Batnum/java/src/BatNum.java b/08_Batnum/java/src/BatNum.java index 4211d74dd..5a9aa6407 100644 --- a/08_Batnum/java/src/BatNum.java +++ b/08_Batnum/java/src/BatNum.java @@ -289,4 +289,4 @@ private int getDelimitedValue(String text, int pos) { String[] tokens = text.split(","); return Integer.parseInt(tokens[pos]); } -} \ No newline at end of file +} diff --git a/08_Batnum/javascript/batnum.js b/08_Batnum/javascript/batnum.js index c7d25b78b..caf6056fe 100644 --- a/08_Batnum/javascript/batnum.js +++ b/08_Batnum/javascript/batnum.js @@ -12,10 +12,10 @@ function input() { var input_element; var input_str; - + return new Promise(function (resolve) { input_element = document.createElement("INPUT"); - + print("? "); input_element.setAttribute("type", "text"); input_element.setAttribute("length", "50"); diff --git a/08_Batnum/python/batnum.py b/08_Batnum/python/batnum.py index 0f3473ed7..d7314578c 100644 --- a/08_Batnum/python/batnum.py +++ b/08_Batnum/python/batnum.py @@ -1,19 +1,22 @@ from enum import Enum + class WinOptions(Enum): Undefined = 0 TakeLast = 1 AvoidLast = 2 + class StartOptions(Enum): Undefined = 0 ComputerFirst = 1 PlayerFirst = 2 + def PrintIntro(): - '''Prints out the introduction and rules for the game.''' - print("BATNUM".rjust(33, ' ')) - print("CREATIVE COMPUTING MORRISSTOWN, NEW JERSEY".rjust(15, ' ')) + """Prints out the introduction and rules for the game.""" + print("BATNUM".rjust(33, " ")) + print("CREATIVE COMPUTING MORRISSTOWN, NEW JERSEY".rjust(15, " ")) print() print() print() @@ -21,7 +24,7 @@ def PrintIntro(): print("COMPUTER IS YOUR OPPONENT.") print() print("THE GAME STARTS WITH AN ASSUMED PILE OF OBJECTS. YOU") - print( "AND YOUR OPPONENT ALTERNATELY REMOVE OBJECTS FROM THE PILE.") + print("AND YOUR OPPONENT ALTERNATELY REMOVE OBJECTS FROM THE PILE.") print("WINNING IS DEFINED IN ADVANCE AS TAKING THE LAST OBJECT OR") print("NOT. YOU CAN ALSO SPECIFY SOME OTHER BEGINNING CONDITIONS.") print("DON'T USE ZERO, HOWEVER, IN PLAYING THE GAME.") @@ -29,8 +32,9 @@ def PrintIntro(): print() return + def GetParams(): - '''This requests the necessary parameters to play the game. + """This requests the necessary parameters to play the game. Returns a set with the five game parameters: pileSize - the starting size of the object pile @@ -38,9 +42,9 @@ def GetParams(): maxSelect - maximum selection that can be made on each turn startOption - 1 if the computer is first or 2 if the player is first - winOption - 1 if the goal is to take the last object + winOption - 1 if the goal is to take the last object or 2 if the goal is to not take the last object - ''' + """ pileSize = 0 winOption = WinOptions.Undefined minSelect = 0 @@ -52,22 +56,25 @@ def GetParams(): while winOption == WinOptions.Undefined: winOption = int(input("ENTER WIN OPTION - 1 TO TAKE LAST, 2 TO AVOID LAST: ")) while minSelect < 1 or maxSelect < 1 or minSelect > maxSelect: - (minSelect, maxSelect) = [int(x) for x in input("ENTER MIN AND MAX ").split(' ')] + (minSelect, maxSelect) = ( + int(x) for x in input("ENTER MIN AND MAX ").split(" ") + ) while startOption == StartOptions.Undefined: startOption = int(input("ENTER START OPTION - 1 COMPUTER FIRST, 2 YOU FIRST ")) return (pileSize, minSelect, maxSelect, startOption, winOption) + def PlayerMove(pileSize, minSelect, maxSelect, startOption, winOption): - '''This handles the player's turn - asking the player how many objects + """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 pileSize.''' + + Returns a boolean indicating whether the game is over and the new pileSize.""" playerDone = False while not playerDone: playerMove = int(input("YOUR MOVE ")) if playerMove == 0: - print ("I TOLD YOU NOT TO USE ZERO! COMPUTER WINS BY FORFEIT.") + print("I TOLD YOU NOT TO USE ZERO! COMPUTER WINS BY FORFEIT.") return (True, pileSize) if playerMove > maxSelect or playerMove < minSelect: print("ILLEGAL MOVE, REENTER IT") @@ -82,10 +89,11 @@ def PlayerMove(pileSize, minSelect, maxSelect, startOption, winOption): return (True, pileSize) return (False, pileSize) + def ComputerPick(pileSize, minSelect, maxSelect, startOption, winOption): - '''This handles the logic to determine how many objects the computer + """This handles the logic to determine how many objects the computer will select on its turn. - ''' + """ q = pileSize - 1 if winOption == WinOptions.AvoidLast else pileSize c = minSelect + maxSelect computerPick = q - (c * int(q / c)) @@ -95,24 +103,25 @@ def ComputerPick(pileSize, minSelect, maxSelect, startOption, winOption): computerPick = maxSelect return computerPick + def ComputerMove(pileSize, minSelect, maxSelect, startOption, winOption): - '''This handles the computer's turn - first checking for the various + """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 pileSize.''' + + Returns a boolean indicating whether the game is over and the new pileSize.""" # First, check for win conditions on this move # In this case, we win by taking the last object and # the remaining pile is less than max select # so the computer can grab them all and win if winOption == WinOptions.TakeLast and pileSize <= maxSelect: - print (f"COMPUTER TAKES {pileSize} AND WINS.") + print(f"COMPUTER TAKES {pileSize} AND WINS.") return (True, pileSize) # In this case, we lose by taking the last object and # the remaining pile is less than minsize and the computer # has to take all of them. if winOption == WinOptions.AvoidLast and pileSize <= minSelect: - print (f"COMPUTER TAKES {minSelect} AND LOSES.") + print(f"COMPUTER TAKES {minSelect} AND LOSES.") return (True, pileSize) # Otherwise, we determine how many the computer selects @@ -121,10 +130,11 @@ def ComputerMove(pileSize, minSelect, maxSelect, startOption, winOption): print(f"COMPUTER TAKES {currSel} AND LEAVES {pileSize}") return (False, pileSize) + def PlayGame(pileSize, minSelect, maxSelect, startOption, winOption): - '''This is the main game loop - repeating each turn until one + """This is the main game loop - repeating each turn until one of the win/lose conditions is met. - ''' + """ gameOver = False # playersTurn is a boolean keeping track of whether it's the # player's or computer's turn @@ -132,18 +142,23 @@ def PlayGame(pileSize, minSelect, maxSelect, startOption, winOption): while not gameOver: if playersTurn: - (gameOver, pileSize) = PlayerMove(pileSize, minSelect, maxSelect, startOption, winOption) + (gameOver, pileSize) = PlayerMove( + pileSize, minSelect, maxSelect, startOption, winOption + ) playersTurn = False if gameOver: return if not playersTurn: - (gameOver, pileSize) = ComputerMove(pileSize, minSelect, maxSelect, startOption, winOption) + (gameOver, pileSize) = ComputerMove( + pileSize, minSelect, maxSelect, startOption, winOption + ) playersTurn = True - + return + if __name__ == "__main__": - + pileSize = 0 minSelect = 0 maxSelect = 0 diff --git a/09_Battle/csharp/Game.cs b/09_Battle/csharp/Game.cs index c74a48cac..1ee9ceb5d 100644 --- a/09_Battle/csharp/Game.cs +++ b/09_Battle/csharp/Game.cs @@ -305,7 +305,7 @@ public void UserInteraction() var shipType = (shipNum - 1) / 2 + 1; lost[shipType] = lost[shipType] + 1; - + Print("AND YOU SUNK IT. HURRAH FOR THE GOOD GUYS."); Print("SO FAR, THE BAD GUYS HAVE LOST"); Write($"{lost[1]} DESTROYER(S), {lost[2]} CRUISER(S), AND "); diff --git a/09_Battle/java/Battle.java b/09_Battle/java/Battle.java index c0b279064..3b58ada62 100644 --- a/09_Battle/java/Battle.java +++ b/09_Battle/java/Battle.java @@ -155,7 +155,7 @@ public void play() { System.out.println("\n****************************\n"); } - } + } } } } diff --git a/09_Battle/java/Input.java b/09_Battle/java/Input.java index ee87465f9..2b905601d 100644 --- a/09_Battle/java/Input.java +++ b/09_Battle/java/Input.java @@ -38,10 +38,10 @@ public boolean readCoordinates() throws IOException { System.out.println("Need two coordinates separated by ','"); continue; } - + coords = new int[2]; boolean error = false; - // each field should contain an integer from 1 to the size of the sea + // each field should contain an integer from 1 to the size of the sea try { for (int c = 0 ; c < 2; ++c ) { int val = Integer.parseInt(fields[c].strip()); diff --git a/09_Battle/java/Sea.java b/09_Battle/java/Sea.java index f0c31facd..fd6820aba 100644 --- a/09_Battle/java/Sea.java +++ b/09_Battle/java/Sea.java @@ -1,4 +1,4 @@ -// Track the content of the sea +// Track the content of the sea class Sea { // the sea is a square grid of tiles. It is a one-dimensional array, and this // class maps x and y coordinates to an array index @@ -20,11 +20,11 @@ public Sea(int make_size) { public String encodedDump() { StringBuilder out = new StringBuilder(); for (int x = 0; x < size; ++x) { - for (int y = 0; y < size; ++y) + for (int y = 0; y < size; ++y) out.append(Integer.toString(get(x, y))); out.append('\n'); } - return out.toString(); + return out.toString(); } /* return true if x,y is in the sea and empty diff --git a/09_Battle/java/Ship.java b/09_Battle/java/Ship.java index 23605e5c5..86712db8d 100644 --- a/09_Battle/java/Ship.java +++ b/09_Battle/java/Ship.java @@ -17,7 +17,7 @@ class Ship { private boolean placed; // whether this ship is in the sea yet private boolean sunk; // whether this ship has been sunk private ArrayList hits; // which tiles of the ship have been hit - + private int startX; // starting position coordinates private int startY; private int orientX; // x and y deltas from each tile occupied to the next diff --git a/09_Battle/javascript/battle.js b/09_Battle/javascript/battle.js index 3adcfaba4..8ffb7fa08 100644 --- a/09_Battle/javascript/battle.js +++ b/09_Battle/javascript/battle.js @@ -12,10 +12,10 @@ function input() { var input_element; var input_str; - + return new Promise(function (resolve) { input_element = document.createElement("INPUT"); - + print("? "); input_element.setAttribute("type", "text"); input_element.setAttribute("length", "50"); diff --git a/09_Battle/python/battle.py b/09_Battle/python/battle.py index d9449b771..93d24fe9d 100644 --- a/09_Battle/python/battle.py +++ b/09_Battle/python/battle.py @@ -40,8 +40,9 @@ def place_ship(sea: SeaType, size: int, code: int) -> None: point = add_vector(point, vector) points.append(point) - if (not all([is_within_sea(point, sea) for point in points]) or - any([value_at(point, sea) for point in points])): + if not all([is_within_sea(point, sea) for point in points]) or any( + [value_at(point, sea) for point in points] + ): # ship out of bounds or crosses other ship, trying again continue @@ -54,7 +55,7 @@ def place_ship(sea: SeaType, size: int, code: int) -> None: def print_encoded_sea(sea: SeaType) -> None: for x in range(len(sea)): - print(' '.join([str(sea[y][x]) for y in range(len(sea) - 1, -1, -1)])) + print(" ".join([str(sea[y][x]) for y in range(len(sea) - 1, -1, -1)])) def is_within_sea(point: PointType, sea: SeaType) -> bool: @@ -70,18 +71,18 @@ def count_sunk(sea: SeaType, *codes: int) -> int: def value_at(point: PointType, sea: SeaType) -> int: - return sea[point[1] - 1][point[0] -1] + return sea[point[1] - 1][point[0] - 1] def set_value_at(value: int, point: PointType, sea: SeaType) -> None: - sea[point[1] - 1][point[0] -1] = value + sea[point[1] - 1][point[0] - 1] = value def get_next_target(sea: SeaType) -> PointType: while True: try: - guess = input('? ') - point = guess.split(',') + guess = input("? ") + point = guess.split(",") if len(point) != 2: raise ValueError() @@ -93,7 +94,9 @@ def get_next_target(sea: SeaType) -> PointType: return point except ValueError: - print(f'INVALID. SPECIFY TWO NUMBERS FROM 1 TO {len(sea)}, SEPARATED BY A COMMA.') + print( + f"INVALID. SPECIFY TWO NUMBERS FROM 1 TO {len(sea)}, SEPARATED BY A COMMA." + ) def setup_ships(sea: SeaType): @@ -106,23 +109,27 @@ def setup_ships(sea: SeaType): def main() -> None: - sea = tuple(([0 for _ in range(SEA_WIDTH)] for _ in range(SEA_WIDTH))) + sea = tuple([0 for _ in range(SEA_WIDTH)] for _ in range(SEA_WIDTH)) setup_ships(sea) - print(f''' + print( + f""" BATTLE CREATIVE COMPUTING MORRISTOWN, NEW JERSEY THE FOLLOWING CODE OF THE BAD GUYS' FLEET DISPOSITION HAS BEEN CAPTURED BUT NOT DECODED: -''') +""" + ) print_encoded_sea(sea) - print(''' + print( + """ DE-CODE IT AND USE IT IF YOU CAN BUT KEEP THE DE-CODING METHOD A SECRET. -START GAME''') +START GAME""" + ) splashes = 0 hits = 0 @@ -131,33 +138,39 @@ def main() -> None: target_value = value_at(target, sea) if target_value < 0: - print(f'YOU ALREADY PUT A HOLE IN SHIP NUMBER {abs(target_value)} AT THAT POINT.') + print( + f"YOU ALREADY PUT A HOLE IN SHIP NUMBER {abs(target_value)} AT THAT POINT." + ) if target_value <= 0: - print('SPLASH! TRY AGAIN.') + print("SPLASH! TRY AGAIN.") splashes += 1 continue - print(f'A DIRECT HIT ON SHIP NUMBER {target_value}') + print(f"A DIRECT HIT ON SHIP NUMBER {target_value}") hits += 1 set_value_at(-target_value, target, sea) if not has_ship(sea, target_value): - print('AND YOU SUNK IT. HURRAH FOR THE GOOD GUYS.') - print('SO FAR, THE BAD GUYS HAVE LOST') - print(f'{count_sunk(sea, 1, 2)} DESTROYER(S),', - f'{count_sunk(sea, 3, 4)} CRUISER(S),', - f'AND {count_sunk(sea, 5, 6)} AIRCRAFT CARRIER(S).') + print("AND YOU SUNK IT. HURRAH FOR THE GOOD GUYS.") + print("SO FAR, THE BAD GUYS HAVE LOST") + print( + f"{count_sunk(sea, 1, 2)} DESTROYER(S),", + f"{count_sunk(sea, 3, 4)} CRUISER(S),", + f"AND {count_sunk(sea, 5, 6)} AIRCRAFT CARRIER(S).", + ) if any(has_ship(sea, code) for code in range(1, 7)): - print(f'YOUR CURRENT SPLASH/HIT RATIO IS {splashes}/{hits}') + print(f"YOUR CURRENT SPLASH/HIT RATIO IS {splashes}/{hits}") continue - print('YOU HAVE TOTALLY WIPED OUT THE BAD GUYS\' FLEET ' - f'WITH A FINAL SPLASH/HIT RATIO OF {splashes}/{hits}') + print( + "YOU HAVE TOTALLY WIPED OUT THE BAD GUYS' FLEET " + f"WITH A FINAL SPLASH/HIT RATIO OF {splashes}/{hits}" + ) if not splashes: - print('CONGRATULATIONS -- A DIRECT HIT EVERY TIME.') + print("CONGRATULATIONS -- A DIRECT HIT EVERY TIME.") print("\n****************************") break diff --git a/09_Battle/python/battle_oo.py b/09_Battle/python/battle_oo.py index dc35efa69..468e9dbe8 100644 --- a/09_Battle/python/battle_oo.py +++ b/09_Battle/python/battle_oo.py @@ -2,7 +2,6 @@ from dataclasses import dataclass from random import randrange - DESTROYER_LENGTH = 2 CRUISER_LENGTH = 3 AIRCRAFT_CARRIER_LENGTH = 4 @@ -14,10 +13,10 @@ class Point: y: int @classmethod - def random(cls, start: int, stop: int) -> 'Point': + def random(cls, start: int, stop: int) -> "Point": return Point(randrange(start, stop), randrange(start, stop)) - def __add__(self, vector: 'Vector') -> 'Point': + def __add__(self, vector: "Vector") -> "Point": return Point(self.x + vector.x, self.y + vector.y) @@ -27,10 +26,10 @@ class Vector: y: int @staticmethod - def random() -> 'Vector': + def random() -> "Vector": return Vector(randrange(-1, 2, 2), randrange(-1, 2, 2)) - def __mul__(self, factor: int) -> 'Vector': + def __mul__(self, factor: int) -> "Vector": return Vector(self.x * factor, self.y * factor) @@ -38,25 +37,25 @@ class Sea: WIDTH = 6 def __init__(self): - self._graph = tuple(([0 for _ in range(self.WIDTH)] for _ in range(self.WIDTH))) + self._graph = tuple([0 for _ in range(self.WIDTH)] for _ in range(self.WIDTH)) def _validate_item_indices(self, point: Point) -> None: if not isinstance(point, Point): - raise ValueError(f'Sea indices must be Points, not {type(point).__name__}') + raise ValueError(f"Sea indices must be Points, not {type(point).__name__}") - if not((1 <= point.x <= self.WIDTH) and (1 <= point.y <= self.WIDTH)): - raise IndexError('Sea index out of range') + if not ((1 <= point.x <= self.WIDTH) and (1 <= point.y <= self.WIDTH)): + raise IndexError("Sea index out of range") # Allows us to get the value using a point as a key, for example, `sea[Point(3,2)]` def __getitem__(self, point: Point) -> int: self._validate_item_indices(point) - return self._graph[point.y - 1][point.x -1] + return self._graph[point.y - 1][point.x - 1] # Allows us to get the value using a point as a key, for example, `sea[Point(3,2)] = 3` def __setitem__(self, point: Point, value: int) -> None: self._validate_item_indices(point) - self._graph[point.y - 1][point.x -1] = value + self._graph[point.y - 1][point.x - 1] = value # Allows us to check if a point exists in the sea for example, `if Point(3,2) in sea:` def __contains__(self, point: Point) -> bool: @@ -70,9 +69,14 @@ def __contains__(self, point: Point) -> bool: # Redefines how python will render this object when asked as a str def __str__(self): # Display it encoded - return "\n".join([' '.join([str(self._graph[y][x]) - for y in range(self.WIDTH - 1, -1, -1)]) - for x in range(self.WIDTH)]) + return "\n".join( + [ + " ".join( + [str(self._graph[y][x]) for y in range(self.WIDTH - 1, -1, -1)] + ) + for x in range(self.WIDTH) + ] + ) def has_ship(self, ship_code: int) -> bool: return any(ship_code in row for row in self._graph) @@ -96,8 +100,8 @@ def __init__(self) -> None: def _next_target(self) -> Point: while True: try: - guess = input('? ') - coordinates = guess.split(',') + guess = input("? ") + coordinates = guess.split(",") if len(coordinates) != 2: raise ValueError() @@ -109,11 +113,13 @@ def _next_target(self) -> Point: return point except ValueError: - print(f'INVALID. SPECIFY TWO NUMBERS FROM 1 TO {Sea.WIDTH}, SEPARATED BY A COMMA.') + print( + f"INVALID. SPECIFY TWO NUMBERS FROM 1 TO {Sea.WIDTH}, SEPARATED BY A COMMA." + ) @property def splash_hit_ratio(self) -> str: - return f'{self.splashes}/{self.hits}' + return f"{self.splashes}/{self.hits}" @property def _is_finished(self) -> bool: @@ -126,8 +132,10 @@ def place_ship(self, size: int, ship_code: int) -> None: # Get potential ship points points = [start + vector * i for i in range(size)] - if not (all([point in self.sea for point in points]) and - not any([self.sea[point] for point in points])): + if not ( + all([point in self.sea for point in points]) + and not any([self.sea[point] for point in points]) + ): # ship out of bounds or crosses other ship, trying again continue @@ -137,53 +145,59 @@ def place_ship(self, size: int, ship_code: int) -> None: break - def loop(self): while True: target = self._next_target() target_value = self.sea[target] if target_value < 0: - print(f'YOU ALREADY PUT A HOLE IN SHIP NUMBER {abs(target_value)} AT THAT POINT.') + print( + f"YOU ALREADY PUT A HOLE IN SHIP NUMBER {abs(target_value)} AT THAT POINT." + ) if target_value <= 0: - print('SPLASH! TRY AGAIN.') + print("SPLASH! TRY AGAIN.") self.splashes += 1 continue - print(f'A DIRECT HIT ON SHIP NUMBER {target_value}') + print(f"A DIRECT HIT ON SHIP NUMBER {target_value}") self.hits += 1 self.sea[target] = -target_value if not self.sea.has_ship(target_value): - print('AND YOU SUNK IT. HURRAH FOR THE GOOD GUYS.') + print("AND YOU SUNK IT. HURRAH FOR THE GOOD GUYS.") self._display_sunk_report() if self._is_finished: self._display_game_end() break - print(f'YOUR CURRENT SPLASH/HIT RATIO IS {self.splash_hit_ratio}') + print(f"YOUR CURRENT SPLASH/HIT RATIO IS {self.splash_hit_ratio}") def _display_sunk_report(self): - print('SO FAR, THE BAD GUYS HAVE LOST', - f'{self.sea.count_sunk(1, 2)} DESTROYER(S),', - f'{self.sea.count_sunk(3, 4)} CRUISER(S),', - f'AND {self.sea.count_sunk(5, 6)} AIRCRAFT CARRIER(S).') + print( + "SO FAR, THE BAD GUYS HAVE LOST", + f"{self.sea.count_sunk(1, 2)} DESTROYER(S),", + f"{self.sea.count_sunk(3, 4)} CRUISER(S),", + f"AND {self.sea.count_sunk(5, 6)} AIRCRAFT CARRIER(S).", + ) def _display_game_end(self): - print('YOU HAVE TOTALLY WIPED OUT THE BAD GUYS\' FLEET ' - f'WITH A FINAL SPLASH/HIT RATIO OF {self.splash_hit_ratio}') + print( + "YOU HAVE TOTALLY WIPED OUT THE BAD GUYS' FLEET " + f"WITH A FINAL SPLASH/HIT RATIO OF {self.splash_hit_ratio}" + ) if not self.splashes: - print('CONGRATULATIONS -- A DIRECT HIT EVERY TIME.') + print("CONGRATULATIONS -- A DIRECT HIT EVERY TIME.") print("\n****************************") def main() -> None: game = Battle() - print(f''' + print( + f""" BATTLE CREATIVE COMPUTING MORRISTOWN, NEW JERSEY @@ -195,7 +209,8 @@ def main() -> None: DE-CODE IT AND USE IT IF YOU CAN BUT KEEP THE DE-CODING METHOD A SECRET. -START GAME''') +START GAME""" + ) game.loop() diff --git a/10_Blackjack/blackjack.bas b/10_Blackjack/blackjack.bas index 5274d31fa..121c6502c 100644 --- a/10_Blackjack/blackjack.bas +++ b/10_Blackjack/blackjack.bas @@ -289,7 +289,7 @@ 3125 PRINT "---TOTAL IS";AA 3130 PRINT 3140 REM--TALLY THE RESULT -3150 REM +3150 REM 3160 Z$="LOSES PUSHES WINS " 3165 PRINT 3170 FOR I=1 TO N diff --git a/10_Blackjack/javascript/blackjack.js b/10_Blackjack/javascript/blackjack.js index 16f5a3434..21e11b9ef 100644 --- a/10_Blackjack/javascript/blackjack.js +++ b/10_Blackjack/javascript/blackjack.js @@ -12,10 +12,10 @@ function input() { var input_element; var input_str; - + return new Promise(function (resolve) { input_element = document.createElement("INPUT"); - + print("? "); input_element.setAttribute("type", "text"); input_element.setAttribute("length", "50"); @@ -217,7 +217,7 @@ async function main() // --ta[i] IS THE TOTAL FOR PLAYER I, sa[i] IS THE TOTAL THIS HAND FOR // --PLAYER I, ba[i] IS TH BET FOR HAND I // --ra[i] IS THE LENGTH OF pa[I,*] - + // --Program starts here // --Initialize for (i = 1; i <= 15; i++) @@ -416,7 +416,7 @@ async function main() if (pa[i][1] != 1) { // --Now play the two hands do { - + print("HAND " + (i > d1 ? 2 : 1) + " "); h1 = 5; while (1) { @@ -472,7 +472,7 @@ async function main() if (aa <= 16) { print("DRAWS"); do { - + x = get_card(); alt_card_print(x); add_card_to_row(i, x); diff --git a/10_Blackjack/rust/Cargo.toml b/10_Blackjack/rust/Cargo.toml index 1c2935d47..3b1d02f52 100644 --- a/10_Blackjack/rust/Cargo.toml +++ b/10_Blackjack/rust/Cargo.toml @@ -6,4 +6,4 @@ edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] -rand = "0.8.5" \ No newline at end of file +rand = "0.8.5" diff --git a/10_Blackjack/rust/README.md b/10_Blackjack/rust/README.md index f84e546c2..7e85f9a15 100644 --- a/10_Blackjack/rust/README.md +++ b/10_Blackjack/rust/README.md @@ -1,3 +1,3 @@ Original source downloaded [from Vintage Basic](http://www.vintage-basic.net/games.html) -Conversion to [Rust](https://www.rust-lang.org/) by Anthony Rubick [AnthonyMichaelTDM](https://github.com/AnthonyMichaelTDM) \ No newline at end of file +Conversion to [Rust](https://www.rust-lang.org/) by Anthony Rubick [AnthonyMichaelTDM](https://github.com/AnthonyMichaelTDM) diff --git a/10_Blackjack/rust/src/main.rs b/10_Blackjack/rust/src/main.rs index e3a0a4594..e649f3562 100644 --- a/10_Blackjack/rust/src/main.rs +++ b/10_Blackjack/rust/src/main.rs @@ -3,7 +3,7 @@ use std::{io, io::{stdout, Write}}; /** * todo list: - * + * * allow splitting */ @@ -89,9 +89,9 @@ impl<'a> HAND<'a> { fn new() -> HAND<'a> { return HAND { cards: Vec::new()}; } - + /** - * add a passed card to this hand + * add a passed card to this hand */ fn add_card(&mut self, card: CARD<'a>) { self.cards.push(card); @@ -136,7 +136,7 @@ impl<'a> DECKS<'a> { //returns a number of full decks of 52 cards, shuffles them //DATA let mut deck = DECKS{deck: Vec::new(), discard_pile: Vec::new()}; - let number_of_decks = 3; + let number_of_decks = 3; //fill deck for _n in 0..number_of_decks { //fill deck with number_of_decks decks worth of cards @@ -223,7 +223,7 @@ impl<'a> PLAYER<'a> { /** * returns a string of the players hand - * + * * if player is a dealer, returns the first card in the hand followed by *'s for every other card * if player is a player, returns every card and the total */ @@ -245,7 +245,7 @@ impl<'a> PLAYER<'a> { match &self.player_type { &PlayerType::Dealer => { //if this is a dealer return format!( - "{}*",//message + "{}*",//message { //*'s for other cards let mut s:String = String::new(); let mut cards_in_hand = self.hand.cards.iter(); @@ -274,7 +274,7 @@ impl<'a> PLAYER<'a> { } } - /** + /** * get the players 'play' */ fn get_play(&self) -> Play { @@ -283,7 +283,7 @@ impl<'a> PLAYER<'a> { if it's a dealer, use an algorithm to determine the play if it's a player, ask user for input */ - match &self.player_type { + match &self.player_type { &PlayerType::Dealer => { if self.hand.get_total() > 16 { // if total value of hand is greater than 16, stand return Play::Stand; @@ -374,7 +374,7 @@ impl<'a> GAME<'a> { let scores; let game = self.games_played; //save it here so we don't have borrowing issues let mut player_hands_message: String = String::new();//cache it here so we don't have borrowing issues - + //deal cards to each player for _i in 0..2 { // do this twice //draw card for each player @@ -384,7 +384,7 @@ impl<'a> GAME<'a> { //get everyones bets self.players.iter_mut().for_each(|player| player.get_bet()); scores = self.stats_as_string(); //save it here so we don't have borrowing issues later - + //play game for each player for player in self.players.iter_mut() { //turn loop, ends when player finishes their turn @@ -436,7 +436,7 @@ impl<'a> GAME<'a> { println!("\t{}", play.to_string()); //double their balance if there's enough money, othewise go all-in - if player.bet * 2 < player.balance { + if player.bet * 2 < player.balance { player.bet *= 2; } else { @@ -450,7 +450,7 @@ impl<'a> GAME<'a> { }, } } - + //add player to score cache thing player_hands_message += format!("{} Hand:\t{}\n", player.get_name(), player.hand_as_string(true)).as_str(); } @@ -473,7 +473,7 @@ impl<'a> GAME<'a> { print!("{} ", x.get_name());//print name x.wins += 1;//increment their wins }); - if num_winners > 1 {println!("all tie with {}\n\n\n", top_score);} + if num_winners > 1 {println!("all tie with {}\n\n\n", top_score);} else {println!("wins with {}!\n\n\n",top_score);} //handle bets @@ -503,7 +503,7 @@ fn main() { //print welcome message welcome(); - //create game + //create game game = GAME::new( get_number_from_user_input("How many players should there be (at least 1)?", 1, 7) ); //game loop, play game until user wants to stop @@ -527,7 +527,7 @@ fn welcome() { //welcome message print!(" BLACK JACK - CREATIVE COMPUTING MORRISTOWN, NEW JERSEY + CREATIVE COMPUTING MORRISTOWN, NEW JERSEY \n\n"); } @@ -551,7 +551,7 @@ fn instructions() { NUMBER OF PLAYERS NOTE:'/' (splitting) is not currently implemented, and does nothing - + PRESS ENTER TO CONTINUE "); io::stdin().read_line(&mut String::new()).expect("Failed to read line"); @@ -578,9 +578,9 @@ fn get_number_from_user_input(prompt: &str, min:usize, max:usize) -> usize { if i < min || i > max { //input out of desired range println!("INPUT OUT OF VALID RANGE. TRY AGAIN. {}-{}",min,max); continue; // run the loop again - } + } else { - break i;// this escapes the loop, returning i + break i;// this escapes the loop, returning i } }, Err(e) => { @@ -613,9 +613,9 @@ fn get_char_from_user_input(prompt: &str, valid_results: &Vec) -> char { if !valid_results.contains(&i) { //input out of desired range println!("INPUT IS NOT VALID CHARACTER. TRY AGAIN."); continue; // run the loop again - } + } else { - break i;// this escapes the loop, returning i + break i;// this escapes the loop, returning i } }, None => { diff --git a/11_Bombardment/csharp/Bombardment.cs b/11_Bombardment/csharp/Bombardment.cs index bcbdcc261..dcaeb86e7 100644 --- a/11_Bombardment/csharp/Bombardment.cs +++ b/11_Bombardment/csharp/Bombardment.cs @@ -18,7 +18,7 @@ internal class Bombardment private List computerPositions = new List(); private List playerPositions = new List(); private List computerGuesses = new List(); - + private void PrintStartingMessage() { Console.WriteLine("{0}BOMBARDMENT", new string(' ', 33)); @@ -26,7 +26,7 @@ private void PrintStartingMessage() Console.WriteLine(); Console.WriteLine(); Console.WriteLine(); - + Console.WriteLine("YOU ARE ON A BATTLEFIELD WITH 4 PLATOONS AND YOU"); Console.WriteLine("HAVE 25 OUTPOSTS AVAILABLE WHERE THEY MAY BE PLACED."); Console.WriteLine("YOU CAN ONLY PLACE ONE PLATOON AT ANY ONE OUTPOST."); @@ -51,9 +51,9 @@ private void PrintStartingMessage() { // The token replacement can be padded by using the format {tokenPosition, padding} // Negative values for the padding cause the output to be left-aligned. - Console.WriteLine("{0,-3}{1,-3}{2,-3}{3,-3}{4,-3}", i, i + 1, i + 2, i + 3, i + 4); + Console.WriteLine("{0,-3}{1,-3}{2,-3}{3,-3}{4,-3}", i, i + 1, i + 2, i + 3, i + 4); } - + Console.WriteLine("\n"); } diff --git a/11_Bombardment/java/src/Bombardment.java b/11_Bombardment/java/src/Bombardment.java index 1dede841c..1657913c2 100644 --- a/11_Bombardment/java/src/Bombardment.java +++ b/11_Bombardment/java/src/Bombardment.java @@ -366,4 +366,4 @@ private int randomNumber() { return (int) (Math.random() * (MAX_GRID_SIZE) + 1); } -} \ No newline at end of file +} diff --git a/11_Bombardment/javascript/bombardment.js b/11_Bombardment/javascript/bombardment.js index 3cd0a5d7d..6db01df20 100644 --- a/11_Bombardment/javascript/bombardment.js +++ b/11_Bombardment/javascript/bombardment.js @@ -12,10 +12,10 @@ function input() { var input_element; var input_str; - + return new Promise(function (resolve) { input_element = document.createElement("INPUT"); - + print("? "); input_element.setAttribute("type", "text"); input_element.setAttribute("length", "50"); @@ -103,7 +103,7 @@ async function main() y = parseInt(await input()); } while (y < 0 || y > 25) ; if (y == c || y == d || y == e || y == f) { - + // The original game has a bug. You can shoot the same outpost // several times. This solves it. if (y == c) diff --git a/11_Bombardment/perl/bombardment.pl b/11_Bombardment/perl/bombardment.pl index 0641102e2..158c34938 100644 --- a/11_Bombardment/perl/bombardment.pl +++ b/11_Bombardment/perl/bombardment.pl @@ -54,7 +54,7 @@ sub computer_turn { else { print "YOU'RE DEAD. YOUR LAST OUTPOST WAS AT $target. HA, HA, HA.\nBETTER LUCK NEXT TIME\n"; } - + } else { print "I MISSED YOU, YOU DIRTY RAT. I PICKED $target. YOUR TURN:\n"; diff --git a/11_Bombardment/python/bombardment.py b/11_Bombardment/python/bombardment.py index a16113e79..47ab0d7da 100755 --- a/11_Bombardment/python/bombardment.py +++ b/11_Bombardment/python/bombardment.py @@ -2,6 +2,7 @@ import random from functools import partial + def display_intro(): print("" * 33 + "BOMBARDMENT") print("" * 15 + " CREATIVE COMPUTING MORRISTOWN, NEW JERSEY") @@ -25,7 +26,7 @@ def display_intro(): def display_field(): for row in range(5): initial = row * 5 + 1 - print('\t'.join([str(initial + column) for column in range(5)])) + print("\t".join([str(initial + column) for column in range(5)])) print("\n" * 9) @@ -35,7 +36,7 @@ def positions_list(): def generate_enemy_positions(): - """ Randomly choose 4 'positions' out of a range of 1 to 25 """ + """Randomly choose 4 'positions' out of a range of 1 to 25""" positions = positions_list() random.shuffle(positions) return set(positions[:4]) @@ -49,13 +50,13 @@ def prompt_for_player_positions(): while True: raw_positions = input("WHAT ARE YOUR FOUR POSITIONS? ") - positions = set(int(pos) for pos in raw_positions.split()) + positions = {int(pos) for pos in raw_positions.split()} # Verify user inputs (for example, if the player gives a # a position for 26, the enemy can never hit it) - if (len(positions) != 4): + if len(positions) != 4: print("PLEASE ENTER 4 UNIQUE POSITIONS\n") continue - elif (any(not is_valid_position(pos) for pos in positions)): + elif any(not is_valid_position(pos) for pos in positions): print("ALL POSITIONS MUST RANGE (1-25)\n") continue else: @@ -74,7 +75,7 @@ def prompt_player_for_target(): def attack(target, positions, hit_message, miss_message, progress_messages): - """ Performs attack procedure returning True if we are to continue. """ + """Performs attack procedure returning True if we are to continue.""" if target in positions: print(hit_message.format(target)) @@ -87,9 +88,9 @@ def attack(target, positions, hit_message, miss_message, progress_messages): def init_enemy(): - """ Returns a closure analogous to prompt_player_for_target. Will - choose from a unique sequence of positions to avoid picking the - same position twice. """ + """Returns a closure analogous to prompt_player_for_target. Will + choose from a unique sequence of positions to avoid picking the + same position twice.""" position_sequence = positions_list() random.shuffle(position_sequence) @@ -103,21 +104,19 @@ def choose(): # Messages correspond to outposts remaining (3, 2, 1, 0) PLAYER_PROGRESS_MESSAGES = ( - "YOU GOT ME, I'M GOING FAST. BUT I'LL GET YOU WHEN\n" - "MY TRANSISTO&S RECUP%RA*E!", + "YOU GOT ME, I'M GOING FAST. BUT I'LL GET YOU WHEN\n" "MY 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" - ) + "ONE DOWN, THREE TO GO.\n\n", +) ENEMY_PROGRESS_MESSAGES = ( - "YOU'RE DEAD. YOUR LAST OUTPOST WAS AT {}. HA, HA, HA.\n" - "BETTER LUCK NEXT TIME.", + "YOU'RE DEAD. YOUR LAST OUTPOST WAS AT {}. HA, HA, HA.\n" "BETTER 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", - ) +) def play(): @@ -128,22 +127,28 @@ def play(): player_positions = prompt_for_player_positions() # Build partial functions only requiring the target as input - player_attacks = partial(attack, - positions=enemy_positions, - hit_message="YOU GOT ONE OF MY OUTPOSTS!", - miss_message="HA, HA YOU MISSED. MY TURN NOW:\n\n", - progress_messages=PLAYER_PROGRESS_MESSAGES) - - enemy_attacks = partial(attack, - positions=player_positions, - hit_message="I GOT YOU. IT WON'T BE LONG NOW. POST {} WAS HIT.", - miss_message="I MISSED YOU, YOU DIRTY RAT. I PICKED {}. YOUR TURN:\n\n", - progress_messages=ENEMY_PROGRESS_MESSAGES) + player_attacks = partial( + attack, + positions=enemy_positions, + hit_message="YOU GOT ONE OF MY OUTPOSTS!", + miss_message="HA, HA YOU MISSED. MY TURN NOW:\n\n", + progress_messages=PLAYER_PROGRESS_MESSAGES, + ) + + enemy_attacks = partial( + attack, + positions=player_positions, + hit_message="I GOT YOU. IT WON'T BE LONG NOW. POST {} WAS HIT.", + miss_message="I MISSED YOU, YOU DIRTY RAT. I PICKED {}. YOUR TURN:\n\n", + progress_messages=ENEMY_PROGRESS_MESSAGES, + ) enemy_position_choice = init_enemy() # Play as long as both player_attacks and enemy_attacks allow to continue - while player_attacks(prompt_player_for_target()) and enemy_attacks(enemy_position_choice()): + while player_attacks(prompt_player_for_target()) and enemy_attacks( + enemy_position_choice() + ): pass diff --git a/12_Bombs_Away/bombsaway.bas b/12_Bombs_Away/bombsaway.bas index 38af3edfc..bbf61c8a3 100644 --- a/12_Bombs_Away/bombsaway.bas +++ b/12_Bombs_Away/bombsaway.bas @@ -35,7 +35,7 @@ 280 PRINT 285 INPUT "HOW MANY MISSIONS HAVE YOU FLOWN";D 290 IF D<160 THEN 300 -292 PRINT "MISSIONS, NOT MILES..." +292 PRINT "MISSIONS, NOT MILES..." 295 PRINT "150 MISSIONS IS HIGH EVEN FOR OLD-TIMERS." 297 PRINT "NOW THEN, "; : GOTO 285 300 PRINT:IF D<100 THEN 310 diff --git a/12_Bombs_Away/csharp/BombsAwayConsole/Program.cs b/12_Bombs_Away/csharp/BombsAwayConsole/Program.cs index 35728cfcc..04d9fed1a 100644 --- a/12_Bombs_Away/csharp/BombsAwayConsole/Program.cs +++ b/12_Bombs_Away/csharp/BombsAwayConsole/Program.cs @@ -23,4 +23,3 @@ bool UserWantsToPlayAgain(IUserInterface ui) return result; } - diff --git a/12_Bombs_Away/java/src/BombsAway.java b/12_Bombs_Away/java/src/BombsAway.java index 290b2c6d2..4f43d99bd 100644 --- a/12_Bombs_Away/java/src/BombsAway.java +++ b/12_Bombs_Away/java/src/BombsAway.java @@ -519,4 +519,4 @@ private double randomNumber(int range) { return (Math.random() * (range)); } -} \ No newline at end of file +} diff --git a/12_Bombs_Away/javascript/bombsaway.js b/12_Bombs_Away/javascript/bombsaway.js index 848318566..7fccf55b7 100644 --- a/12_Bombs_Away/javascript/bombsaway.js +++ b/12_Bombs_Away/javascript/bombsaway.js @@ -12,10 +12,10 @@ function input() { var input_element; var input_str; - + return new Promise(function (resolve) { input_element = document.createElement("INPUT"); - + print("? "); input_element.setAttribute("type", "text"); input_element.setAttribute("length", "50"); diff --git a/12_Bombs_Away/perl/bombsaway.pl b/12_Bombs_Away/perl/bombsaway.pl index 1b4989f66..9cd4b1bd2 100644 --- a/12_Bombs_Away/perl/bombsaway.pl +++ b/12_Bombs_Away/perl/bombsaway.pl @@ -155,7 +155,7 @@ ($question, @comments) # and $guns_hit_rate here because the original BASIC code did not reset # the associated variables (respectively T and S) at every mission, thus # leaking state from one mission to the following ones. - # + # # In particular, both are leaked to the Japan mission(s), and # $guns_hit_rate is leaked to future "multiple()" missions that have # missiles only. diff --git a/13_Bounce/java/Bounce.java b/13_Bounce/java/Bounce.java index 6d39daa27..ca7275a19 100644 --- a/13_Bounce/java/Bounce.java +++ b/13_Bounce/java/Bounce.java @@ -9,52 +9,52 @@ *

* Note: The idea was to create a version of the 1970's BASIC game in Java, without introducing * new features - no additional text, error checking, etc has been added. - * + * * Converted from BASIC to Java by Darren Cardenas. */ - -public class Bounce { + +public class Bounce { private final Scanner scan; // For user input - + public Bounce() { - + scan = new Scanner(System.in); - - } // End of constructor Bounce - public void play() { + } // End of constructor Bounce + + public void play() { showIntro(); startGame(); - - } // End of method play - private void showIntro() { - + } // End of method play + + private void showIntro() { + System.out.println(" ".repeat(32) + "BOUNCE"); System.out.println(" ".repeat(14) + "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY"); System.out.println("\n\n"); - + } // End of method showIntro - private void startGame() { + private void startGame() { double coefficient = 0; - double height = 0; + double height = 0; double timeIncrement = 0; double timeIndex = 0; double timeTotal = 0; - double velocity = 0; - + double velocity = 0; + double[] timeData = new double[21]; - + int heightInt = 0; int index = 0; int maxData = 0; - + String lineContent = ""; - + System.out.println("THIS SIMULATION LETS YOU SPECIFY THE INITIAL VELOCITY"); System.out.println("OF A BALL THROWN STRAIGHT UP, AND THE COEFFICIENT OF"); System.out.println("ELASTICITY OF THE BALL. PLEASE USE A DECIMAL FRACTION"); @@ -63,107 +63,107 @@ private void startGame() { System.out.println("YOU ALSO SPECIFY THE TIME INCREMENT TO BE USED IN"); System.out.println("'STROBING' THE BALL'S FLIGHT (TRY .1 INITIALLY)."); System.out.println(""); - + // Begin outer while loop while (true) { - + System.out.print("TIME INCREMENT (SEC)? "); timeIncrement = Double.parseDouble(scan.nextLine()); System.out.println(""); - + System.out.print("VELOCITY (FPS)? "); - velocity = Double.parseDouble(scan.nextLine()); + velocity = Double.parseDouble(scan.nextLine()); System.out.println(""); - + System.out.print("COEFFICIENT? "); - coefficient = Double.parseDouble(scan.nextLine()); + coefficient = Double.parseDouble(scan.nextLine()); System.out.println(""); System.out.println("FEET"); System.out.println(""); - + maxData = (int)(70 / (velocity / (16 * timeIncrement))); - - for (index = 1; index <= maxData; index++) { + + for (index = 1; index <= maxData; index++) { timeData[index] = velocity * Math.pow(coefficient, index - 1) / 16; } - + // Begin loop through all rows of y-axis data - for (heightInt = (int)(-16 * Math.pow(velocity / 32, 2) + Math.pow(velocity, 2) / 32 + 0.5) * 10; + for (heightInt = (int)(-16 * Math.pow(velocity / 32, 2) + Math.pow(velocity, 2) / 32 + 0.5) * 10; heightInt >= 0; heightInt -= 5) { height = heightInt / 10.0; lineContent = ""; - + if ((int)(Math.floor(height)) == height) { lineContent += " " + (int)(height) + " "; - } - - timeTotal = 0; - - for (index = 1; index <= maxData; index++) { - + } + + timeTotal = 0; + + for (index = 1; index <= maxData; index++) { + for (timeIndex = 0; timeIndex <= timeData[index]; timeIndex += timeIncrement) { - + timeTotal += timeIncrement; - if (Math.abs(height - (0.5 * (-32) * Math.pow(timeIndex, 2) + velocity + if (Math.abs(height - (0.5 * (-32) * Math.pow(timeIndex, 2) + velocity * Math.pow(coefficient, index - 1) * timeIndex)) <= 0.25) { - - while (lineContent.length() < (timeTotal / timeIncrement) - 1) { - lineContent += " "; - } - lineContent += "0"; - } + + while (lineContent.length() < (timeTotal / timeIncrement) - 1) { + lineContent += " "; + } + lineContent += "0"; + } } - + timeIndex = timeData[index + 1] / 2; - + if (-16 * Math.pow(timeIndex, 2) + velocity * Math.pow(coefficient, index - 1) * timeIndex < height) { - - break; - } - } - + + break; + } + } + System.out.println(lineContent); - + } // End loop through all rows of y-axis data lineContent = ""; - + // Show the x-axis for (index = 1; index <= (int)(timeTotal + 1) / timeIncrement + 1; index++) { - - lineContent += "."; + + lineContent += "."; } - + System.out.println(lineContent); - + lineContent = " 0"; - + for (index = 1; index <= (int)(timeTotal + 0.9995); index++) { - - while (lineContent.length() < (int)(index / timeIncrement)) { - lineContent += " "; - } - lineContent += index; + + while (lineContent.length() < (int)(index / timeIncrement)) { + lineContent += " "; + } + lineContent += index; } - + System.out.println(lineContent); - System.out.println(" ".repeat((int)((timeTotal + 1) / (2 * timeIncrement) - 3)) + "SECONDS"); - - } // End outer while loop + System.out.println(" ".repeat((int)((timeTotal + 1) / (2 * timeIncrement) - 3)) + "SECONDS"); + + } // End outer while loop + + } // End of method startGame - } // End of method startGame - public static void main(String[] args) { - + Bounce game = new Bounce(); game.play(); - + } // End of method main - + } // End of class Bounce diff --git a/13_Bounce/javascript/bounce.js b/13_Bounce/javascript/bounce.js index d9cac590f..177ff4ffa 100644 --- a/13_Bounce/javascript/bounce.js +++ b/13_Bounce/javascript/bounce.js @@ -12,10 +12,10 @@ function input() { var input_element; var input_str; - + return new Promise(function (resolve) { input_element = document.createElement("INPUT"); - + print("? "); input_element.setAttribute("type", "text"); input_element.setAttribute("length", "50"); diff --git a/13_Bounce/python/bounce.py b/13_Bounce/python/bounce.py index 3ab7411c5..d1658982d 100644 --- a/13_Bounce/python/bounce.py +++ b/13_Bounce/python/bounce.py @@ -61,7 +61,7 @@ def run_simulation(delta_t, v0, coeff_rest): t[i] = v0 * coeff_rest ** (i - 1) / 16 # Draw the trajectory of the bouncing ball, one slice of height at a time - h = int(-16 * (v0 / 32) ** 2 + v0 ** 2 / 32 + 0.5) + h = int(-16 * (v0 / 32) ** 2 + v0**2 / 32 + 0.5) while h >= 0: line = "" if int(h) == h: @@ -72,14 +72,14 @@ def run_simulation(delta_t, v0, coeff_rest): while tm <= t[i]: l += delta_t if ( - abs(h - (0.5 * (-32) * tm ** 2 + v0 * coeff_rest ** (i - 1) * tm)) + abs(h - (0.5 * (-32) * tm**2 + v0 * coeff_rest ** (i - 1) * tm)) <= 0.25 ): line = print_at_tab(line, int(l / delta_t), "0") tm += delta_t tm = t[i + 1] / 2 - if -16 * tm ** 2 + v0 * coeff_rest ** (i - 1) * tm < h: + if -16 * tm**2 + v0 * coeff_rest ** (i - 1) * tm < h: break print(line) h = h - 0.5 diff --git a/13_Bounce/ruby/bounce.rb b/13_Bounce/ruby/bounce.rb index e215a8971..6af0d4755 100644 --- a/13_Bounce/ruby/bounce.rb +++ b/13_Bounce/ruby/bounce.rb @@ -108,7 +108,7 @@ def plot_bouncing_ball(strobbing_time, v0, c) # skipped by line 98 plot_width += 1 if plotted_height == 0 } - + if heighest_position_in_next_bounce(time_in_bounce, v0, i, c) < plotted_height then # If we got no more ball positions at or above current height in the next bounce, # we can skip the rest of the bounces and move down to the next height to plot diff --git a/14_Bowling/bowling.bas b/14_Bowling/bowling.bas index 916c19389..a6732580e 100644 --- a/14_Bowling/bowling.bas +++ b/14_Bowling/bowling.bas @@ -18,7 +18,7 @@ 1440 PRINT "SCORES ." 1530 PRINT "FIRST OF ALL...HOW MANY ARE PLAYING"; 1620 INPUT R -1710 PRINT +1710 PRINT 1800 PRINT "VERY GOOD..." 1890 FOR I=1 TO 100: FOR J=1 TO 6: A(I,J)=0: NEXT J: NEXT I 1980 F=1 @@ -69,7 +69,7 @@ 6030 IF B<>1 OR D>=10 THEN 6210 6120 PRINT "ROLL YOUR 2ND BALL" 6210 REM ARK STORAGE OF THE SCORES -6300 PRINT +6300 PRINT 6390 A(F*P,B)=D 6480 IF B=2 THEN 7020 6570 B=2 @@ -85,15 +85,15 @@ 7380 FOR I=1 TO 10 7470 PRINT I; 7560 NEXT I -7650 PRINT +7650 PRINT 7740 FOR P=1 TO R 7830 FOR I=1 TO 3 7920 FOR J=1 TO 10 8010 PRINT A(J*P,I); 8100 NEXT J -8105 PRINT +8105 PRINT 8190 NEXT I -8280 PRINT +8280 PRINT 8370 NEXT P 8460 PRINT "DO YOU WANT ANOTHER GAME" 8550 INPUT A$ diff --git a/14_Bowling/csharp/Bowling.cs b/14_Bowling/csharp/Bowling.cs index 16ab067ef..98a8eb32d 100644 --- a/14_Bowling/csharp/Bowling.cs +++ b/14_Bowling/csharp/Bowling.cs @@ -33,7 +33,7 @@ private static void ShowBanner() Utility.PrintString(); } private static void MaybeShowInstructions() - { + { Utility.PrintString("THE INSTRUCTIONS (Y/N)"); if (Utility.InputString() == "N") return; Utility.PrintString("THE GAME OF BOWLING TAKES MIND AND SKILL.DURING THE GAME"); @@ -89,7 +89,7 @@ private void GameLoop() { Utility.PrintString("STRIKE!!!!!\a\a\a\a"); // No second roll - ball = 0; + ball = 0; gameResults[player].Results[frame].PinsBall2 = pinsDownAfterRoll; gameResults[player].Results[frame].Score = FrameResult.Points.Strike; } diff --git a/14_Bowling/java/Bowling.java b/14_Bowling/java/Bowling.java index 998f4fb3c..ced25e863 100644 --- a/14_Bowling/java/Bowling.java +++ b/14_Bowling/java/Bowling.java @@ -9,35 +9,35 @@ *

* Note: The idea was to create a version of the 1970's BASIC game in Java, without introducing * new features - no additional text, error checking, etc has been added. - * + * * Converted from BASIC to Java by Darren Cardenas. */ - -public class Bowling { - - private final Scanner scan; // For user input - + +public class Bowling { + + private final Scanner scan; // For user input + public Bowling() { - + scan = new Scanner(System.in); - - } // End of constructor Bowling + + } // End of constructor Bowling public void play() { - + showIntro(); startGame(); - - } // End of method play - + + } // End of method play + private static void showIntro() { - + System.out.println(" ".repeat(33) + "BOWL"); System.out.println(" ".repeat(14) + "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY"); System.out.println("\n\n"); - } // End of method showIntro - + } // End of method showIntro + private void startGame() { int ball = 0; @@ -45,234 +45,234 @@ private void startGame() { int frame = 0; int ii = 0; // Loop iterator int jj = 0; // Loop iterator - int kk = 0; // Loop iterator + int kk = 0; // Loop iterator int numPlayers = 0; int pinsDownBefore = 0; int pinsDownNow = 0; int player = 0; int randVal = 0; int result = 0; - + int[] pins = new int[16]; - + int[][] scores = new int[101][7]; - + String userResponse = ""; System.out.println("WELCOME TO THE ALLEY"); - System.out.println("BRING YOUR FRIENDS"); + System.out.println("BRING YOUR FRIENDS"); System.out.println("OKAY LET'S FIRST GET ACQUAINTED"); System.out.println(""); System.out.println("THE INSTRUCTIONS (Y/N)"); System.out.print("? "); - + userResponse = scan.nextLine(); - - if (userResponse.toUpperCase().equals("Y")) { + + if (userResponse.toUpperCase().equals("Y")) { printRules(); } - + System.out.print("FIRST OF ALL...HOW MANY ARE PLAYING? "); numPlayers = Integer.parseInt(scan.nextLine()); - - System.out.println(""); - System.out.println("VERY GOOD..."); + + System.out.println(""); + System.out.println("VERY GOOD..."); // Begin outer while loop while (true) { - - for (ii = 1; ii <= 100; ii++) { - for (jj = 1; jj <= 6; jj++) { - scores[ii][jj] = 0; - } + + for (ii = 1; ii <= 100; ii++) { + for (jj = 1; jj <= 6; jj++) { + scores[ii][jj] = 0; + } } - - frame = 1; + + frame = 1; // Begin frame while loop while (frame < 11) { // Begin loop through all players for (player = 1; player <= numPlayers; player++) { - + pinsDownBefore = 0; ball = 1; result = 0; - - for (ii = 1; ii <= 15; ii++) { - pins[ii] = 0; + + for (ii = 1; ii <= 15; ii++) { + pins[ii] = 0; } - + while (true) { - + // Ball generator using mod '15' system - + System.out.println("TYPE ROLL TO GET THE BALL GOING."); System.out.print("? "); scan.nextLine(); - + kk = 0; pinsDownNow = 0; - + for (ii = 1; ii <= 20; ii++) { - - randVal = (int)(Math.random() * 100) + 1; - + + randVal = (int)(Math.random() * 100) + 1; + for (jj = 1; jj <= 10; jj++) { - - if (randVal < 15 * jj) { + + if (randVal < 15 * jj) { break; - } - } - pins[15 * jj - randVal] = 1; + } + } + pins[15 * jj - randVal] = 1; } - + // Pin diagram - + System.out.println("PLAYER: " + player + " FRAME: " + frame + " BALL: " + ball); - + for (ii = 0; ii <= 3; ii++) { - + System.out.println(""); - + System.out.print(" ".repeat(ii)); for (jj = 1; jj <= 4 - ii; jj++) { kk++; - - if (pins[kk] == 1) { - + + if (pins[kk] == 1) { + System.out.print("O "); - + } else { - - System.out.print("+ "); + + System.out.print("+ "); } - } + } } - + System.out.println(""); - + // Roll analysis - - for (ii = 1; ii <= 10; ii++) { - pinsDownNow += pins[ii]; - } - - if (pinsDownNow - pinsDownBefore == 0) { - System.out.println("GUTTER!!"); + + for (ii = 1; ii <= 10; ii++) { + pinsDownNow += pins[ii]; } - - if (ball == 1 && pinsDownNow == 10) { - System.out.println("STRIKE!!!!!"); - - // Ring bell - for (bell = 1; bell <= 4; bell++) { - System.out.print("\007"); + + if (pinsDownNow - pinsDownBefore == 0) { + System.out.println("GUTTER!!"); + } + + if (ball == 1 && pinsDownNow == 10) { + System.out.println("STRIKE!!!!!"); + + // Ring bell + for (bell = 1; bell <= 4; bell++) { + System.out.print("\007"); try { Thread.sleep(500); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } - } + } result = 3; } - + if (ball == 2 && pinsDownNow == 10) { System.out.println("SPARE!!!!"); - result = 2; + result = 2; } - + if (ball == 2 && pinsDownNow < 10) { System.out.println("ERROR!!!"); - result = 1; + result = 1; } - + if (ball == 1 && pinsDownNow < 10) { - System.out.println("ROLL YOUR 2ND BALL"); + System.out.println("ROLL YOUR 2ND BALL"); } - + // Storage of the scores - + System.out.println(""); - + scores[frame * player][ball] = pinsDownNow; - - if (ball != 2) { + + if (ball != 2) { ball = 2; - pinsDownBefore = pinsDownNow; + pinsDownBefore = pinsDownNow; - if (result != 3) { - scores[frame * player][ball] = pinsDownNow - pinsDownBefore; + if (result != 3) { + scores[frame * player][ball] = pinsDownNow - pinsDownBefore; if (result == 0) { continue; } } else { scores[frame * player][ball] = pinsDownNow; } - + } break; } - - scores[frame * player][3] = result; - + + scores[frame * player][3] = result; + } // End loop through all players - + frame++; - - } // End frame while loop + + } // End frame while loop System.out.println("FRAMES"); - + System.out.print(" "); - for (ii = 1; ii <= 10; ii++) { - System.out.print(ii + " "); + for (ii = 1; ii <= 10; ii++) { + System.out.print(ii + " "); } - + System.out.println(""); - - for (player = 1; player <= numPlayers; player++) { - for (ii = 1; ii <= 3; ii++) { - System.out.print(" "); - for (jj = 1; jj <= 10; jj++) { - System.out.print (scores[jj * player][ii] + " "); + + for (player = 1; player <= numPlayers; player++) { + for (ii = 1; ii <= 3; ii++) { + System.out.print(" "); + for (jj = 1; jj <= 10; jj++) { + System.out.print (scores[jj * player][ii] + " "); } - System.out.println(""); + System.out.println(""); } System.out.println(""); } - + System.out.println("DO YOU WANT ANOTHER GAME"); System.out.print("? "); - + userResponse = scan.nextLine(); - + if (!String.valueOf(userResponse.toUpperCase().charAt(0)).equals("Y")) { - break; + break; } - - } // End outer while loop - - } // End of method startGame - + + } // End outer while loop + + } // End of method startGame + public static void printRules() { - + System.out.println("THE GAME OF BOWLING TAKES MIND AND SKILL.DURING THE GAME"); System.out.println("THE COMPUTER WILL KEEP SCORE.YOU MAY COMPETE WITH"); System.out.println("OTHER PLAYERS[UP TO FOUR].YOU WILL BE PLAYING TEN FRAMES"); System.out.println("ON THE PIN DIAGRAM 'O' MEANS THE PIN IS DOWN...'+' MEANS THE"); System.out.println("PIN IS STANDING.AFTER THE GAME THE COMPUTER WILL SHOW YOUR"); System.out.println("SCORES ."); - + } // End of method printRules - + public static void main(String[] args) { - + Bowling game = new Bowling(); game.play(); - + } // End of method main - + } // End of class Bowling diff --git a/14_Bowling/javascript/bowling.js b/14_Bowling/javascript/bowling.js index 056397cbb..70c33ac73 100644 --- a/14_Bowling/javascript/bowling.js +++ b/14_Bowling/javascript/bowling.js @@ -12,10 +12,10 @@ function input() { var input_element; var input_str; - + return new Promise(function (resolve) { input_element = document.createElement("INPUT"); - + print("? "); input_element.setAttribute("type", "text"); input_element.setAttribute("length", "50"); diff --git a/14_Bowling/python/bowling.py b/14_Bowling/python/bowling.py index 42eaeddbe..a5d8f0793 100644 --- a/14_Bowling/python/bowling.py +++ b/14_Bowling/python/bowling.py @@ -16,12 +16,12 @@ def calculate_score(rolls): score += pins if b == 1: if pins == 10: # strike - score += sum(rolls[index + 1:index + 3]) + score += sum(rolls[index + 1 : index + 3]) frame += 1 else: b = 2 else: - if sum(rolls[index - 1:index + 1]) == 10: # spare + if sum(rolls[index - 1 : index + 1]) == 10: # spare score += rolls[index + 1] b = 1 frame += 1 @@ -46,7 +46,7 @@ def play_frame(self, frame): self.show(pins) pin_count = score - prev_score self.rolls.append(pin_count) # log the number of pins toppled this roll - print(f'{pin_count} for {self.name}') + print(f"{pin_count} for {self.name}") if score - prev_score == 0: print("GUTTER!!!") if ball == 0: @@ -63,7 +63,7 @@ def play_frame(self, frame): prev_score = score # remember previous pins to distinguish ... if frame == 9 and extra > 0: - print(f'Extra rolls for {self.name}') + print(f"Extra rolls for {self.name}") pins = [0] * 10 # reset the pins score = 0 for ball in range(extra): @@ -74,48 +74,48 @@ def play_frame(self, frame): self.rolls.append(score) def __str__(self): - return f'{self.name}: {self.rolls}, total:{calculate_score(self.rolls)}' + return f"{self.name}: {self.rolls}, total:{calculate_score(self.rolls)}" def show(self, pins): pins_iter = iter(pins) print() for row in range(4): - print(' ' * row, end='') + print(" " * row, end="") for _ in range(4 - row): p = next(pins_iter) - print('O ' if p else '+ ', end='') + print("O " if p else "+ ", end="") print() def centreText(text, width): t = len(text) - return (' ' * ((width - t) // 2)) + text + return (" " * ((width - t) // 2)) + text def main(): - print(centreText('Bowl', 80)) - print(centreText('CREATIVE COMPUTING MORRISTOWN, NEW JERSEY', 80)) + print(centreText("Bowl", 80)) + print(centreText("CREATIVE COMPUTING MORRISTOWN, NEW JERSEY", 80)) print() - print('WELCOME TO THE ALLEY.') - print('BRING YOUR FRIENDS.') + print("WELCOME TO THE ALLEY.") + print("BRING YOUR FRIENDS.") print("OKAY LET'S FIRST GET ACQUAINTED.") while True: print() - if input('THE INSTRUCTIONS (Y/N)? ') in 'yY': - print('THE GAME OF BOWLING TAKES MIND AND SKILL. DURING THE GAME') - print('THE COMPUTER WILL KEEP SCORE. YOU MAY COMPETE WITH') - print('OTHER PLAYERS[UP TO FOUR]. YOU WILL BE PLAYING TEN FRAMES.') + if input("THE INSTRUCTIONS (Y/N)? ") in "yY": + print("THE GAME OF BOWLING TAKES MIND AND SKILL. DURING THE GAME") + print("THE COMPUTER WILL KEEP SCORE. YOU MAY COMPETE WITH") + print("OTHER PLAYERS[UP TO FOUR]. YOU WILL BE PLAYING TEN FRAMES.") print("ON THE PIN DIAGRAM 'O' MEANS THE PIN IS DOWN...'+' MEANS THE") - print('PIN IS STANDING. AFTER THE GAME THE COMPUTER WILL SHOW YOUR') - print('SCORES.') + print("PIN IS STANDING. AFTER THE GAME THE COMPUTER WILL SHOW YOUR") + print("SCORES.") - total_players = int(input('FIRST OF ALL...HOW MANY ARE PLAYING? ')) + total_players = int(input("FIRST OF ALL...HOW MANY ARE PLAYING? ")) player_names = [] print() - print('VERY GOOD...') + print("VERY GOOD...") for index in range(total_players): - player_names.append(Player(input(f'Enter name for player {index + 1}: '))) + player_names.append(Player(input(f"Enter name for player {index + 1}: "))) for frame in range(10): for player in player_names: @@ -124,11 +124,11 @@ def main(): for player in player_names: print(player) - if input('DO YOU WANT ANOTHER GAME? ') not in 'yY': + if input("DO YOU WANT ANOTHER GAME? ") not in "yY": break -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/15_Boxing/csharp/AttackStrategy.cs b/15_Boxing/csharp/AttackStrategy.cs index 5ffdb2cce..dbc4617d8 100644 --- a/15_Boxing/csharp/AttackStrategy.cs +++ b/15_Boxing/csharp/AttackStrategy.cs @@ -21,7 +21,7 @@ public void Attack() { Other.DamageTaken += 2; } - + Work.Push(punch.Punch switch { Punch.FullSwing => FullSwing, @@ -36,7 +36,7 @@ public void Attack() protected abstract void Hook(); protected abstract void Uppercut(); protected abstract void Jab(); - + protected void RegisterKnockout(string knockoutMessage) { Work.Clear(); @@ -45,4 +45,4 @@ protected void RegisterKnockout(string knockoutMessage) } protected record AttackPunch(Punch Punch, bool IsBestPunch); -} \ No newline at end of file +} diff --git a/15_Boxing/csharp/Boxer.cs b/15_Boxing/csharp/Boxer.cs index 3f5fdd265..1162826b3 100644 --- a/15_Boxing/csharp/Boxer.cs +++ b/15_Boxing/csharp/Boxer.cs @@ -42,4 +42,4 @@ public void SetRandomPunches() Vulnerability = (Punch) GameUtils.Roll(4); // D1 } while (BestPunch == Vulnerability); } -} \ No newline at end of file +} diff --git a/15_Boxing/csharp/OpponentAttackStrategy.cs b/15_Boxing/csharp/OpponentAttackStrategy.cs index c5bf3e388..b2617685d 100644 --- a/15_Boxing/csharp/OpponentAttackStrategy.cs +++ b/15_Boxing/csharp/OpponentAttackStrategy.cs @@ -112,4 +112,4 @@ protected override void Jab() // 640 private void RegisterOtherKnockedOut() => RegisterKnockout($"{Other} IS KNOCKED COLD AND {_opponent} IS THE WINNER AND CHAMP!"); -} \ No newline at end of file +} diff --git a/15_Boxing/csharp/PlayerAttackStrategy.cs b/15_Boxing/csharp/PlayerAttackStrategy.cs index fd43c0ed1..b523ed748 100644 --- a/15_Boxing/csharp/PlayerAttackStrategy.cs +++ b/15_Boxing/csharp/PlayerAttackStrategy.cs @@ -6,7 +6,7 @@ public class PlayerAttackStrategy : AttackStrategy { private readonly Boxer _player; - public PlayerAttackStrategy(Boxer player, Opponent opponent, Action notifyGameEnded, Stack work) + public PlayerAttackStrategy(Boxer player, Opponent opponent, Action notifyGameEnded, Stack work) : base(opponent, work, notifyGameEnded) => _player = player; protected override AttackPunch GetPunch() @@ -118,4 +118,4 @@ protected override void Jab() void ScoreJabOnOpponent() => Other.DamageTaken += 3; } -} \ No newline at end of file +} diff --git a/15_Boxing/csharp/Program.cs b/15_Boxing/csharp/Program.cs index 57923de00..6f7404981 100644 --- a/15_Boxing/csharp/Program.cs +++ b/15_Boxing/csharp/Program.cs @@ -6,9 +6,9 @@ WriteLine(new string('\t', 15) + "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY"); WriteLine("{0}{0}{0}BOXING OLYMPIC STYLE (3 ROUNDS -- 2 OUT OF 3 WINS){0}", Environment.NewLine); -var opponent = new Opponent(); +var opponent = new Opponent(); opponent.SetName("WHAT IS YOUR OPPONENT'S NAME"); // J$ -var player = new Boxer(); +var player = new Boxer(); player.SetName("INPUT YOUR MAN'S NAME"); // L$ PrintPunchDescription(); @@ -26,4 +26,4 @@ round.CheckPlayerWin(); if (round.GameEnded) break; } -WriteLine("{0}{0}AND NOW GOODBYE FROM THE OLYMPIC ARENA.{0}", Environment.NewLine); \ No newline at end of file +WriteLine("{0}{0}AND NOW GOODBYE FROM THE OLYMPIC ARENA.{0}", Environment.NewLine); diff --git a/15_Boxing/csharp/Punch.cs b/15_Boxing/csharp/Punch.cs index add2003a5..dc2db88e5 100644 --- a/15_Boxing/csharp/Punch.cs +++ b/15_Boxing/csharp/Punch.cs @@ -6,4 +6,4 @@ public enum Punch Hook = 2, Uppercut = 3, Jab = 4 -} \ No newline at end of file +} diff --git a/15_Boxing/csharp/Round.cs b/15_Boxing/csharp/Round.cs index dfa1e26ba..20220d20b 100644 --- a/15_Boxing/csharp/Round.cs +++ b/15_Boxing/csharp/Round.cs @@ -2,14 +2,14 @@ class Round { - + private readonly Boxer _player; private readonly Boxer _opponent; private readonly int _round; private Stack _work = new(); private readonly PlayerAttackStrategy _playerAttackStrategy; private readonly OpponentAttackStrategy _opponentAttackStrategy; - + public bool GameEnded { get; private set; } public Round(Boxer player, Opponent opponent, int round) @@ -34,7 +34,7 @@ public void Start() // This delay does not exist in the VB code but it makes a bit easier to follow the game. // I assume the computers at the time were slow enough // so that they did not need this delay... - Thread.Sleep(300); + Thread.Sleep(300); action(); } } @@ -47,7 +47,7 @@ public void CheckOpponentWin() GameEnded = true; } } - + public void CheckPlayerWin() { if (_player.IsWinner) @@ -63,7 +63,7 @@ private void ResetPlayers() _opponent.ResetForNewRound(); _work.Push(RoundBegins); } - + private void RoundBegins() { Console.WriteLine(); @@ -93,4 +93,4 @@ private void DecideWhoAttacks() { _work.Push( GameUtils.RollSatisfies(10, x => x > 5) ? _opponentAttackStrategy.Attack : _playerAttackStrategy.Attack ); } -} \ No newline at end of file +} diff --git a/15_Boxing/csharp/Utils.cs b/15_Boxing/csharp/Utils.cs index 1ada516ca..55dc7a4a5 100644 --- a/15_Boxing/csharp/Utils.cs +++ b/15_Boxing/csharp/Utils.cs @@ -17,7 +17,7 @@ public static Punch GetPunch(string prompt) } return result; } - + public static Func Roll { get; } = upperLimit => (int) (upperLimit * Rnd.NextSingle()) + 1; public static bool RollSatisfies(int upperLimit, Predicate predicate) => predicate(Roll(upperLimit)); @@ -32,4 +32,4 @@ public static string ToFriendlyString(this Punch punch) _ => throw new ArgumentOutOfRangeException(nameof(punch), punch, null) }; -} \ No newline at end of file +} diff --git a/15_Boxing/java/Basic.java b/15_Boxing/java/Basic.java index 3822e3f3e..5fcd5baf9 100644 --- a/15_Boxing/java/Basic.java +++ b/15_Boxing/java/Basic.java @@ -42,4 +42,4 @@ public void print(String message, Object... args) { System.out.printf(message, args); } } -} \ No newline at end of file +} diff --git a/15_Boxing/java/Boxing.java b/15_Boxing/java/Boxing.java index 64b20155e..0eb694597 100644 --- a/15_Boxing/java/Boxing.java +++ b/15_Boxing/java/Boxing.java @@ -7,9 +7,9 @@ *

*/ public class Boxing { - + private static final Basic.Console console = new Basic.Console(); - + private GameSession session; public void play() { @@ -224,4 +224,4 @@ private void showIntro () { console.print(" CREATIVE COMPUTING MORRISTOWN, NEW JERSEY\n\n\n"); console.print("BOXING OLYMPIC STYLE (3 ROUNDS -- 2 OUT OF 3 WINS)\n\n"); } -} \ No newline at end of file +} diff --git a/15_Boxing/java/GameSession.java b/15_Boxing/java/GameSession.java index 3a2c77a5e..70292a121 100644 --- a/15_Boxing/java/GameSession.java +++ b/15_Boxing/java/GameSession.java @@ -64,4 +64,4 @@ public boolean isGameWinner(Player player) { public boolean isPlayerKnocked() { return knocked; } -} \ No newline at end of file +} diff --git a/15_Boxing/java/Player.java b/15_Boxing/java/Player.java index 2462b9d0a..e2cc152fc 100644 --- a/15_Boxing/java/Player.java +++ b/15_Boxing/java/Player.java @@ -39,4 +39,4 @@ public Player(String name) { public boolean hitVulnerability(Punch punch) { return vulnerability == punch; } -} \ No newline at end of file +} diff --git a/15_Boxing/javascript/boxing.js b/15_Boxing/javascript/boxing.js index 12620f77d..197c2f533 100644 --- a/15_Boxing/javascript/boxing.js +++ b/15_Boxing/javascript/boxing.js @@ -12,10 +12,10 @@ function input() { var input_element; var input_str; - + return new Promise(function (resolve) { input_element = document.createElement("INPUT"); - + print("? "); input_element.setAttribute("type", "text"); input_element.setAttribute("length", "50"); diff --git a/15_Boxing/python/boxing.py b/15_Boxing/python/boxing.py index 3db8d2647..a690f4fbb 100755 --- a/15_Boxing/python/boxing.py +++ b/15_Boxing/python/boxing.py @@ -1,13 +1,14 @@ #!/usr/bin/env python3 import random -QUESTION_PROMPT = '? ' +QUESTION_PROMPT = "? " + def play(): - print('BOXING') - print('CREATIVE COMPUTING MORRISTOWN, NEW JERSEY') - print('\n\n') - print('BOXING OLYMPIC STYLE (3 ROUNDS -- 2 OUT OF 3 WINS)') + print("BOXING") + print("CREATIVE COMPUTING MORRISTOWN, NEW JERSEY") + print("\n\n") + print("BOXING OLYMPIC STYLE (3 ROUNDS -- 2 OUT OF 3 WINS)") opponent_score = 0 player_score = 0 @@ -18,29 +19,32 @@ def play(): opponent_knockedout = False player_knockedout = False - print('WHAT IS YOUR OPPONENT\'S NAME', end=QUESTION_PROMPT) + print("WHAT IS YOUR OPPONENT'S NAME", end=QUESTION_PROMPT) opponent_name = input() - print('WHAT IS YOUR MAN\'S NAME', end=QUESTION_PROMPT) + print("WHAT IS YOUR MAN'S NAME", end=QUESTION_PROMPT) player_name = input() - print('DIFFERENT PUNCHES ARE 1 FULL SWING 2 HOOK 3 UPPERCUT 4 JAB') - print('WHAT IS YOUR MAN\'S BEST', end=QUESTION_PROMPT) + print("DIFFERENT PUNCHES ARE 1 FULL SWING 2 HOOK 3 UPPERCUT 4 JAB") + print("WHAT IS YOUR MAN'S BEST", end=QUESTION_PROMPT) player_best = int(input()) - print('WHAT IS HIS VULNERABILITY', end=QUESTION_PROMPT) + print("WHAT IS HIS VULNERABILITY", end=QUESTION_PROMPT) player_weakness = int(input()) opponent_best = 0 - opponent_weakness = 0 + opponent_weakness = 0 while opponent_best == opponent_weakness: opponent_best = random.randint(1, 4) opponent_weakness = random.randint(1, 4) - print('{}\'S ADVANTAGE is {} AND VULNERABILITY IS SECRET.' - .format(opponent_name, opponent_weakness)) + print( + "{}'S ADVANTAGE is {} AND VULNERABILITY IS SECRET.".format( + opponent_name, opponent_weakness + ) + ) for round in (1, 2, 3): - print('ROUND {} BEGINS...\n'.format(round)) + print(f"ROUND {round} BEGINS...\n") if opponent_score >= 2 or player_score >= 2: break @@ -53,96 +57,117 @@ def play(): player_damage += 2 if punch == 1: - print('{} TAKES A FULL SWING AND'.format(opponent_name), end = ' ') + print(f"{opponent_name} TAKES A FULL SWING AND", end=" ") if player_weakness == 1 or random.randint(1, 60) < 30: - print('POW!!!! HE HITS HIM RIGHT IN THE FACE!') + print("POW!!!! HE HITS HIM RIGHT IN THE FACE!") if player_damage > 35: player_knockedout = True break player_damage += 15 else: - print('BUT IT\'S BLOCKED!') + print("BUT IT'S BLOCKED!") elif punch == 2: - print('{} GETS {} IN THE JAW (OUCH!)'.format(opponent_name, player_name), end = ' ') + print( + "{} GETS {} IN THE JAW (OUCH!)".format( + opponent_name, player_name + ), + end=" ", + ) player_damage += 7 - print('....AND AGAIN') + print("....AND AGAIN") if player_damage > 35: player_knockedout = True break player_damage += 5 elif punch == 3: - print('{} IS ATTACKED BY AN UPPERCUT (OH,OH)'.format(player_name)) + print(f"{player_name} IS ATTACKED BY AN UPPERCUT (OH,OH)") if player_weakness == 3 or random.randint(1, 200) > 75: - print('{} BLOCKS AND HITS {} WITH A HOOK'.format(player_name, opponent_name)) + print( + "{} BLOCKS AND HITS {} WITH A HOOK".format( + player_name, opponent_name + ) + ) opponent_damage += 5 else: - print('AND {} CONNECTS...'.format(opponent_name)) + print(f"AND {opponent_name} CONNECTS...") player_damage += 8 else: - print('{} JABS AND'.format(opponent_name), end = ' ') + print(f"{opponent_name} JABS AND", end=" ") if player_weakness == 4 or random.randint(1, 7) > 4: - print('BLOOD SPILLS !!!') + print("BLOOD SPILLS !!!") player_damage += 3 else: - print('AND IT\'S BLOCKED (LUCKY BLOCK!)') + print("AND IT'S BLOCKED (LUCKY BLOCK!)") else: - print('{}\'S PUNCH'.format(player_name), end='? ') + print(f"{player_name}'S PUNCH", end="? ") punch = int(input()) if punch == opponent_weakness: opponent_damage += 2 if punch == 1: - print('{} SWINGS AND'.format(player_name), end = ' ') + print(f"{player_name} SWINGS AND", end=" ") if opponent_weakness == 1 or random.randint(1, 30) < 10: - print('HE CONNECTS!') + print("HE CONNECTS!") if opponent_damage > 35: opponent_knockedout = True break opponent_damage += 15 else: - print('HE MISSES') + print("HE MISSES") elif punch == 2: - print('{} GIVES THE HOOK...'.format(player_name), end = ' ') + print(f"{player_name} GIVES THE HOOK...", end=" ") if opponent_weakness == 2 or random.randint(1, 2) == 1: - print('CONNECTS...') + print("CONNECTS...") opponent_damage += 7 else: - print('BUT IT\'S BLOCKED!!!!!!!!!!!!!') + print("BUT IT'S BLOCKED!!!!!!!!!!!!!") elif punch == 3: - print('{} TRIES AN UPPERCUT'.format(player_name), end = ' ') + print(f"{player_name} TRIES AN UPPERCUT", end=" ") if opponent_weakness == 3 or random.randint(1, 100) < 51: - print('AND HE CONNECTS!') + print("AND HE CONNECTS!") opponent_damage += 4 else: - print('AND IT\'S BLOCKED (LUCKY BLOCK!)') + print("AND IT'S BLOCKED (LUCKY BLOCK!)") else: - print('{} JABS AT {}\'S HEAD'.format(player_name, opponent_name), end = ' ') + print( + f"{player_name} JABS AT {opponent_name}'S HEAD", + end=" ", + ) if opponent_weakness == 4 or random.randint(1, 8) < 4: - print('AND HE CONNECTS!') + print("AND HE CONNECTS!") opponent_damage += 3 else: - print('AND IT\'S BLOCKED (LUCKY BLOCK!)') + print("AND IT'S BLOCKED (LUCKY BLOCK!)") if player_knockedout or opponent_knockedout: break elif player_damage > opponent_damage: - print('{} WINS ROUND {}'.format(opponent_name, round)) + print(f"{opponent_name} WINS ROUND {round}") opponent_score += 1 else: - print('{} WINS ROUND {}'.format(player_name, round)) + print(f"{player_name} WINS ROUND {round}") player_score += 1 if player_knockedout: - print('{} IS KNOCKED COLD AND {} IS THE WINNER AND CHAMP'.format(player_name, opponent_name)) + print( + "{} IS KNOCKED COLD AND {} IS THE WINNER AND CHAMP".format( + player_name, opponent_name + ) + ) elif opponent_knockedout: - print('{} IS KNOCKED COLD AND {} IS THE WINNER AND CHAMP'.format(opponent_name, player_name)) + print( + "{} IS KNOCKED COLD AND {} IS THE WINNER AND CHAMP".format( + opponent_name, player_name + ) + ) elif opponent_score > player_score: - print('{} WINS (NICE GOING), {}'.format(opponent_name, player_name)) + print(f"{opponent_name} WINS (NICE GOING), {player_name}") else: - print('{} AMAZINGLY WINS'.format(player_name)) + print(f"{player_name} AMAZINGLY WINS") + + print("\n\nAND NOW GOODBYE FROM THE OLYMPIC ARENA.") - print('\n\nAND NOW GOODBYE FROM THE OLYMPIC ARENA.') -if __name__ == '__main__': +if __name__ == "__main__": play() diff --git a/16_Bug/java/src/Bug.java b/16_Bug/java/src/Bug.java index 861afc5a5..2fc06a494 100644 --- a/16_Bug/java/src/Bug.java +++ b/16_Bug/java/src/Bug.java @@ -250,4 +250,4 @@ private int randomNumber() { return (int) (Math.random() * (SIX) + 1); } -} \ No newline at end of file +} diff --git a/16_Bug/java/src/Insect.java b/16_Bug/java/src/Insect.java index 08e9414f0..747cfbb6e 100644 --- a/16_Bug/java/src/Insect.java +++ b/16_Bug/java/src/Insect.java @@ -360,4 +360,4 @@ private String addSpaces(int number) { return new String(spaces); } -} \ No newline at end of file +} diff --git a/16_Bug/java/src/PlayerBug.java b/16_Bug/java/src/PlayerBug.java index 1a82e8b33..c8f735085 100644 --- a/16_Bug/java/src/PlayerBug.java +++ b/16_Bug/java/src/PlayerBug.java @@ -15,4 +15,3 @@ public PlayerBug() { } - diff --git a/16_Bug/javascript/bug.js b/16_Bug/javascript/bug.js index e222e03d0..5f13657bc 100644 --- a/16_Bug/javascript/bug.js +++ b/16_Bug/javascript/bug.js @@ -12,7 +12,7 @@ function input() { return new Promise(function (resolve) { const input_element = document.createElement("INPUT"); - + print("? "); input_element.setAttribute("type", "text"); input_element.setAttribute("length", "50"); diff --git a/16_Bug/python/Bug.py b/16_Bug/python/Bug.py index ba5f4de4e..819e50ef6 100644 --- a/16_Bug/python/Bug.py +++ b/16_Bug/python/Bug.py @@ -2,7 +2,7 @@ def print_n_whitespaces(n: int): - print(" "*n, end="") + print(" " * n, end="") def print_n_newlines(n: int): @@ -75,10 +75,10 @@ def print_legs(n_legs): ["3", "HEAD", "1"], ["4", "FEELERS", "2"], ["5", "TAIL", "1"], - ["6", "LEGS", "6"] + ["6", "LEGS", "6"], ] for row in table: - print("{:<16}{:<16}{:<20}".format(row[0], row[1], row[2])) + print(f"{row[0]:<16}{row[1]:<16}{row[2]:<20}") print_n_newlines(2) A = 0 @@ -299,4 +299,4 @@ def print_legs(n_legs): if Y != 0: break -print("I HOPE YOU ENJOYED THE GAME, PLAY IT AGAIN SOON!!") \ No newline at end of file +print("I HOPE YOU ENJOYED THE GAME, PLAY IT AGAIN SOON!!") diff --git a/16_Bug/python/bug-overengineered.py b/16_Bug/python/bug-overengineered.py index adb9a31e7..11b0d867e 100644 --- a/16_Bug/python/bug-overengineered.py +++ b/16_Bug/python/bug-overengineered.py @@ -7,31 +7,35 @@ Ported by Peter Sharp """ -from random import randint from collections import namedtuple +from random import randint PAGE_WIDTH = 64 + def main(states, data): """ Starts the game loop using given states and data - + Uses a modified version of the MVC (Model View Controller) pattern that uses functions instead of objects - + each state in the game has one of each of the following: View, displays data Control, converts raw command from user into something the model understands Model, updates game data based on action received from controller """ - + while True: - if 'exit' == data['state']: break - view, control, model = states[data['state']] + if "exit" == data["state"]: + break + view, control, model = states[data["state"]] cmd = view(data) action = control(cmd) data = model(data, action) - -Bodypart = namedtuple('Bodypart', ['name', 'count', 'depends']) + + +Bodypart = namedtuple("Bodypart", ["name", "count", "depends"]) + def print_start(_): """ @@ -47,19 +51,21 @@ def print_start(_): print() return input("DO YOU WANT INSTRUCTIONS? ") + def control_start(cmd): """ Controls the start state """ - if cmd.lower() in ('y', 'yes'): - action = 'instructions' + if cmd.lower() in ("y", "yes"): + action = "instructions" else: - action = 'game' + action = "game" return action - + + def print_instructions(data): """ - Prints game instructions + Prints game instructions """ print("THE OBJECT OF BUG IS TO FINISH YOUR BUG BEFORE I FINISH") print("MINE. EACH NUMBER STANDS FOR A PART OF THE BUG BODY.") @@ -70,244 +76,263 @@ def print_instructions(data): print("IF THERE IS A CHANGE IN EITHER BUG I WILL GIVE YOU THE") print("OPTION OF SEEING THE PICTURES OF THE BUGS.") print("THE NUMBERS STAND FOR PARTS AS FOLLOWS:") - - print_table([ - ("NUMBER","PART","NUMBER OF PART NEEDED"), - *[(i + 1, part.name, part.count) for i, part in enumerate(data['partTypes'])] - ]) + + print_table( + [ + ("NUMBER", "PART", "NUMBER OF PART NEEDED"), + *[ + (i + 1, part.name, part.count) + for i, part in enumerate(data["partTypes"]) + ], + ] + ) print() print() - return '' + return "" + def goto_game(_): """ - Returns game + Returns game """ - return 'game' + return "game" + def update_state(data, action): """ sets game state to given player value """ - return {**data, 'state': action} + return {**data, "state": action} + def update_game(data, action): """ - Updates game data for player turns until one player successfully gets a body part + Updates game data for player turns until one player successfully gets a body part """ # stores logs of what happened during a particular round logs = [] - - if 'pictures' == action: - data['state'] = 'pictures' + + if "pictures" == action: + data["state"] = "pictures" else: partAdded = False while partAdded == False: - for player, parts in data['players'].items(): + for player, parts in data["players"].items(): # rolls the dice for a part - newPartIdx = randint(1,6) - 1 - + newPartIdx = randint(1, 6) - 1 + # gets information about the picked part - partType = data['partTypes'][newPartIdx] - + partType = data["partTypes"][newPartIdx] + # gets the number of existing parts of that type the player has partCount = parts[newPartIdx] - - logs.append(('rolled', newPartIdx, player)) - - # a new part can only be added if the player has the parts + + logs.append(("rolled", newPartIdx, player)) + + # a new part can only be added if the player has the parts # the new part depends on and doesn't have enough of the part already overMaxParts = partType.count < partCount + 1 - missingPartDep = partType.depends != None and parts[partType.depends] == 0 - + missingPartDep = ( + partType.depends != None and parts[partType.depends] == 0 + ) + if not overMaxParts and not missingPartDep: - # adds a new part + # adds a new part partCount += 1 - logs.append(('added', newPartIdx, player)) + logs.append(("added", newPartIdx, player)) partAdded = True elif missingPartDep: - logs.append(('missingDep', newPartIdx, player, partType.depends)) + logs.append(("missingDep", newPartIdx, player, partType.depends)) if overMaxParts: - logs.append(('overMax', newPartIdx, player, partCount)) - - data['players'][player][newPartIdx] = partCount - data['logs'] = logs - + logs.append(("overMax", newPartIdx, player, partCount)) + + data["players"][player][newPartIdx] = partCount + data["logs"] = logs + # checks if any players have finished their bug finished = get_finished(data) if len(finished) > 0: # and sets the state to 'won' if that's the case - data['finished'] = finished - data['state'] = 'won' + data["finished"] = finished + data["state"] = "won" return data + def get_finished(data): """ Gets players who have finished their bugs """ - totalParts = sum([partType.count for partType in data['partTypes']]) + totalParts = sum(partType.count for partType in data["partTypes"]) finished = [] - for player, parts in data['players'].items(): - if(sum(parts) == totalParts): finished.append(player) + for player, parts in data["players"].items(): + if sum(parts) == totalParts: + finished.append(player) return finished + def print_game(data): """ Displays the results of the game turn """ - for log in data['logs']: + for log in data["logs"]: code, partIdx, player, *logdata = log - partType = data['partTypes'][partIdx] - - if('rolled' == code): + partType = data["partTypes"][partIdx] + + if "rolled" == code: print() print(f"{player} ROLLED A {partIdx + 1}") print(f"{partIdx + 1}={partType.name}") - - elif('added' == code): - if 'YOU' == player: - if partType.name in ['FEELERS', 'LEGS', 'TAIL']: + + elif "added" == code: + if "YOU" == player: + if partType.name in ["FEELERS", "LEGS", "TAIL"]: print(f"I NOW GIVE YOU A {partType.name.replace('s', '')}.") else: print(f"YOU NOW HAVE A {partType.name}.") - elif 'I' == player: - if partType.name in ['BODY', 'NECK', 'TAIL']: + elif "I" == player: + if partType.name in ["BODY", "NECK", "TAIL"]: print(f"I NOW HAVE A {partType.name}.") - elif partType.name == 'FEELERS': + elif partType.name == "FEELERS": print("I GET A FEELER.") - + if partType.count > 2: - print(f"{player} NOW HAVE {data['players'][player][partIdx]} {partType.name}") - - elif 'missingDep' == code: - depIdx, = logdata - dep = data['partTypes'][depIdx] - print(f"YOU DO NOT HAVE A {dep.name}" if 'YOU' == player else f"I NEEDED A {dep.name}") - - elif 'overMax' == code: - partCount, = logdata - if(partCount > 1): - num = 'TWO' if 2 == partCount else partCount + print( + f"{player} NOW HAVE {data['players'][player][partIdx]} {partType.name}" + ) + + elif "missingDep" == code: + (depIdx,) = logdata + dep = data["partTypes"][depIdx] + print( + f"YOU DO NOT HAVE A {dep.name}" + if "YOU" == player + else f"I NEEDED A {dep.name}" + ) + + elif "overMax" == code: + (partCount,) = logdata + if partCount > 1: + num = "TWO" if 2 == partCount else partCount maxMsg = f"HAVE {num} {partType.name}S ALREADY" else: maxMsg = f"ALREADY HAVE A {partType.name}" print(f"{player} {maxMsg}") - return input("DO YOU WANT THE PICTURES? ") if len(data['logs']) else 'n' + return input("DO YOU WANT THE PICTURES? ") if len(data["logs"]) else "n" + def print_pictures(data): """ Displays what the bugs look like for each player """ - typeIxs = { partType.name: idx for idx, partType in enumerate(data['partTypes']) } + typeIxs = {partType.name: idx for idx, partType in enumerate(data["partTypes"])} PIC_WIDTH = 22 - for player, parts in data['players'].items(): + for player, parts in data["players"].items(): print(f"*****{'YOUR' if 'YOU' == player else 'MY'} BUG*****") print() print() - if(parts[typeIxs['BODY']] > 0): - if(parts[typeIxs['FEELERS']] > 0): - F = ' '.join(['F'] * parts[typeIxs['FEELERS']]) + if parts[typeIxs["BODY"]] > 0: + if parts[typeIxs["FEELERS"]] > 0: + F = " ".join(["F"] * parts[typeIxs["FEELERS"]]) for _ in range(4): - print(' ' * 9 + F) - if(parts[typeIxs['HEAD']] > 0): + print(" " * 9 + F) + if parts[typeIxs["HEAD"]] > 0: print_centered("HHHHHHH", PIC_WIDTH) print_centered("H H", PIC_WIDTH) print_centered("H O O H", PIC_WIDTH) print_centered("H H", PIC_WIDTH) print_centered("H V H", PIC_WIDTH) print_centered("HHHHHHH", PIC_WIDTH) - if(parts[typeIxs['NECK']] > 0): + if parts[typeIxs["NECK"]] > 0: for _ in range(2): print_centered("N N", PIC_WIDTH) print_centered("BBBBBBBBBBBB", PIC_WIDTH) for _ in range(2): print_centered("B B", PIC_WIDTH) - - if(parts[typeIxs['TAIL']] > 0): + + if parts[typeIxs["TAIL"]] > 0: print("TTTTTB B") print_centered("BBBBBBBBBBBB", PIC_WIDTH) - if(parts[typeIxs['LEGS']] > 0): - L = 'L' * parts[typeIxs['LEGS']] + if parts[typeIxs["LEGS"]] > 0: + L = "L" * parts[typeIxs["LEGS"]] for _ in range(2): - print(' '*5+L) + print(" " * 5 + L) print() + def control_game(cmd): """ returns state based on command """ - if cmd.lower() in ('y', 'yes'): - action = 'pictures' + if cmd.lower() in ("y", "yes"): + action = "pictures" else: - action = 'game' + action = "game" return action + def print_winner(data): """ Displays the winning message """ - for player in data['finished']: + for player in data["finished"]: print(f"{'YOUR' if 'YOU' == player else 'MY'} BUG IS FINISHED.") print("I HOPE YOU ENJOYED THE GAME, PLAY IT AGAIN SOON!!") - + + def exit_game(_): """ Exists the game regardless of input """ - return 'exit' - + return "exit" + + def print_centered(msg, width=PAGE_WIDTH): """ Prints given message centered to given width """ spaces = " " * ((width - len(msg)) // 2) print(spaces + msg) - + + def print_table(rows): for row in rows: print(*row, sep="\t") -if __name__ == '__main__': - + +if __name__ == "__main__": + # The main states in the game states = { # Initial state of the game - 'start': (print_start, control_start, update_state), - + "start": (print_start, control_start, update_state), # displays game instructions - 'instructions': (print_instructions, goto_game, update_state), - - # the main game state - 'game': (print_game, control_game, update_game), - + "instructions": (print_instructions, goto_game, update_state), + # the main game state + "game": (print_game, control_game, update_game), # displays pictures before returning to game - 'pictures': (print_pictures, goto_game, update_state), - + "pictures": (print_pictures, goto_game, update_state), # Displays the winning players and message - 'won': (print_winner, exit_game, update_state) + "won": (print_winner, exit_game, update_state), } # body part types used by the game to work out whether a player's body part can be added partTypes = ( - Bodypart(name="BODY", count=1 , depends=None), - Bodypart(name="NECK", count=1 , depends=0), - Bodypart(name="HEAD", count=1 , depends=1), - Bodypart(name="FEELERS", count=2 , depends=2), - Bodypart(name="TAIL", count=1 , depends=0), - Bodypart(name="LEGS", count=6 , depends=0) + Bodypart(name="BODY", count=1, depends=None), + Bodypart(name="NECK", count=1, depends=0), + Bodypart(name="HEAD", count=1, depends=1), + Bodypart(name="FEELERS", count=2, depends=2), + Bodypart(name="TAIL", count=1, depends=0), + Bodypart(name="LEGS", count=6, depends=0), ) # all the data used by the game data = { - 'state': 'start', - 'partNo': None, - 'players': { - 'YOU': [0] * len(partTypes), - 'I': [0] * len(partTypes) - }, - 'partTypes': partTypes, - 'finished': [], - 'logs': [] + "state": "start", + "partNo": None, + "players": {"YOU": [0] * len(partTypes), "I": [0] * len(partTypes)}, + "partTypes": partTypes, + "finished": [], + "logs": [], } - main(states, data) \ No newline at end of file + main(states, data) diff --git a/17_Bullfight/javascript/bullfight.js b/17_Bullfight/javascript/bullfight.js index c3e022521..d8355e1e4 100644 --- a/17_Bullfight/javascript/bullfight.js +++ b/17_Bullfight/javascript/bullfight.js @@ -12,10 +12,10 @@ function input() { var input_element; var input_str; - + return new Promise(function (resolve) { input_element = document.createElement("INPUT"); - + print("? "); input_element.setAttribute("type", "text"); input_element.setAttribute("length", "50"); diff --git a/17_Bullfight/python/Bullfight.py b/17_Bullfight/python/Bullfight.py index 4b77c2deb..49fad4baa 100644 --- a/17_Bullfight/python/Bullfight.py +++ b/17_Bullfight/python/Bullfight.py @@ -3,7 +3,7 @@ def print_n_whitespaces(n: int): - print(" "*n, end="") + print(" " * n, end="") def print_n_newlines(n: int): @@ -12,18 +12,18 @@ def print_n_newlines(n: int): def subroutine_1610(): - B = 3/A*random.random() - if (B < 0.37): + B = 3 / A * random.random() + if B < 0.37: C = 0.5 - elif (B < 0.5): + elif B < 0.5: C = 0.4 - elif (B < 0.63): + elif B < 0.63: C = 0.3 - elif (B < 0.87): + elif B < 0.87: C = 0.2 else: C = 0.1 - T = math.floor(10*C+0.2) + T = math.floor(10 * C + 0.2) print(f"THE {AS}{BS} DID A {LS[T]} JOB.") if T >= 4: if T == 5: @@ -44,8 +44,9 @@ def subroutine_1610(): def FNC(): - Q = (4.5+L/6-(D[1]+D[2])*2.5+4*D[4]+2 * - D[5]-(D[3] ** 2)/120-A)*random.random() + Q = ( + 4.5 + L / 6 - (D[1] + D[2]) * 2.5 + 4 * D[4] + 2 * D[5] - (D[3] ** 2) / 120 - A + ) * random.random() return Q @@ -103,7 +104,7 @@ def FNC(): print_n_newlines(2) D[3] = 0 while True: - D[3] = D[3] + 1 # 660 + D[3] = D[3] + 1 # 660 print(f"PASS NUMBER {D[3]}") if D[3] >= 3: while True: # 1930 @@ -133,7 +134,7 @@ def FNC(): # goto 1130 pass gore = 0 - if Z1 != 1: # NO + if Z1 != 1: # NO while True: E = float(input()) if E != float(int(abs(E))): @@ -147,11 +148,11 @@ def FNC(): else: M = 0.5 L = L + M - F = (6-A+M/10)*random.random()/((D[1]+D[2]+D[3]/10)*5) + F = (6 - A + M / 10) * random.random() / ((D[1] + D[2] + D[3] / 10) * 5) if F < 0.51: continue gore = 1 - else: # YES + else: # YES print() print("IT IS THE MOMENT OF TRUTH.") print() @@ -161,7 +162,7 @@ def FNC(): gore = 2 # goto 970 else: - K=(6-A)*10*random.random()/((D[1]+D[2])*5*D[3]) + K = (6 - A) * 10 * random.random() / ((D[1] + D[2]) * 5 * D[3]) if H == 4: if K > 0.8: gore = 1 @@ -177,7 +178,7 @@ def FNC(): print("THE BULL HAS GORED YOU!") death = False while True: - _ = random.randint(1, 2) # 970 + _ = random.randint(1, 2) # 970 if _ == 1: print("YOU ARE DEAD.") D[4] = 1.5 @@ -213,7 +214,7 @@ def FNC(): death = True break - if death==True: + if death == True: break # 1310 print_n_newlines(3) diff --git a/18_Bullseye/javascript/bullseye.js b/18_Bullseye/javascript/bullseye.js index 0b8d061c1..b2ec905f0 100644 --- a/18_Bullseye/javascript/bullseye.js +++ b/18_Bullseye/javascript/bullseye.js @@ -12,10 +12,10 @@ function input() { var input_element; var input_str; - + return new Promise(function (resolve) { input_element = document.createElement("INPUT"); - + print("? "); input_element.setAttribute("type", "text"); input_element.setAttribute("length", "50"); diff --git a/18_Bullseye/perl/bullseye.pl b/18_Bullseye/perl/bullseye.pl index 22405d30c..404807c0d 100755 --- a/18_Bullseye/perl/bullseye.pl +++ b/18_Bullseye/perl/bullseye.pl @@ -48,12 +48,10 @@ } for (my $I=1; $I<=$N; $I++) { - if ($S[$I]>=200) { $M= $M+1; $W[$M]= $I; } + if ($S[$I]>=200) { $M= $M+1; $W[$M]= $I; } } } until ($M!=0); print "\n"; print "WE HAVE A WINNER!!\n\n"; for (my $I=1; $I<=$M; $I++) { print $A[$W[$I]]." SCORED ".$S[$W[$I]]." POINTS.\n"; } print "\n"; print "THANKS FOR THE GAME.\n"; exit; - - diff --git a/18_Bullseye/python/Bullseye.py b/18_Bullseye/python/Bullseye.py index 82c1d8cb4..b4c0936cb 100644 --- a/18_Bullseye/python/Bullseye.py +++ b/18_Bullseye/python/Bullseye.py @@ -2,13 +2,14 @@ def print_n_whitespaces(n: int): - print(" "*n, end="") + print(" " * n, end="") def print_n_newlines(n: int): for _ in range(n): print() + print_n_whitespaces(32) print("BULLSEYE") print_n_whitespaces(15) @@ -18,10 +19,26 @@ def print_n_newlines(n: int): print("WITH 10, 20, 30, AND 40 POINT ZONES. THE OBJECTIVE IS") print("TO GET 200 POINTS.") print() -print("THROW",end="");print_n_whitespaces(20);print("DESCRIPTION", end="");print_n_whitespaces(45);print("PROBABLE SCORE") -print(" 1",end="");print_n_whitespaces(20);print("FAST OVERARM",end="");print_n_whitespaces(45);print("BULLSEYE OR COMPLETE MISS") -print(" 2",end="");print_n_whitespaces(20);print("CONTROLLED OVERARM",end="");print_n_whitespaces(45);print("10, 20 OR 30 POINTS") -print(" 3",end="");print_n_whitespaces(20);print("UNDERARM",end="");print_n_whitespaces(45);print("ANYTHING") +print("THROW", end="") +print_n_whitespaces(20) +print("DESCRIPTION", end="") +print_n_whitespaces(45) +print("PROBABLE SCORE") +print(" 1", end="") +print_n_whitespaces(20) +print("FAST OVERARM", end="") +print_n_whitespaces(45) +print("BULLSEYE OR COMPLETE MISS") +print(" 2", end="") +print_n_whitespaces(20) +print("CONTROLLED OVERARM", end="") +print_n_whitespaces(45) +print("10, 20 OR 30 POINTS") +print(" 3", end="") +print_n_whitespaces(20) +print("UNDERARM", end="") +print_n_whitespaces(45) +print("ANYTHING") print() M = 0 @@ -37,7 +54,7 @@ def print_n_newlines(n: int): N = int(input("HOW MANY PLAYERS? ")) A = {} -for I in range(1, N+1): +for I in range(1, N + 1): Name = input("NAME OF PLAYER #") A[I] = Name @@ -45,29 +62,29 @@ def print_n_newlines(n: int): R = R + 1 print() print(f"ROUND {R}---------") - for I in range(1, N+1): + for I in range(1, N + 1): print() while True: T = int(input(f"{A[I]}'S THROW? ")) if T < 1 or T > 3: print("INPUT 1, 2, OR 3!") - else: + else: break if T == 1: - P1=.65 - P2=.55 - P3=.5 - P4=.5 + P1 = 0.65 + P2 = 0.55 + P3 = 0.5 + P4 = 0.5 elif T == 2: - P1=.99 - P2=.77 - P3=.43 - P4=.01 + P1 = 0.99 + P2 = 0.77 + P3 = 0.43 + P4 = 0.01 elif T == 3: - P1=.95 - P2=.75 - P3=.45 - P4=.05 + P1 = 0.95 + P2 = 0.75 + P3 = 0.45 + P4 = 0.05 U = random.random() if U >= P1: print("BULLSEYE!! 40 POINTS!") @@ -78,7 +95,7 @@ def print_n_newlines(n: int): elif U >= P3: print("20-POINT ZONE") B = 20 - elif U >= P4: + elif U >= P4: print("WHEW! 10 POINTS.") B = 10 else: @@ -86,15 +103,15 @@ def print_n_newlines(n: int): B = 0 S[I] = S[I] + B print(f"TOTAL SCORE = {S[I]}") - for I in range(1, N+1): + for I in range(1, N + 1): if S[I] > 200: - M = M+1 + M = M + 1 W[M] = I - + print() print("WE HAVE A WINNER!!") print() -for I in range(1, M+1): +for I in range(1, M + 1): print(f"{A[W[I]]} SCORED {S[W[I]]} POINTS.") print() -print("THANKS FOR THE GAME.") \ No newline at end of file +print("THANKS FOR THE GAME.") diff --git a/19_Bunny/csharp/Bunny.cs b/19_Bunny/csharp/Bunny.cs index 76e5e7e41..4e3adf8ac 100644 --- a/19_Bunny/csharp/Bunny.cs +++ b/19_Bunny/csharp/Bunny.cs @@ -30,9 +30,9 @@ public void Run() // Set up a BASIC-ish data object BasicData data = new (bunnyData); - // Get the first five data values into an array. + // Get the first five data values into an array. // These are the characters we are going to print. - // Unlike the original program, we are only converting + // Unlike the original program, we are only converting // them to ASCII once. var a = new char[5]; for (var i = 0; i < 5; ++i) diff --git a/19_Bunny/java/src/Bunny.java b/19_Bunny/java/src/Bunny.java index d2fd16997..00963a63f 100644 --- a/19_Bunny/java/src/Bunny.java +++ b/19_Bunny/java/src/Bunny.java @@ -164,4 +164,4 @@ public static void main(String[] args) { Bunny bunny = new Bunny(); bunny.process(); } -} \ No newline at end of file +} diff --git a/19_Bunny/javascript/bunny.js b/19_Bunny/javascript/bunny.js index 11342d8b8..97e0376ce 100644 --- a/19_Bunny/javascript/bunny.js +++ b/19_Bunny/javascript/bunny.js @@ -52,7 +52,7 @@ for (var pos = 0; bunny_data[pos] < 128; pos++) { } while (str.length < bunny_data[pos]) str += " "; - for (var i = bunny_data[pos]; i <= bunny_data[pos + 1]; i++) + for (var i = bunny_data[pos]; i <= bunny_data[pos + 1]; i++) str += bunny_string[i % 5]; pos++; } diff --git a/19_Bunny/python/bunny.py b/19_Bunny/python/bunny.py index c1c9a6976..c7ce2bc2c 100755 --- a/19_Bunny/python/bunny.py +++ b/19_Bunny/python/bunny.py @@ -2,21 +2,241 @@ # This data is meant to be read-only, so we are storing it in a tuple -DATA = (2,21,14,14,25, - 1,2,-1,0,2,45,50,-1,0,5,43,52,-1,0,7,41,52,-1, - 1,9,37,50,-1,2,11,36,50,-1,3,13,34,49,-1,4,14,32,48,-1, - 5,15,31,47,-1,6,16,30,45,-1,7,17,29,44,-1,8,19,28,43,-1, - 9,20,27,41,-1,10,21,26,40,-1,11,22,25,38,-1,12,22,24,36,-1, - 13,34,-1,14,33,-1,15,31,-1,17,29,-1,18,27,-1, - 19,26,-1,16,28,-1,13,30,-1,11,31,-1,10,32,-1, - 8,33,-1,7,34,-1,6,13,16,34,-1,5,12,16,35,-1, - 4,12,16,35,-1,3,12,15,35,-1,2,35,-1,1,35,-1, - 2,34,-1,3,34,-1,4,33,-1,6,33,-1,10,32,34,34,-1, - 14,17,19,25,28,31,35,35,-1,15,19,23,30,36,36,-1, - 14,18,21,21,24,30,37,37,-1,13,18,23,29,33,38,-1, - 12,29,31,33,-1,11,13,17,17,19,19,22,22,24,31,-1, - 10,11,17,18,22,22,24,24,29,29,-1, - 22,23,26,29,-1,27,29,-1,28,29,-1,4096) +DATA = ( + 2, + 21, + 14, + 14, + 25, + 1, + 2, + -1, + 0, + 2, + 45, + 50, + -1, + 0, + 5, + 43, + 52, + -1, + 0, + 7, + 41, + 52, + -1, + 1, + 9, + 37, + 50, + -1, + 2, + 11, + 36, + 50, + -1, + 3, + 13, + 34, + 49, + -1, + 4, + 14, + 32, + 48, + -1, + 5, + 15, + 31, + 47, + -1, + 6, + 16, + 30, + 45, + -1, + 7, + 17, + 29, + 44, + -1, + 8, + 19, + 28, + 43, + -1, + 9, + 20, + 27, + 41, + -1, + 10, + 21, + 26, + 40, + -1, + 11, + 22, + 25, + 38, + -1, + 12, + 22, + 24, + 36, + -1, + 13, + 34, + -1, + 14, + 33, + -1, + 15, + 31, + -1, + 17, + 29, + -1, + 18, + 27, + -1, + 19, + 26, + -1, + 16, + 28, + -1, + 13, + 30, + -1, + 11, + 31, + -1, + 10, + 32, + -1, + 8, + 33, + -1, + 7, + 34, + -1, + 6, + 13, + 16, + 34, + -1, + 5, + 12, + 16, + 35, + -1, + 4, + 12, + 16, + 35, + -1, + 3, + 12, + 15, + 35, + -1, + 2, + 35, + -1, + 1, + 35, + -1, + 2, + 34, + -1, + 3, + 34, + -1, + 4, + 33, + -1, + 6, + 33, + -1, + 10, + 32, + 34, + 34, + -1, + 14, + 17, + 19, + 25, + 28, + 31, + 35, + 35, + -1, + 15, + 19, + 23, + 30, + 36, + 36, + -1, + 14, + 18, + 21, + 21, + 24, + 30, + 37, + 37, + -1, + 13, + 18, + 23, + 29, + 33, + 38, + -1, + 12, + 29, + 31, + 33, + -1, + 11, + 13, + 17, + 17, + 19, + 19, + 22, + 22, + 24, + 31, + -1, + 10, + 11, + 17, + 18, + 22, + 22, + 24, + 24, + 29, + 29, + -1, + 22, + 23, + 26, + 29, + -1, + 27, + 29, + -1, + 28, + 29, + -1, + 4096, +) def display_intro(): @@ -26,9 +246,9 @@ def display_intro(): def tab(column): - """ Emulates the TAB command in BASIC. Returns a string with ASCII - codes for setting the cursor to the specified column. """ - return "\r\33[{}C".format(column) + """Emulates the TAB command in BASIC. Returns a string with ASCII + codes for setting the cursor to the specified column.""" + return f"\r\33[{column}C" def play(): @@ -71,7 +291,7 @@ def play(): # The following number, indicates the end of the segment. end = next(data) # Unlike FOR I=X TO Y, the 'stop' argument of 'range' is non-inclusive, so we must add 1 - for i in range(start, end+1, 1): + for i in range(start, end + 1, 1): # Cycle through the letters in "BUNNY" as we draw line j = i - 5 * int(i / 5) print(chr(L + bunny[j]), end="") diff --git a/19_Bunny/ruby/README.md b/19_Bunny/ruby/README.md index 1b8e6e8f2..846a6e854 100644 --- a/19_Bunny/ruby/README.md +++ b/19_Bunny/ruby/README.md @@ -8,4 +8,3 @@ There are two versions of this program here: BASIC program. * `bunny-modern.rb` takes more advantage of the features of modern tools and languages. - diff --git a/19_Bunny/ruby/bunny-faithful.rb b/19_Bunny/ruby/bunny-faithful.rb index 7f6681cb7..0aac2f71f 100644 --- a/19_Bunny/ruby/bunny-faithful.rb +++ b/19_Bunny/ruby/bunny-faithful.rb @@ -19,7 +19,7 @@ # * 0,2 draws letters between columns 0 and 2 # * 45,50 draws letters between columns 45 and 50 # * -1 starts a new line -# +# # ...and so on. # # We keep the data statements as they are and redraw the image using @@ -33,7 +33,7 @@ # the data always draws from left to right so we just keep track of # the last column written to and then add some spaces to advance to # where we need to be. -# +# # Do the thing. (We put it in a function to keep from spewing global @@ -51,7 +51,7 @@ def main # The positions to write; this is ripped from the BASIC program's # DATA statements. positions = [ - 1,2,-1,0,2,45,50,-1,0,5,43,52,-1,0,7,41,52,-1, + 1,2,-1,0,2,45,50,-1,0,5,43,52,-1,0,7,41,52,-1, 1,9,37,50,-1,2,11,36,50,-1,3,13,34,49,-1,4,14,32,48,-1, 5,15,31,47,-1,6,16,30,45,-1,7,17,29,44,-1,8,19,28,43,-1, 9,20,27,41,-1,10,21,26,40,-1,11,22,25,38,-1,12,22,24,36,-1, @@ -80,7 +80,7 @@ def main puts last_pos = 0 next - end + end # Advance to start of the range print ' '*(first - last_pos) diff --git a/19_Bunny/ruby/bunny-modern.rb b/19_Bunny/ruby/bunny-modern.rb index 6bd778ddb..d7d12fb4f 100644 --- a/19_Bunny/ruby/bunny-modern.rb +++ b/19_Bunny/ruby/bunny-modern.rb @@ -114,7 +114,7 @@ def print_bunny_text(text) # Bonus hackery: we could replace the above with this one-liner, # but it's kind of hard to understand so it may or may not be wise # to use it. - # + # # line.gsub!(/(\S)/) {|m| bunny[$~.begin(0) % bunny.size] } puts line diff --git a/20_Buzzword/csharp/Program.cs b/20_Buzzword/csharp/Program.cs index e9970d82f..17b8a6b31 100644 --- a/20_Buzzword/csharp/Program.cs +++ b/20_Buzzword/csharp/Program.cs @@ -75,7 +75,7 @@ static string GeneratePhrase() } ///

- /// Handles user input. On wrong input it displays information about + /// Handles user input. On wrong input it displays information about /// valid keys in infinite loop. /// /// True if user pressed 'Y', false if 'N'. diff --git a/20_Buzzword/java/src/UserInterface.java b/20_Buzzword/java/src/UserInterface.java index 103e88c8b..8115b2dac 100644 --- a/20_Buzzword/java/src/UserInterface.java +++ b/20_Buzzword/java/src/UserInterface.java @@ -35,7 +35,7 @@ public UserInterface(final Scanner input, final Supplier buzzwords) { this.input = input; this.output = output; - this.buzzwords = buzzwords; + this.buzzwords = buzzwords; } @Override diff --git a/20_Buzzword/javascript/buzzword.js b/20_Buzzword/javascript/buzzword.js index 80c4e51e9..55780b21c 100644 --- a/20_Buzzword/javascript/buzzword.js +++ b/20_Buzzword/javascript/buzzword.js @@ -12,10 +12,10 @@ function input() { var input_element; var input_str; - + return new Promise(function (resolve) { input_element = document.createElement("INPUT"); - + print("? "); input_element.setAttribute("type", "text"); input_element.setAttribute("length", "50"); diff --git a/20_Buzzword/perl/buzzword.pl b/20_Buzzword/perl/buzzword.pl index 75f09b3c2..41cd8e4d2 100755 --- a/20_Buzzword/perl/buzzword.pl +++ b/20_Buzzword/perl/buzzword.pl @@ -15,13 +15,13 @@ "ABILITY","BASAL","BEHAVIORAL","CHILD-CENTERED", "DIFFERENTIATED","DISCOVERY","FLEXIBLE","HETEROGENEOUS", "HOMOGENEOUS","MANIPULATIVE","MODULAR","TAVISTOCK", - "INDIVIDUALIZED","LEARNING","EVALUATIVE","OBJECTIVE", + "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" + "PERFORMANCE","REINFORCEMENT","OPEN CLASSROOM","RESOURCE", + "STRUCTURE","FACILITY","ENVIRONMENT" ); my $Y; @@ -35,5 +35,3 @@ print "COME BACK WHEN YOU NEED HELP WITH ANOTHER REPORT!\n"; exit; - - diff --git a/20_Buzzword/python/buzzword.py b/20_Buzzword/python/buzzword.py index 4de33d297..493e27300 100644 --- a/20_Buzzword/python/buzzword.py +++ b/20_Buzzword/python/buzzword.py @@ -22,21 +22,53 @@ import random - -WORDS = [ ["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"] ] +WORDS = [ + [ + "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", + ], +] # Display intro text @@ -55,14 +87,14 @@ for section in WORDS: if len(phrase) > 0: phrase += " " - phrase += section[random.randint(0, len(section)-1)] - + phrase += section[random.randint(0, len(section) - 1)] + print(phrase) print("") - + response = input("? ") try: - if response.upper()[0] != 'Y': + if response.upper()[0] != "Y": still_running = False except: still_running = False @@ -71,7 +103,6 @@ print("Come back when you need help with another report!\n") - ###################################################################### # # Porting Notes @@ -93,7 +124,7 @@ # newsletter named "EDU" that focused on using computers in an # educational setting. No surprise, then, that the buzzwords in # this program were targeted towards educators! -# +# # # Ideas for Modifications # @@ -104,10 +135,3 @@ # choose a field and pick the buzzwords accordingly. # ###################################################################### - - - - - - - diff --git a/20_Buzzword/ruby/buzzword.rb b/20_Buzzword/ruby/buzzword.rb index 3ddcf0faf..a81e0790c 100644 --- a/20_Buzzword/ruby/buzzword.rb +++ b/20_Buzzword/ruby/buzzword.rb @@ -23,12 +23,12 @@ "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", @@ -54,13 +54,13 @@ phrase << prefix[rand(prefix.length)] phrase << body[rand(body.length)] phrase << postfix[rand(postfix.length)] - + puts phrase.join(' ') puts "\n" - + print "?" response = gets - + break unless response.upcase.start_with?('Y') end @@ -75,7 +75,7 @@ # built the buzzword phrases by randomly sampling from each of the # three regions of the array (1-13, 14-26, and 27-39). # -# Instead, we're storing the words for each section in three +# Instead, we're storing the words for each section in three # separate arrays. That makes it easy to loop through the sections # to stitch the phrase together, and it easily accomodates adding # (or removing) elements from any section. They don't all need to @@ -88,7 +88,7 @@ # newsletter named "EDU" that focused on using computers in an # educational setting. No surprise, then, that the buzzwords in # this program were targeted towards educators! -# +# # # Ideas for Modifications # diff --git a/21_Calendar/csharp/Program.cs b/21_Calendar/csharp/Program.cs index 4fd2b177a..8504c2e9c 100644 --- a/21_Calendar/csharp/Program.cs +++ b/21_Calendar/csharp/Program.cs @@ -30,14 +30,14 @@ static void Main(string[] args) // the usage of Write*Line* means we do not have to specify a newline (\n) Console.WriteLine(Tab(32) + "CALENDAR"); Console.WriteLine(Tab(15) + "CREATE COMPUTING MORRISTOWN, NEW JERSEY"); - //give us some space. + //give us some space. Console.WriteLine(""); Console.WriteLine(""); Console.WriteLine(""); //establish some variables needed to print out a calculator - //the length of each month in days. On a leap year, the start of this would be + //the length of each month in days. On a leap year, the start of this would be // 0, 31, 29 to account for Feb. the 0 at the start is for days elapsed to work right in Jan. int[] monthLengths = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; // m in original source @@ -89,9 +89,9 @@ static void Main(string[] args) } header += " "; // how many days left till the year's over? - header += (365 - elapsed) + " **"; // on leap years 366 + header += (365 - elapsed) + " **"; // on leap years 366 Console.WriteLine(header); - //dates + //dates Console.WriteLine(" S M T W T F S"); Console.WriteLine(" "); @@ -107,7 +107,7 @@ static void Main(string[] args) for (int week = 1; week <= 6; week++) { Console.WriteLine(weekOutput); - weekOutput = " "; + weekOutput = " "; for (g = 1; g <= 7; g++) { //add one to the day diff --git a/21_Calendar/java/Calendar.java b/21_Calendar/java/Calendar.java index 4202a4dc6..b27f8fbda 100644 --- a/21_Calendar/java/Calendar.java +++ b/21_Calendar/java/Calendar.java @@ -6,64 +6,64 @@ *

* Note: The idea was to create a version of the 1970's BASIC game in Java, without introducing * new features - no additional text, error checking, etc has been added. - * + * * Converted from BASIC to Java by Darren Cardenas. */ - -public class Calendar { + +public class Calendar { private static final int NUM_WEEK_ROWS = 6; private static final int NUM_DAYS_PER_WEEK = 7; - private static final int NUM_MONTHS_PER_YEAR = 12; - private static final int[] daysPerMonth = { 0, 31, 28, 31, 30, 31, 30, - 31, 31, 30, 31, 30, 31 }; - + private static final int NUM_MONTHS_PER_YEAR = 12; + private static final int[] daysPerMonth = { 0, 31, 28, 31, 30, 31, 30, + 31, 31, 30, 31, 30, 31 }; + public void play() { - + showIntro(); startGame(); - - } // End of method play - + + } // End of method play + private static void showIntro() { - + System.out.println(" ".repeat(31) + "CALENDAR"); System.out.println(" ".repeat(14) + "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY"); System.out.println("\n\n"); - } // End of method showIntro - - private void startGame() { + } // End of method showIntro + + private void startGame() { int dayOfMonth = 0; int dayOfWeek = 0; int dayOfYear = 0; - int daysTotal = 0; + int daysTotal = 0; int index = 0; int month = 0; - int row = 0; - + int row = 0; + String lineContent = ""; - - for (index = 1; index <= 6; index++) { - System.out.println(""); + + for (index = 1; index <= 6; index++) { + System.out.println(""); } - + daysTotal = -1; dayOfYear = 0; - + System.out.println(""); - + // Begin loop through all months for (month = 1; month <= NUM_MONTHS_PER_YEAR; month++) { System.out.println(""); - + dayOfYear = dayOfYear + daysPerMonth[month - 1]; - + lineContent = String.format("** %-3d" + "*".repeat(18), dayOfYear); - - switch (month) { + + switch (month) { case 1: lineContent += " JANUARY "; break; @@ -75,14 +75,14 @@ private void startGame() { break; case 4: lineContent += " APRIL "; - break; - case 5: + break; + case 5: lineContent += " MAY "; - break; - case 6: + break; + case 6: lineContent += " JUNE "; - break; - case 7: + break; + case 7: lineContent += " JULY "; break; case 8: @@ -103,73 +103,73 @@ private void startGame() { default: break; } - + lineContent += "*".repeat(18) + " " + (365 - dayOfYear) + "**"; - + System.out.println(lineContent); System.out.println(""); System.out.print(" S M T W"); System.out.println(" T F S"); System.out.println(""); - + System.out.println("*".repeat(59)); // Begin loop through each week row for (row = 1; row <= NUM_WEEK_ROWS; row++) { - + System.out.println(""); - + lineContent = " "; - + // Begin loop through days of the week for (dayOfWeek = 1; dayOfWeek <= NUM_DAYS_PER_WEEK; dayOfWeek++) { - + daysTotal++; - + dayOfMonth = daysTotal - dayOfYear; - + if (dayOfMonth > daysPerMonth[month]) { row = 6; - break; + break; } - if (dayOfMonth > 0) { + if (dayOfMonth > 0) { lineContent += dayOfMonth; } - - while (lineContent.length() < (4 + 8 * dayOfWeek)) { - lineContent += " "; - } - + + while (lineContent.length() < (4 + 8 * dayOfWeek)) { + lineContent += " "; + } + } // End loop through days of the week - - if (dayOfMonth == daysPerMonth[month]) { + + if (dayOfMonth == daysPerMonth[month]) { row = 6; daysTotal += dayOfWeek; System.out.println(lineContent); break; } - + System.out.println(lineContent); - + } // End loop through each week row - - daysTotal -= dayOfWeek; - + + daysTotal -= dayOfWeek; + } // End loop through all months - - for (index = 1; index <= 6; index++) { - System.out.println(""); - } - - } // End of method startGame - + + for (index = 1; index <= 6; index++) { + System.out.println(""); + } + + } // End of method startGame + public static void main(String[] args) { - + Calendar game = new Calendar(); game.play(); - + } // End of method main - + } // End of class Calendar diff --git a/21_Calendar/javascript/calendar.js b/21_Calendar/javascript/calendar.js index 288191986..df6c90e67 100644 --- a/21_Calendar/javascript/calendar.js +++ b/21_Calendar/javascript/calendar.js @@ -63,7 +63,7 @@ for (n = 1; n <= 12; n++) { print("\n"); str = ""; for (i = 1; i <= 59; i++) - str += "*"; + str += "*"; for (week = 1; week <= 6; week++) { print(str + "\n"); str = " "; @@ -83,7 +83,7 @@ for (n = 1; n <= 12; n++) { d += g; break; } - } + } d -= g; print(str + "\n"); } diff --git a/21_Calendar/python/calendar.py b/21_Calendar/python/calendar.py index 6f3f572b8..e954d7c72 100644 --- a/21_Calendar/python/calendar.py +++ b/21_Calendar/python/calendar.py @@ -20,6 +20,7 @@ # ######################################################## + def parse_input(): """ function to parse input for weekday and leap year boolean @@ -32,7 +33,7 @@ def parse_input(): "wednesday": -3, "thursday": -4, "friday": -5, - "saturday": -6 + "saturday": -6, } day = 0 @@ -51,11 +52,11 @@ def parse_input(): while True: leap = input("IS IT A LEAP YEAR?:") - if 'y' in leap.lower(): + if "y" in leap.lower(): leap_day = True break - if 'n' in leap.lower(): + if "n" in leap.lower(): leap_day = False break @@ -66,12 +67,12 @@ def calendar(weekday, leap_year): """ function to print a year's calendar. - input: + input: _weekday_: int - the initial day of the week (0=SUN, -1=MON, -2=TUES...) _leap_year_: bool - indicates if the year is a leap year """ months_days = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] - days = 'S M T W T F S\n' + days = "S M T W T F S\n" sep = "*" * 59 years_day = 365 d = weekday @@ -80,26 +81,31 @@ def calendar(weekday, leap_year): months_days[2] = 29 years_day = 366 - months_names = [" JANUARY ", - " FEBRUARY", - " MARCH ", - " APRIL ", - " MAY ", - " JUNE ", - " JULY ", - " AUGUST ", - "SEPTEMBER", - " OCTOBER ", - " NOVEMBER", - " DECEMBER"] + months_names = [ + " JANUARY ", + " FEBRUARY", + " MARCH ", + " APRIL ", + " MAY ", + " JUNE ", + " JULY ", + " AUGUST ", + "SEPTEMBER", + " OCTOBER ", + " NOVEMBER", + " DECEMBER", + ] days_count = 0 # S in the original program # main loop for n in range(1, 13): - days_count += months_days[n-1] - print("** {} ****************** {} ****************** {} **\n".format(days_count, - months_names[n-1], years_day-days_count)) + days_count += months_days[n - 1] + print( + "** {} ****************** {} ****************** {} **\n".format( + days_count, months_names[n - 1], years_day - days_count + ) + ) print(days) print(sep) @@ -113,11 +119,11 @@ def calendar(weekday, leap_year): break if d2 <= 0: - print("{}".format(' '), end=' ') + print("{}".format(" "), end=" ") elif d2 < 10: - print(" {}".format(d2), end=' ') + print(f" {d2}", end=" ") else: - print("{}".format(d2), end=' ') + print(f"{d2}", end=" ") print() if d2 >= months_days[n]: @@ -132,9 +138,9 @@ def calendar(weekday, leap_year): def main(): - print(" "*32 + "CALENDAR") - print(" "*15 + "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY") - print("\n"*11) + print(" " * 32 + "CALENDAR") + print(" " * 15 + "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY") + print("\n" * 11) day, leap_year = parse_input() calendar(day, leap_year) diff --git a/22_Change/csharp/Program.cs b/22_Change/csharp/Program.cs index 12804731f..67c7e59b6 100644 --- a/22_Change/csharp/Program.cs +++ b/22_Change/csharp/Program.cs @@ -25,7 +25,7 @@ static void Header() ///

/// /// False if any input can't be parsed to double. Price and payment returned would be 0. - /// True if it was possible to parse inputs into doubles. Price and payment returned + /// True if it was possible to parse inputs into doubles. Price and payment returned /// would be as provided by the user. /// static (bool status, double price, double payment) GetInput() diff --git a/22_Change/javascript/change.js b/22_Change/javascript/change.js index 7c25bcbd3..d29a41718 100644 --- a/22_Change/javascript/change.js +++ b/22_Change/javascript/change.js @@ -12,10 +12,10 @@ function input() { var input_element; var input_str; - + return new Promise(function (resolve) { input_element = document.createElement("INPUT"); - + print("? "); input_element.setAttribute("type", "text"); input_element.setAttribute("length", "50"); diff --git a/23_Checkers/checkers.annotated.bas b/23_Checkers/checkers.annotated.bas index af8ffabcd..78e2e2d96 100644 --- a/23_Checkers/checkers.annotated.bas +++ b/23_Checkers/checkers.annotated.bas @@ -121,7 +121,7 @@ # Otherwise, consider u,v if s(u,v)=0 then gosub 910 - endif + endif 870 return # Evaluate jumping (x,y) to (u,v). diff --git a/23_Checkers/javascript/checkers.js b/23_Checkers/javascript/checkers.js index 4d406e0e8..14a7d3513 100644 --- a/23_Checkers/javascript/checkers.js +++ b/23_Checkers/javascript/checkers.js @@ -12,10 +12,10 @@ function input() { var input_element; var input_str; - + return new Promise(function (resolve) { input_element = document.createElement("INPUT"); - + print("? "); input_element.setAttribute("type", "text"); input_element.setAttribute("length", "50"); @@ -112,7 +112,7 @@ var s = []; for (x = 0; x <= 7; x++) s[x] = []; - + var g = -1; var data = [1, 0, 1, 0, 0, 0, -1, 0, 0, 1, 0, 0, 0, -1, 0, -1, 15]; var p = 0; diff --git a/23_Checkers/python/checkers.py b/23_Checkers/python/checkers.py index fc1008ae7..ea015861d 100644 --- a/23_Checkers/python/checkers.py +++ b/23_Checkers/python/checkers.py @@ -49,7 +49,7 @@ def get_coordinates(prompt): continue try: - x, y = [int(c) for c in response.split(",")] + x, y = (int(c) for c in response.split(",")) except ValueError as ve: print(err_msg) continue diff --git a/24_Chemist/javascript/chemist.js b/24_Chemist/javascript/chemist.js index 8d6aabf57..b71292746 100644 --- a/24_Chemist/javascript/chemist.js +++ b/24_Chemist/javascript/chemist.js @@ -12,10 +12,10 @@ function input() { var input_element; var input_str; - + return new Promise(function (resolve) { input_element = document.createElement("INPUT"); - + print("? "); input_element.setAttribute("type", "text"); input_element.setAttribute("length", "50"); diff --git a/24_Chemist/perl/chemist.pl b/24_Chemist/perl/chemist.pl index 9f75bfac4..4565da5d5 100755 --- a/24_Chemist/perl/chemist.pl +++ b/24_Chemist/perl/chemist.pl @@ -33,5 +33,3 @@ print "YOUR 9 LIVES ARE USED, BUT YOU WILL BE LONG REMEMBERED FOR\n"; print "YOUR CONTRIBUTIONS TO THE FIELD OF COMIC BOOK CHEMISTRY.\n"; exit; - - diff --git a/25_Chief/java/src/Chief.java b/25_Chief/java/src/Chief.java index 1db2eb6cc..fd9627fd0 100644 --- a/25_Chief/java/src/Chief.java +++ b/25_Chief/java/src/Chief.java @@ -203,4 +203,4 @@ private String displayTextAndGetInput(String text) { return kbScanner.next(); } -} \ No newline at end of file +} diff --git a/25_Chief/java/src/ChiefGame.java b/25_Chief/java/src/ChiefGame.java index 25ebc1bc6..000c7bc26 100644 --- a/25_Chief/java/src/ChiefGame.java +++ b/25_Chief/java/src/ChiefGame.java @@ -5,4 +5,4 @@ public static void main(String[] args) { Chief chief = new Chief(); chief.play(); } -} \ No newline at end of file +} diff --git a/25_Chief/javascript/chief.js b/25_Chief/javascript/chief.js index 98fde4198..1125a98c1 100644 --- a/25_Chief/javascript/chief.js +++ b/25_Chief/javascript/chief.js @@ -12,10 +12,10 @@ function input() { var input_element; var input_str; - + return new Promise(function (resolve) { input_element = document.createElement("INPUT"); - + print("? "); input_element.setAttribute("type", "text"); input_element.setAttribute("length", "50"); diff --git a/25_Chief/python/Chief.py b/25_Chief/python/Chief.py index 67b4eab86..d60f81806 100644 --- a/25_Chief/python/Chief.py +++ b/25_Chief/python/Chief.py @@ -1,77 +1,89 @@ def print_lightning_bolt(): - print('*'*36) - n = 24 - while n > 16: - print(' '*n + 'x x') - n -=1 - print(' '*16 + 'x xxx') - print(' '*15 + 'x x') - print(' '*14+ 'xxx x') - n -=1 - while n > 8: - print(' '*n + 'x x') - n -=1 - print(' '*8 + 'xx') - print(' '*7 +'x') - print('*'*36) + print("*" * 36) + n = 24 + while n > 16: + print(" " * n + "x x") + n -= 1 + print(" " * 16 + "x xxx") + print(" " * 15 + "x x") + print(" " * 14 + "xxx x") + n -= 1 + while n > 8: + print(" " * n + "x x") + n -= 1 + print(" " * 8 + "xx") + print(" " * 7 + "x") + print("*" * 36) def print_solution(n): - print('\n{} plus 3 gives {}. This Divided by 5 equals {}'.format(n, n+3, (n+3)/5)) - print('This times 8 gives {}. If we divide 5 and add 5.'.format(( (n+3)/5 )*8 )) - print('We get {}, which, minus 1 equals {}'.format(( ((n+3)/5)*8)/5+5, ((((n+3)/5)*8)/5+5)-1 )) + print( + "\n{} plus 3 gives {}. This Divided by 5 equals {}".format( + n, n + 3, (n + 3) / 5 + ) + ) + print(f"This times 8 gives {((n + 3) / 5) * 8}. If we divide 5 and add 5.") + print( + "We get {}, which, minus 1 equals {}".format( + (((n + 3) / 5) * 8) / 5 + 5, ((((n + 3) / 5) * 8) / 5 + 5) - 1 + ) + ) + def Game(): - print('\nTake a Number and ADD 3. Now, Divide this number by 5 and') - print('multiply by 8. Now, Divide by 5 and add the same. Subtract 1') - - resp = float(input('\nWhat do you have? ')) - comp_guess = (((resp - 4)*5)/8)*5 -3 - resp2 = input('\nI bet your number was {} was i right(Yes or No)? '.format(comp_guess)) - - if resp2 == 'Yes' or resp2 == 'YES' or resp2 == 'yes': - print('\nHuh, I Knew I was unbeatable') - print('And here is how i did it') - print_solution(comp_guess) - input('') - - else: - resp3 = float(input('\nHUH!! what was you original number? ')) - - if resp3 == comp_guess: - print('\nThat was my guess, AHA i was right') - print("Shamed to accept defeat i guess, don't worry you can master mathematics too") - print('Here is how i did it') - print_solution(comp_guess) - input('') - + print("\nTake a Number and ADD 3. Now, Divide this number by 5 and") + print("multiply by 8. Now, Divide by 5 and add the same. Subtract 1") + + resp = float(input("\nWhat do you have? ")) + comp_guess = (((resp - 4) * 5) / 8) * 5 - 3 + resp2 = input(f"\nI bet your number was {comp_guess} was i right(Yes or No)? ") + + if resp2 == "Yes" or resp2 == "YES" or resp2 == "yes": + print("\nHuh, I Knew I was unbeatable") + print("And here is how i did it") + print_solution(comp_guess) + input("") + + else: + resp3 = float(input("\nHUH!! what was you original number? ")) + + if resp3 == comp_guess: + print("\nThat was my guess, AHA i was right") + print( + "Shamed to accept defeat i guess, don't worry you can master mathematics too" + ) + print("Here is how i did it") + print_solution(comp_guess) + input("") + + else: + print("\nSo you think you're so smart, EH?") + print("Now, Watch") + print_solution(resp3) + + resp4 = input("\nNow do you believe me? ") + + if resp4 == "Yes" or resp4 == "YES" or resp4 == "yes": + print("\nOk, Lets play again sometime bye!!!!") + input("") + + else: + print("\nYOU HAVE MADE ME VERY MAD!!!!!") + print("BY THE WRATH OF THE MATHEMATICS AND THE RAGE OF THE GODS") + print("THERE SHALL BE LIGHTNING!!!!!!!") + print_lightning_bolt() + print("\nI Hope you believe me now, for your own sake") + input("") + + +if __name__ == "__main__": + + print("I am CHIEF NUMBERS FREEK, The GREAT INDIAN MATH GOD.") + play = input("\nAre you ready to take the test you called me out for(Yes or No)? ") + if play == "Yes" or play == "YES" or play == "yes": + Game() else: - print('\nSo you think you\'re so smart, EH?') - print('Now, Watch') - print_solution(resp3) - - resp4 = input('\nNow do you believe me? ') - - if resp4 == 'Yes' or resp4 == 'YES' or resp4 == 'yes': - print('\nOk, Lets play again sometime bye!!!!') - input('') - - else: - print('\nYOU HAVE MADE ME VERY MAD!!!!!') - print("BY THE WRATH OF THE MATHEMATICS AND THE RAGE OF THE GODS") - print("THERE SHALL BE LIGHTNING!!!!!!!") - print_lightning_bolt() - print('\nI Hope you believe me now, for your own sake') - input('') - -if __name__ == '__main__': - - print('I am CHIEF NUMBERS FREEK, The GREAT INDIAN MATH GOD.') - play = input('\nAre you ready to take the test you called me out for(Yes or No)? ') - if play == 'Yes' or play == 'YES' or play == 'yes': - Game() - else: - print('Ok, Nevermind. Let me go back to my great slumber, Bye') - input('') + print("Ok, Nevermind. Let me go back to my great slumber, Bye") + input("") diff --git a/26_Chomp/chomp.bas b/26_Chomp/chomp.bas index 50e5e232a..2ca7a51f0 100644 --- a/26_Chomp/chomp.bas +++ b/26_Chomp/chomp.bas @@ -3,7 +3,7 @@ 30 PRINT:PRINT:PRINT 40 DIM A(10,10) 100 REM *** THE GAME OF CHOMP *** COPYRIGHT PCC 1973 *** -110 PRINT +110 PRINT 120 PRINT "THIS IS THE GAME OF CHOMP (SCIENTIFIC AMERICAN, JAN 1973)" 130 PRINT "DO YOU WANT THE RULES (1=YES, 0=NO!)"; 140 INPUT R @@ -25,16 +25,16 @@ 300 PRINT "(INCLUDING THAT SQUARE, TOO) DISAPPEAR -- CHOMP!!" 310 PRINT "NO FAIR CHOMPING SQUARES THAT HAVE ALREADY BEEN CHOMPED," 320 PRINT "OR THAT ARE OUTSIDE THE ORIGINAL DIMENSIONS OF THE COOKIE." -330 PRINT +330 PRINT 340 PRINT "HERE WE GO..." -350 REM +350 REM 360 F=0 370 FOR I=1 TO 10 372 FOR J=1 TO 10 375 A(I,J)=0 377 NEXT J 379 NEXT I -380 PRINT +380 PRINT 390 PRINT "HOW MANY PLAYERS"; 400 INPUT P 410 I1=0 @@ -48,7 +48,7 @@ 490 IF C <= 9 THEN 530 500 PRINT "TOO MANY COLUMNS (9 IS MAXIMUM). NOW, "; 510 GOTO 470 -530 PRINT +530 PRINT 540 FOR I=1 TO R 550 FOR J=1 TO C 560 A(I,J)=1 @@ -56,7 +56,7 @@ 580 NEXT I 590 A(1,1)=-1 600 REM PRINT THE BOARD -610 PRINT +610 PRINT 620 PRINT TAB(7);"1 2 3 4 5 6 7 8 9" 630 FOR I=1 TO R 640 PRINT I;TAB(7); @@ -67,11 +67,11 @@ 690 GOTO 710 700 PRINT "P "; 710 NEXT J -720 PRINT +720 PRINT 730 NEXT I -740 PRINT +740 PRINT 750 IF F=0 THEN 770 -760 RETURN +760 RETURN 770 REM GET CHOMPS FOR EACH PLAYER IN TURN 780 LET I1=I1+1 790 LET P1=I1-INT(I1/P)*P @@ -97,7 +97,7 @@ 990 GOTO 610 1000 REM END OF GAME DETECTED IN LINE 900 1010 PRINT "YOU LOSE, PLAYER";P1 -1020 PRINT +1020 PRINT 1030 PRINT "AGAIN (1=YES, 0=NO!)"; 1040 INPUT R 1050 IF R=1 THEN 340 diff --git a/26_Chomp/java/Chomp.java b/26_Chomp/java/Chomp.java index c11a5647b..82b4e3e1c 100644 --- a/26_Chomp/java/Chomp.java +++ b/26_Chomp/java/Chomp.java @@ -88,7 +88,7 @@ private void printBoard(){ private void move(int player){ System.out.println(String.format("Player %d",(player+1))); - + String input; String [] coordinates; int x=-1,y=-1; diff --git a/26_Chomp/javascript/chomp.js b/26_Chomp/javascript/chomp.js index 652023e66..3a63bbc7a 100644 --- a/26_Chomp/javascript/chomp.js +++ b/26_Chomp/javascript/chomp.js @@ -12,10 +12,10 @@ function input() { var input_element; var input_str; - + return new Promise(function (resolve) { input_element = document.createElement("INPUT"); - + print("? "); input_element.setAttribute("type", "text"); input_element.setAttribute("length", "50"); diff --git a/26_Chomp/perl/chomp.pl b/26_Chomp/perl/chomp.pl index 34727626e..4a7bc4e59 100644 --- a/26_Chomp/perl/chomp.pl +++ b/26_Chomp/perl/chomp.pl @@ -13,7 +13,7 @@ sub main { } sub game_play { - + # the initial game set up &print_intro; my ($players,$rows,$cols) = &get_user_info; @@ -24,7 +24,7 @@ sub game_play { # continuous loop until the poison pill is swallowed until ($game_over == 1) { - if ($player > ($players-1)) { #checks to make sure we're just looping thru valid players + if ($player > ($players-1)) { #checks to make sure we're just looping thru valid players $player = 0; } $player++; @@ -39,7 +39,7 @@ sub game_play { &modify_gameboard($rows,$cols,$user_row,$user_col); &print_gameboard($rows,$cols); } - + } sub get_player_row_col { @@ -136,7 +136,7 @@ sub modify_gameboard { my ($rows,$cols,$user_row,$user_col) = @_; foreach my $row ($user_row..($rows)) { foreach my $col ($user_col..($cols)) { - $cookie[$row][$col]=" "; + $cookie[$row][$col]=" "; } } } diff --git a/26_Chomp/python/chomp.py b/26_Chomp/python/chomp.py index 56190a9e2..f46799a1e 100755 --- a/26_Chomp/python/chomp.py +++ b/26_Chomp/python/chomp.py @@ -5,7 +5,7 @@ class Canvas: - """ For drawing the cookie """ + """For drawing the cookie""" def __init__(self, width=9, height=9, fill="*"): self._buffer = [] @@ -83,8 +83,12 @@ def play_game(): player_column = -1 while player_row == -1 or player_column == -1: try: - coordinates = [int(item) for item in input( - "Coordinates of chomp (Row, Column) ").split(",")] + coordinates = [ + int(item) + for item in input("Coordinates of chomp (Row, Column) ").split( + "," + ) + ] player_row = coordinates[0] player_column = coordinates[1] diff --git a/27_Civil_War/csharp/Program.cs b/27_Civil_War/csharp/Program.cs index c79d1a3ad..b715ffebb 100644 --- a/27_Civil_War/csharp/Program.cs +++ b/27_Civil_War/csharp/Program.cs @@ -116,4 +116,4 @@ void DisplayResult() armies[1].DisplayStrategies(); } -} \ No newline at end of file +} diff --git a/27_Civil_War/java/.gitignore b/27_Civil_War/java/.gitignore index a87dc8b25..354c7850a 100644 --- a/27_Civil_War/java/.gitignore +++ b/27_Civil_War/java/.gitignore @@ -1,3 +1,3 @@ *.class *.iml -.idea/ \ No newline at end of file +.idea/ diff --git a/27_Civil_War/java/src/CivilWar.java b/27_Civil_War/java/src/CivilWar.java index 042126f64..34819ad09 100644 --- a/27_Civil_War/java/src/CivilWar.java +++ b/27_Civil_War/java/src/CivilWar.java @@ -704,4 +704,4 @@ private record HistoricalDatum(String name, ArmyPair troops, private record UnionLosses(int losses, int desertions) { } -} \ No newline at end of file +} diff --git a/27_Civil_War/javascript/civilwar.js b/27_Civil_War/javascript/civilwar.js index c16306214..f783bb17c 100644 --- a/27_Civil_War/javascript/civilwar.js +++ b/27_Civil_War/javascript/civilwar.js @@ -12,10 +12,10 @@ function input() { var input_element; var input_str; - + return new Promise(function (resolve) { input_element = document.createElement("INPUT"); - + print("? "); input_element.setAttribute("type", "text"); input_element.setAttribute("length", "50"); diff --git a/27_Civil_War/python/Civilwar.py b/27_Civil_War/python/Civilwar.py index 956abe1f8..dd1d67114 100644 --- a/27_Civil_War/python/Civilwar.py +++ b/27_Civil_War/python/Civilwar.py @@ -3,68 +3,84 @@ def tab(n): - return " "*n - - -battles = [["JULY 21, 1861. GEN. BEAUREGARD, COMMANDING THE SOUTH, MET", - "UNION FORCES WITH GEN. MCDOWELL IN A PREMATURE BATTLE AT", - "BULL RUN. GEN. JACKSON HELPED PUSH BACK THE UNION ATTACK."], - - ["APRIL 6-7, 1862. THE CONFEDERATE SURPRISE ATTACK AT", - "SHILOH FAILED DUE TO POOR ORGANIZATION."], - - ["JUNE 25-JULY 1, 1862. GENERAL LEE (CSA) UPHELD THE", - "OFFENSIVE THROUGHOUT THE BATTLE AND FORCED GEN. MCCLELLAN", - "AND THE UNION FORCES AWAY FROM RICHMOND."], - - ["AUG 29-30, 1862. THE COMBINED CONFEDERATE FORCES UNDER LEE", - "AND JACKSON DROVE THE UNION FORCES BACK INTO WASHINGTON."], - - ["SEPT 17, 1862. THE SOUTH FAILED TO INCORPORATE MARYLAND", - "INTO THE CONFEDERACY."], - - ["DEC 13, 1862. THE CONFEDERACY UNDER LEE SUCCESSFULLY", - "REPULSED AN ATTACK BY THE UNION UNDER GEN. BURNSIDE."], - - ["DEC 31, 1862. THE SOUTH UNDER GEN. BRAGG WON A CLOSE BATTLE."], - - ["MAY 1-6, 1863. THE SOUTH HAD A COSTLY VICTORY AND LOST", - "ONE OF THEIR OUTSTANDING GENERALS, 'STONEWALL' JACKSON."], - - ["JULY 4, 1863. VICKSBURG WAS A COSTLY DEFEAT FOR THE SOUTH", - "BECAUSE IT GAVE THE UNION ACCESS TO THE MISSISSIPPI."], - - ["JULY 1-3, 1863. A SOUTHERN MISTAKE BY GEN. LEE AT GETTYSBURG", - "COST THEM ONE OF THE MOST CRUCIAL BATTLES OF THE WAR."], - - ["SEPT. 15, 1863. CONFUSION IN A FOREST NEAR CHICKAMAUGA LED", - "TO A COSTLY SOUTHERN VICTORY."], - - ["NOV. 25, 1863. AFTER THE SOUTH HAD SIEGED GEN. ROSENCRANS'", - "ARMY FOR THREE MONTHS, GEN. GRANT BROKE THE SIEGE."], - - ["MAY 5, 1864. GRANT'S PLAN TO KEEP LEE ISOLATED BEGAN TO", - "FAIL HERE, AND CONTINUED AT COLD HARBOR AND PETERSBURG."], - - ["AUGUST, 1864. SHERMAN AND THREE VETERAN ARMIES CONVERGED", - "ON ATLANTA AND DEALT THE DEATH BLOW TO THE CONFEDERACY."]] + return " " * n + + +battles = [ + [ + "JULY 21, 1861. GEN. BEAUREGARD, COMMANDING THE SOUTH, MET", + "UNION FORCES WITH GEN. MCDOWELL IN A PREMATURE BATTLE AT", + "BULL RUN. GEN. JACKSON HELPED PUSH BACK THE UNION ATTACK.", + ], + [ + "APRIL 6-7, 1862. THE CONFEDERATE SURPRISE ATTACK AT", + "SHILOH FAILED DUE TO POOR ORGANIZATION.", + ], + [ + "JUNE 25-JULY 1, 1862. GENERAL LEE (CSA) UPHELD THE", + "OFFENSIVE THROUGHOUT THE BATTLE AND FORCED GEN. MCCLELLAN", + "AND THE UNION FORCES AWAY FROM RICHMOND.", + ], + [ + "AUG 29-30, 1862. THE COMBINED CONFEDERATE FORCES UNDER LEE", + "AND JACKSON DROVE THE UNION FORCES BACK INTO WASHINGTON.", + ], + [ + "SEPT 17, 1862. THE SOUTH FAILED TO INCORPORATE MARYLAND", + "INTO THE CONFEDERACY.", + ], + [ + "DEC 13, 1862. THE CONFEDERACY UNDER LEE SUCCESSFULLY", + "REPULSED AN ATTACK BY THE UNION UNDER GEN. BURNSIDE.", + ], + ["DEC 31, 1862. THE SOUTH UNDER GEN. BRAGG WON A CLOSE BATTLE."], + [ + "MAY 1-6, 1863. THE SOUTH HAD A COSTLY VICTORY AND LOST", + "ONE OF THEIR OUTSTANDING GENERALS, 'STONEWALL' JACKSON.", + ], + [ + "JULY 4, 1863. VICKSBURG WAS A COSTLY DEFEAT FOR THE SOUTH", + "BECAUSE IT GAVE THE UNION ACCESS TO THE MISSISSIPPI.", + ], + [ + "JULY 1-3, 1863. A SOUTHERN MISTAKE BY GEN. LEE AT GETTYSBURG", + "COST THEM ONE OF THE MOST CRUCIAL BATTLES OF THE WAR.", + ], + [ + "SEPT. 15, 1863. CONFUSION IN A FOREST NEAR CHICKAMAUGA LED", + "TO A COSTLY SOUTHERN VICTORY.", + ], + [ + "NOV. 25, 1863. AFTER THE SOUTH HAD SIEGED GEN. ROSENCRANS'", + "ARMY FOR THREE MONTHS, GEN. GRANT BROKE THE SIEGE.", + ], + [ + "MAY 5, 1864. GRANT'S PLAN TO KEEP LEE ISOLATED BEGAN TO", + "FAIL HERE, AND CONTINUED AT COLD HARBOR AND PETERSBURG.", + ], + [ + "AUGUST, 1864. SHERMAN AND THREE VETERAN ARMIES CONVERGED", + "ON ATLANTA AND DEALT THE DEATH BLOW TO THE CONFEDERACY.", + ], +] historical_data = [ [], ["BULL RUN", 18000, 18500, 1967, 2708, 1], - ["SHILOH", 40000., 44894., 10699, 13047, 3], - ["SEVEN DAYS", 95000., 115000., 20614, 15849, 3], - ["SECOND BULL RUN", 54000., 63000., 10000, 14000, 2], - ["ANTIETAM", 40000., 50000., 10000, 12000, 3], - ["FREDERICKSBURG", 75000., 120000., 5377, 12653, 1], - ["MURFREESBORO", 38000., 45000., 11000, 12000, 1], - ["CHANCELLORSVILLE", 32000, 90000., 13000, 17197, 2], - ["VICKSBURG", 50000., 70000., 12000, 19000, 1], - ["GETTYSBURG", 72500., 85000., 20000, 23000, 3], - ["CHICKAMAUGA", 66000., 60000., 18000, 16000, 2], - ["CHATTANOOGA", 37000., 60000., 36700., 5800, 2], - ["SPOTSYLVANIA", 62000., 110000., 17723, 18000, 2], - ["ATLANTA", 65000., 100000., 8500, 3700, 1]] + ["SHILOH", 40000.0, 44894.0, 10699, 13047, 3], + ["SEVEN DAYS", 95000.0, 115000.0, 20614, 15849, 3], + ["SECOND BULL RUN", 54000.0, 63000.0, 10000, 14000, 2], + ["ANTIETAM", 40000.0, 50000.0, 10000, 12000, 3], + ["FREDERICKSBURG", 75000.0, 120000.0, 5377, 12653, 1], + ["MURFREESBORO", 38000.0, 45000.0, 11000, 12000, 1], + ["CHANCELLORSVILLE", 32000, 90000.0, 13000, 17197, 2], + ["VICKSBURG", 50000.0, 70000.0, 12000, 19000, 1], + ["GETTYSBURG", 72500.0, 85000.0, 20000, 23000, 3], + ["CHICKAMAUGA", 66000.0, 60000.0, 18000, 16000, 2], + ["CHATTANOOGA", 37000.0, 60000.0, 36700.0, 5800, 2], + ["SPOTSYLVANIA", 62000.0, 110000.0, 17723, 18000, 2], + ["ATLANTA", 65000.0, 100000.0, 8500, 3700, 1], +] sa = {} da = {} fa = {} @@ -87,7 +103,7 @@ def tab(n): print() while True: X = input("DO YOU WANT INSTRUCTIONS? ") - if (X == "YES" or X == "NO"): + if X == "YES" or X == "NO": break print("YES OR NO -- ") @@ -192,12 +208,14 @@ def tab(n): i1 = 10 + (l - w) * 2 i2 = 10 + (w - l) * 2 # Money available - da[1] = 100 * math.floor((m1 * (100 - i1) / 2000) - * (1 + (r1 - q1) / (r1 + 1)) + 0.5) + da[1] = 100 * math.floor( + (m1 * (100 - i1) / 2000) * (1 + (r1 - q1) / (r1 + 1)) + 0.5 + ) da[2] = 100 * math.floor(m2 * (100 - i2) / 2000 + 0.5) if bs == "YES": - da[2] = 100 * math.floor((m2 * (100 - i2) / 2000) - * (1 + (r2 - q2) / (r2 + 1)) + 0.5) + da[2] = 100 * math.floor( + (m2 * (100 - i2) / 2000) * (1 + (r2 - q2) / (r2 + 1)) + 0.5 + ) # Men available m5 = math.floor(m1 * (1 + (p1 - t1) / (m3 + 1))) m6 = math.floor(m2 * (1 + (p2 - t2) / (m4 + 1))) @@ -209,7 +227,7 @@ def tab(n): print() print(f"THIS IS THE BATTLE OF {cs}") if xs != "NO": - print("\n".join(battles[a-1])) + print("\n".join(battles[a - 1])) else: print(cs + " INSTANT REPLAY") @@ -222,7 +240,7 @@ def tab(n): print() # ONLY IN PRINTOUT IS CONFED INFLATION = I1 + 15 % # IF TWO GENERALS, INPUT CONFED, FIRST - for i in range(1, d+1): + for i in range(1, d + 1): if bs == "YES" and i == 1: print("CONFEDERATE GENERAL---", end="") print("HOW MUCH DO YOU WISH TO SPEND FOR") @@ -256,15 +274,14 @@ def tab(n): break print("UNION GENERAL---", end="") - for z in range(1, d+1): + for z in range(1, d + 1): if bs == "YES": if z == 1: print("CONFEDERATE ", end="") else: print(" UNION ", end="") # Find morale - o = ((2 * math.pow(fa[z], 2) + - math.pow(ha[z], 2)) / math.pow(f1, 2) + 1) + o = (2 * math.pow(fa[z], 2) + math.pow(ha[z], 2)) / math.pow(f1, 2) + 1 if o >= 10: print("MORALE IS HIGH") elif o >= 5: @@ -291,7 +308,7 @@ def tab(n): if bs != "YES": while True: y = int(input("YOUR STRATEGY ")) - if (abs(y - 3) < 3): + if abs(y - 3) < 3: break print(f"STRATEGY {y} NOT ALLOWED.") if y == 5: @@ -317,7 +334,7 @@ def tab(n): print(y2) else: for i in range(1, 3): - if (i == 1): + if i == 1: print("CONFEDERATE STRATEGY ? ", end="") while True: y = int(input()) @@ -325,10 +342,10 @@ def tab(n): break print(f"STRATEGY {y} NOT ALLOWED.") print("YOUR STRATEGY ? ", end="") - if (i == 2): + if i == 2: y2 = y y = y1 - if (y2 != 5): + if y2 != 5: break else: y1 = y @@ -356,36 +373,42 @@ def tab(n): e = 7 * c5 / 13 u = 1 - if (d == 1): + if d == 1: c6 = math.floor(17 * c2 * c1 / (c5 * 20)) e2 = 5 * o print("CASUALTIES\t" + str(c5) + "\t\t" + str(c6)) print("DESERTIONS\t" + str(math.floor(e)) + "\t\t" + str(math.floor(e2))) print() - if (bs == "YES"): + if bs == "YES": print("COMPARED TO THE ACTUAL CASUALTIES AT " + str(cs)) - print("CONFEDERATE: " + str(math.floor(100 * - (c5 / c1) + 0.5)) + "% OF THE ORIGINAL") - print("UNION: " + str(math.floor(100 * - (c6 / c2) + 0.5)) + "% OF THE ORIGINAL") + print( + "CONFEDERATE: " + + str(math.floor(100 * (c5 / c1) + 0.5)) + + "% OF THE ORIGINAL" + ) + print( + "UNION: " + + str(math.floor(100 * (c6 / c2) + 0.5)) + + "% OF THE ORIGINAL" + ) print() # Find who won - if (u == 1 and u2 == 1 or (u != 1 and u2 != 1 and c5 + e == c6 + e2)): + if u == 1 and u2 == 1 or (u != 1 and u2 != 1 and c5 + e == c6 + e2): print("BATTLE OUTCOME UNRESOLVED") w0 += 1 - elif (u == 1 or (u != 1 and u2 != 1 and c5 + e > c6 + e2)): + elif u == 1 or (u != 1 and u2 != 1 and c5 + e > c6 + e2): print("THE UNION WINS " + str(cs)) if a != 0: l += 1 else: print("THE CONFEDERACY WINS " + str(cs)) - if (a != 0): + if a != 0: w += 1 # Lines 2530 to 2590 from original are unreachable. - if (a != 0): + if a != 0: t1 += c5 + e t2 += c6 + e2 p1 += c1 @@ -402,7 +425,7 @@ def tab(n): s = 3 s0 = 0 for i in range(1, 5): - if (sa[i] <= 5): + if sa[i] <= 5: continue sa[i] -= 5 s0 += s @@ -420,12 +443,12 @@ def tab(n): print() print() print(f"THE CONFEDERACY HAS WON {w} BATTLES AND LOST {l}") -if (y == 5 or (y2 != 5 and w <= l)): +if y == 5 or (y2 != 5 and w <= l): print("THE UNION HAS WON THE WAR") else: print("THE CONFEDERACY HAS WON THE WAR") print() -if (r1 > 0): +if r1 > 0: print(f"FOR THE {w + l + w0} BATTLES FOUGHT (EXCLUDING RERUNS)") print(" \t \t ") print("CONFEDERACY\t UNION") @@ -433,8 +456,9 @@ def tab(n): print(f"SIMULATED LOSSES\t{math.floor(t1 + 0.5)}\t{math.floor(t2 + 0.5)}") print() print( - f" % OF ORIGINAL\t{math.floor(100 * (t1 / p1) + 0.5)}\t{math.floor(100 * (t2 / p2) + 0.5)}") - if (bs != "YES"): + f" % OF ORIGINAL\t{math.floor(100 * (t1 / p1) + 0.5)}\t{math.floor(100 * (t2 / p2) + 0.5)}" + ) + if bs != "YES": print() print("UNION INTELLIGENCE SUGGEST THAT THE SOUTH USED") print("STRATEGIES 1, 2, 3, 4 IN THE FOLLOWING PERCENTAGES") diff --git a/28_Combat/combat.bas b/28_Combat/combat.bas index a42934981..c5fdf9b3e 100644 --- a/28_Combat/combat.bas +++ b/28_Combat/combat.bas @@ -31,7 +31,7 @@ 150 PRINT "YOU LOST";INT(X/3);"MEN, BUT I LOST ";INT(2*D/3) 155 A=INT(A-X/3) 160 D=0 -165 GOTO 500 +165 GOTO 500 200 IF X>B THEN 20 210 IF XB THEN 1030 +1700 IF T>B THEN 1030 1710 IF TC THEN 1030 -1810 IF T>F/2 THEN 1830 +1800 IF T>C THEN 1030 +1810 IF T>F/2 THEN 1830 1820 GOTO 1850 1830 PRINT "MY NAVY AND AIR FORCE IN A COMBINED ATTACK LEFT" 1831 PRINT "YOUR COUNTRY IN SHAMBLES." diff --git a/28_Combat/java/Combat.java b/28_Combat/java/Combat.java index 11b4ae42e..e77f9ec64 100644 --- a/28_Combat/java/Combat.java +++ b/28_Combat/java/Combat.java @@ -9,52 +9,52 @@ *

* Note: The idea was to create a version of the 1970's BASIC game in Java, without introducing * new features - no additional text, error checking, etc has been added. - * + * * Converted from BASIC to Java by Darren Cardenas. */ public class Combat { - + private static final int MAX_UNITS = 72000; // Maximum number of total units per player - + private final Scanner scan; // For user input private boolean planeCrashWin = false; - + private int usrArmy = 0; // Number of user Army units private int usrNavy = 0; // Number of user Navy units private int usrAir = 0; // Number of user Air Force units private int cpuArmy = 30000; // Number of cpu Army units private int cpuNavy = 20000; // Number of cpu Navy units private int cpuAir = 22000; // Number of cpu Air Force units - + public Combat() { - - scan = new Scanner(System.in); - - } // End of constructor Combat - + + scan = new Scanner(System.in); + + } // End of constructor Combat + public void play() { - + showIntro(); getForces(); attackFirst(); attackSecond(); - - } // End of method play - + + } // End of method play + private static void showIntro() { - + System.out.println(" ".repeat(32) + "COMBAT"); System.out.println(" ".repeat(14) + "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY"); System.out.println("\n\n"); System.out.println("I AM AT WAR WITH YOU."); System.out.println("WE HAVE " + MAX_UNITS + " SOLDIERS APIECE.\n"); - - } // End of method showIntro - + + } // End of method showIntro + private void getForces() { - + do { System.out.println("DISTRIBUTE YOUR FORCES."); System.out.println(" ME YOU"); @@ -63,24 +63,24 @@ private void getForces() { System.out.print("NAVY " + cpuNavy + " ? "); usrNavy = scan.nextInt(); System.out.print("A. F. " + cpuAir + " ? "); - usrAir = scan.nextInt(); - + usrAir = scan.nextInt(); + } while ((usrArmy + usrNavy + usrAir) > MAX_UNITS); // Avoid exceeding the maximum number of total units - - } // End of method getForces - + + } // End of method getForces + private void attackFirst() { - + int numUnits = 0; - int unitType = 0; - + int unitType = 0; + do { System.out.println("YOU ATTACK FIRST. TYPE (1) FOR ARMY; (2) FOR NAVY;"); System.out.println("AND (3) FOR AIR FORCE."); System.out.print("? "); unitType = scan.nextInt(); } while ((unitType < 1) || (unitType > 3)); // Avoid out-of-range values - + do { System.out.println("HOW MANY MEN"); System.out.print("? "); @@ -93,15 +93,15 @@ private void attackFirst() { // Begin handling deployment type switch (unitType) { case 1: // Army deployed - + if (numUnits < (usrArmy / 3.0)) { // User deployed less than one-third of their Army units System.out.println("YOU LOST " + numUnits + " MEN FROM YOUR ARMY."); - usrArmy = usrArmy - numUnits; + usrArmy = usrArmy - numUnits; } else if (numUnits < (2.0 * usrArmy / 3.0)) { // User deployed less than two-thirds of their Army units System.out.println("YOU LOST " + (int) Math.floor(numUnits / 3.0) + " MEN, BUT I LOST " + (int) Math.floor(2.0 * cpuArmy / 3.0)); usrArmy = (int) Math.floor(usrArmy - numUnits / 3.0); - cpuArmy = 0; + cpuArmy = 0; } else { // User deployed two-thirds or more of their Army units System.out.println("YOU SUNK ONE OF MY PATROL BOATS, BUT I WIPED OUT TWO"); @@ -109,34 +109,34 @@ else if (numUnits < (2.0 * usrArmy / 3.0)) { // User deployed less than two-thi usrArmy = (int) Math.floor(usrArmy / 3.0); usrAir = (int) Math.floor(usrAir / 3.0); cpuNavy = (int) Math.floor(2.0 * cpuNavy / 3.0); - } + } break; - + case 2: // Navy deployed - + if (numUnits < (cpuNavy / 3.0)) { // User deployed less than one-third relative to cpu Navy units System.out.println("YOUR ATTACK WAS STOPPED!"); - usrNavy = usrNavy - numUnits; - } + usrNavy = usrNavy - numUnits; + } else if (numUnits < (2.0 * cpuNavy / 3.0)) { // User deployed less than two-thirds relative to cpu Navy units - System.out.println("YOU DESTROYED " + (int) Math.floor(2.0 * cpuNavy / 3.0) + " OF MY ARMY."); + System.out.println("YOU DESTROYED " + (int) Math.floor(2.0 * cpuNavy / 3.0) + " OF MY ARMY."); cpuNavy = (int) Math.floor(cpuNavy / 3.0); - } + } else { // User deployed two-thirds or more relative to cpu Navy units System.out.println("YOU SUNK ONE OF MY PATROL BOATS, BUT I WIPED OUT TWO"); System.out.println("OF YOUR AIR FORCE BASES AND 3 ARMY BASES."); usrArmy = (int) Math.floor(usrArmy / 3.0); usrAir = (int) Math.floor(usrAir / 3.0); cpuNavy = (int) Math.floor(2.0 * cpuNavy / 3.0); - } + } break; - + case 3: // Air Force deployed - + if (numUnits < (usrAir / 3.0)) { // User deployed less than one-third of their Air Force units System.out.println("YOUR ATTACK WAS WIPED OUT."); - usrAir = usrAir - numUnits; - } + usrAir = usrAir - numUnits; + } else if (numUnits < (2.0 * usrAir / 3.0)) { // User deployed less than two-thirds of their Air Force units System.out.println("WE HAD A DOGFIGHT. YOU WON - AND FINISHED YOUR MISSION."); cpuArmy = (int) Math.floor(2.0 * cpuArmy / 3.0); @@ -145,22 +145,22 @@ else if (numUnits < (2.0 * usrAir / 3.0)) { // User deployed less than two-thir } else { // User deployed two-thirds or more of their Air Force units System.out.println("YOU WIPED OUT ONE OF MY ARMY PATROLS, BUT I DESTROYED"); - System.out.println("TWO NAVY BASES AND BOMBED THREE ARMY BASES."); + System.out.println("TWO NAVY BASES AND BOMBED THREE ARMY BASES."); usrArmy = (int) Math.floor(usrArmy / 4.0); usrNavy = (int) Math.floor(usrNavy / 3.0); cpuArmy = (int) Math.floor(2.0 * cpuArmy / 3.0); - } - break; - + } + break; + } // End handling deployment type - + } // End of method attackFirst - + private void attackSecond() { - + int numUnits = 0; - int unitType = 0; - + int unitType = 0; + System.out.println(""); System.out.println(" YOU ME"); System.out.print("ARMY "); @@ -169,14 +169,14 @@ private void attackSecond() { System.out.format("%-14s%s\n", usrNavy, cpuNavy); System.out.print("A. F. "); System.out.format("%-14s%s\n", usrAir, cpuAir); - + do { System.out.println("WHAT IS YOUR NEXT MOVE?"); System.out.println("ARMY=1 NAVY=2 AIR FORCE=3"); System.out.print("? "); unitType = scan.nextInt(); } while ((unitType < 1) || (unitType > 3)); // Avoid out-of-range values - + do { System.out.println("HOW MANY MEN"); System.out.print("? "); @@ -184,85 +184,85 @@ private void attackSecond() { } while ((numUnits < 0) || // Avoid negative values ((unitType == 1) && (numUnits > usrArmy)) || // Avoid exceeding the number of available Army units ((unitType == 2) && (numUnits > usrNavy)) || // Avoid exceeding the number of available Navy units - ((unitType == 3) && (numUnits > usrAir))); // Avoid exceeding the number of available Air Force units + ((unitType == 3) && (numUnits > usrAir))); // Avoid exceeding the number of available Air Force units // Begin handling deployment type switch (unitType) { case 1: // Army deployed - + if (numUnits < (cpuArmy / 2.0)) { // User deployed less than half relative to cpu Army units System.out.println("I WIPED OUT YOUR ATTACK!"); - usrArmy = usrArmy - numUnits; + usrArmy = usrArmy - numUnits; } else { // User deployed half or more relative to cpu Army units System.out.println("YOU DESTROYED MY ARMY!"); cpuArmy = 0; - } + } break; - + case 2: // Navy deployed - + if (numUnits < (cpuNavy / 2.0)) { // User deployed less than half relative to cpu Navy units System.out.println("I SUNK TWO OF YOUR BATTLESHIPS, AND MY AIR FORCE"); System.out.println("WIPED OUT YOUR UNGUARDED CAPITOL."); usrArmy = (int) Math.floor(usrArmy / 4.0); - usrNavy = (int) Math.floor(usrNavy / 2.0); - } + usrNavy = (int) Math.floor(usrNavy / 2.0); + } else { // User deployed half or more relative to cpu Navy units System.out.println("YOUR NAVY SHOT DOWN THREE OF MY XIII PLANES,"); System.out.println("AND SUNK THREE BATTLESHIPS."); cpuAir = (int) Math.floor(2.0 * cpuAir / 3.0); - cpuNavy = (int) Math.floor(cpuNavy / 2.0); - } + cpuNavy = (int) Math.floor(cpuNavy / 2.0); + } break; - + case 3: // Air Force deployed - + if (numUnits > (cpuAir / 2.0)) { // User deployed more than half relative to cpu Air Force units System.out.println("MY NAVY AND AIR FORCE IN A COMBINED ATTACK LEFT"); System.out.println("YOUR COUNTRY IN SHAMBLES."); usrArmy = (int) Math.floor(usrArmy / 3.0); usrNavy = (int) Math.floor(usrNavy / 3.0); usrAir = (int) Math.floor(usrAir / 3.0); - } + } else { // User deployed half or less relative to cpu Air Force units System.out.println("ONE OF YOUR PLANES CRASHED INTO MY HOUSE. I AM DEAD."); System.out.println("MY COUNTRY FELL APART."); planeCrashWin = true; - } + } break; - + } // End handling deployment type - + // Suppress message for plane crashes if (planeCrashWin == false) { System.out.println(""); System.out.println("FROM THE RESULTS OF BOTH OF YOUR ATTACKS,"); } - + // User wins - if ((planeCrashWin == true) || + if ((planeCrashWin == true) || ((usrArmy + usrNavy + usrAir) > ((int) Math.floor((3.0 / 2.0 * (cpuArmy + cpuNavy + cpuAir)))))) { - System.out.println("YOU WON, OH! SHUCKS!!!!"); + System.out.println("YOU WON, OH! SHUCKS!!!!"); } // User loses - else if ((usrArmy + usrNavy + usrAir) < ((int) Math.floor((2.0 / 3.0 * (cpuArmy + cpuNavy + cpuAir))))) { // User loss + else if ((usrArmy + usrNavy + usrAir) < ((int) Math.floor((2.0 / 3.0 * (cpuArmy + cpuNavy + cpuAir))))) { // User loss System.out.println("YOU LOST-I CONQUERED YOUR COUNTRY. IT SERVES YOU"); System.out.println("RIGHT FOR PLAYING THIS STUPID GAME!!!"); } // Peaceful outcome - else { + else { System.out.println("THE TREATY OF PARIS CONCLUDED THAT WE TAKE OUR"); System.out.println("RESPECTIVE COUNTRIES AND LIVE IN PEACE."); - } - + } + } // End of method attackSecond - + public static void main(String[] args) { - + Combat combat = new Combat(); combat.play(); - + } // End of method main - -} // End of class Combat \ No newline at end of file + +} // End of class Combat diff --git a/28_Combat/javascript/combat.js b/28_Combat/javascript/combat.js index a2e43c71c..ef2d3030e 100644 --- a/28_Combat/javascript/combat.js +++ b/28_Combat/javascript/combat.js @@ -12,10 +12,10 @@ function input() { var input_element; var input_str; - + return new Promise(function (resolve) { input_element = document.createElement("INPUT"); - + print("? "); input_element.setAttribute("type", "text"); input_element.setAttribute("length", "50"); diff --git a/28_Combat/python/combat.py b/28_Combat/python/combat.py index 3d0f120e1..610cec0fb 100644 --- a/28_Combat/python/combat.py +++ b/28_Combat/python/combat.py @@ -44,17 +44,21 @@ def attackFirst(): while True: print("YOU ATTACK FIRST. TYPE (1) FOR ARMY; (2) FOR NAVY;") print("AND (3) FOR AIR FORCE.") - print("?", end=' ') + print("?", end=" ") unitType = int(input()) if not (unitType < 1 or unitType > 3): break while True: print("HOW MANY MEN") - print("?", end=' ') + print("?", end=" ") numUnits = int(input()) - if not ((numUnits < 0) or ((unitType == 1) and (numUnits > usrArmy)) or ( - (unitType == 2) and (numUnits > usrNavy)) or ((unitType == 3) and (numUnits > usrAir))): + if not ( + (numUnits < 0) + or ((unitType == 1) and (numUnits > usrArmy)) + or ((unitType == 2) and (numUnits > usrNavy)) + or ((unitType == 3) and (numUnits > usrAir)) + ): break if unitType == 1: @@ -62,7 +66,12 @@ def attackFirst(): print("YOU LOST " + str(numUnits) + " MEN FROM YOUR ARMY.") usrArmy = usrArmy - numUnits elif numUnits < (2 * usrArmy / 3): - print("YOU LOST " + str(int(numUnits / 3)) + " MEN, BUT I LOST " + str(int(2 * cpuArmy / 3))) + print( + "YOU LOST " + + str(int(numUnits / 3)) + + " MEN, BUT I LOST " + + str(int(2 * cpuArmy / 3)) + ) usrArmy = int(usrArmy - (numUnits / 3)) cpuArmy = 0 else: @@ -123,39 +132,44 @@ def attackSecond(): unitType = int(input()) if not ((unitType < 1) or (unitType > 3)): break - + while True: print("HOW MANY MEN") print("? ", end="") numUnits = int(input()) - if not((numUnits < 0) or ((unitType == 1) and (numUnits > usrArmy)) or ((unitType == 2) and (numUnits > usrNavy)) or ((unitType == 3) and (numUnits > usrAir))): + if not ( + (numUnits < 0) + or ((unitType == 1) and (numUnits > usrArmy)) + or ((unitType == 2) and (numUnits > usrNavy)) + or ((unitType == 3) and (numUnits > usrAir)) + ): break if unitType == 1: - if numUnits < (cpuArmy/2): + if numUnits < (cpuArmy / 2): print("I WIPED OUT YOUR ATTACK!") usrArmy = usrArmy - numUnits else: print("YOU DESTROYED MY ARMY!") cpuArmy = 0 elif unitType == 2: - if numUnits < (cpuNavy/2): + if numUnits < (cpuNavy / 2): print("I SUNK TWO OF YOUR BATTLESHIPS, AND MY AIR FORCE") print("WIPED OUT YOUR UNGUARDED CAPITOL.") - usrArmy = int(usrArmy/4) - usrNavy = int(usrNavy/2) + usrArmy = int(usrArmy / 4) + usrNavy = int(usrNavy / 2) else: print("YOUR NAVY SHOT DOWN THREE OF MY XIII PLANES,") print("AND SUNK THREE BATTLESHIPS.") - cpuAir = int(2*cpuAir/3) - cpuNavy = int(cpuNavy/2) + cpuAir = int(2 * cpuAir / 3) + cpuNavy = int(cpuNavy / 2) elif unitType == 3: - if numUnits > (cpuAir/2): + if numUnits > (cpuAir / 2): print("MY NAVY AND AIR FORCE IN A COMBINED ATTACK LEFT") print("YOUR COUNTRY IN SHAMBLES.") - usrArmy = int(usrArmy/3) - usrNavy = int(usrNavy/3) - usrAir = int(usrAir/3) + usrArmy = int(usrArmy / 3) + usrNavy = int(usrNavy / 3) + usrAir = int(usrAir / 3) else: print("ONE OF YOUR PLANES CRASHED INTO MY HOUSE. I AM DEAD.") print("MY COUNTRY FELL APART.") @@ -165,9 +179,11 @@ def attackSecond(): print("") print("FROM THE RESULTS OF BOTH OF YOUR ATTACKS,") - if (planeCrashWin == True) or ((usrArmy + usrNavy + usrAir) > (int(3/2*(cpuArmy + cpuNavy + cpuAir)))): + if (planeCrashWin == True) or ( + (usrArmy + usrNavy + usrAir) > (int(3 / 2 * (cpuArmy + cpuNavy + cpuAir))) + ): print("YOU WON, OH! SHUCKS!!!!") - elif (usrArmy + usrNavy + usrAir) < int(2/3*(cpuArmy + cpuNavy + cpuAir)): + elif (usrArmy + usrNavy + usrAir) < int(2 / 3 * (cpuArmy + cpuNavy + cpuAir)): print("YOU LOST-I CONQUERED YOUR COUNTRY. IT SERVES YOU") print("RIGHT FOR PLAYING THIS STUPID GAME!!!") else: @@ -180,6 +196,7 @@ def main(): getForces() attackFirst() attackSecond() - -if __name__ == '__main__': - main() \ No newline at end of file + + +if __name__ == "__main__": + main() diff --git a/29_Craps/README.md b/29_Craps/README.md index 3c45c62bc..7a08b1562 100644 --- a/29_Craps/README.md +++ b/29_Craps/README.md @@ -17,12 +17,12 @@ As published in Basic Computer Games (1978): Downloaded from Vintage Basic at http://www.vintage-basic.net/games.html - + ### Comments on the BASIC code for re-implementers. 15 LET R=0 -`R` is a variable that tracks winnings and losings. Unlike other games that -start out with a lump sum of cash to spend this game assumes the user has as +`R` is a variable that tracks winnings and losings. Unlike other games that +start out with a lump sum of cash to spend this game assumes the user has as much money as they want and we only track how much they lost or won. 21 LET T=1 @@ -31,13 +31,13 @@ much money as they want and we only track how much they lost or won. 24 LET X=(RND(0)) 25 LET T =T+1 26 IF T<=Z THEN 24 -This block of code does nothing other than try to scramble the random number -generator. Random number generation is not random, they are generated from the +This block of code does nothing other than try to scramble the random number +generator. Random number generation is not random, they are generated from the previous generated number. Because of the slow speed of these systems back then, -gaming random number generators was a concern, mostly for gameplay quality. +gaming random number generators was a concern, mostly for gameplay quality. If you could know the "seed value" to the generator then you could effectively -know how to get the exact same dice rolls to happen and change your bet to -maximize your winnings and minimize your losses. +know how to get the exact same dice rolls to happen and change your bet to +maximize your winnings and minimize your losses. The first reason this is an example of bad coding practice is the user is asked to input a number but no clue is given as to the use of this number. This number @@ -45,38 +45,38 @@ has no bearing on the game and as we'll see only has bearing on the internal implementation of somehow trying to get an un-game-able seed for the random number generator (since all future random numbers generated are based off this seed value.) -The `RND(1)` command generates a number from a seed value that is always +The `RND(1)` command generates a number from a seed value that is always the same, everytime, from when the machine is booted up (old C64 behavior). In order to avoid the same dice rolls being generated, a special call to `RND(-TI)` would initialize the random generator with something else. But RND(-TI) is not -a valid command on all systems. So `RND(0)`, which generates a random number -from the system clock is used. But technically this could be gamed because the +a valid command on all systems. So `RND(0)`, which generates a random number +from the system clock is used. But technically this could be gamed because the system clock was driven by the bootup time, there wasn't a BIOS battery on these -systems that kept an internal real time clock going even when the system was +systems that kept an internal real time clock going even when the system was turned off, unlike your regular PC. Therefore, in order to ensure as true randomness as possible, insert human reaction time by asking for human input. -But a human could just be holding down the enter key on bootup and that would -just skip any kind of multi-millisecond variance assigned by a natural human -reaction time. So, paranoia being a great motivator, a number is asked of the +But a human could just be holding down the enter key on bootup and that would +just skip any kind of multi-millisecond variance assigned by a natural human +reaction time. So, paranoia being a great motivator, a number is asked of the user to avoid just holding down the enter key which negates the timing variance -of a human reaction. +of a human reaction. What comes next is a bit of nonsense. The block of code loops a counter, recalling -the `RND(0)` function (and thus reseeding it with the system clock value) +the `RND(0)` function (and thus reseeding it with the system clock value) and then comparing the counter to the user's number input -in order to bail out of the loop. Because the `RND(0)` function is based off the -system clock and the loop of code has no branching other than the bailout -condition, the loop also takes a fixed amount of time to execute, thus making +in order to bail out of the loop. Because the `RND(0)` function is based off the +system clock and the loop of code has no branching other than the bailout +condition, the loop also takes a fixed amount of time to execute, thus making repeated calls to `RND(0)` predictive and this scheming to get a better random number is pointless. Furthermore, the loop is based on the number the user inputs -so a huge number like ten million causes a very noticable delay and leaves the +so a huge number like ten million causes a very noticable delay and leaves the user wondering if the program has errored. The author could have simply called `RND(0)` once and used a prompt that made more sense like asking for the users -name and then using that name in the game's replies. +name and then using that name in the game's replies. -It is advised that you use whatever your languages' random number generator -provides and simply skip trying to recreate this bit of nonsense including +It is advised that you use whatever your languages' random number generator +provides and simply skip trying to recreate this bit of nonsense including the user input. 27 PRINT"INPUT THE AMOUNT OF YOUR WAGER."; @@ -85,20 +85,20 @@ the user input. 40 LET E=INT(7*RND(1)) 41 LET S=INT(7*RND(1)) 42 LET X=E+S - .... a bit later .... - 60 IF X=1 THEN 40 + .... a bit later .... + 60 IF X=1 THEN 40 65 IF X=0 THEN 40 - + `F` is a variable that represents the users wager for this betting round. `E` and `S` represent the two individual and random dice being rolled. This code is actually wrong because it returns a value between 0 and 6. `X` is the sum of these dice rolls. As you'll see though further down in the code, if `X` is zero or one it re-rolls the dice to maintain a potential outcome of the sum of two dice between 2 and 12. This skews the normal distribution -of dice values to favor lower numbers because it does not consider that `E` +of dice values to favor lower numbers because it does not consider that `E` could be zero and `S` could be 2 or higher. To show this skewing of values -you can run the `distribution.bas` program which creates a histogram of the +you can run the `distribution.bas` program which creates a histogram of the distribution of the bad dice throw code and proper dice throw code. Here are the results: @@ -110,20 +110,20 @@ Here are the results: THE INT(6*RND(1)+1) DISTRIBUTION 2 3 4 5 6 7 8 9 10 11 12 2788 5466 8363 11072 13947 16656 13884 11149 8324 5561 2790 -If the dice rolls are fair then we should see the largest occurrence be a 7 and +If the dice rolls are fair then we should see the largest occurrence be a 7 and the smallest should be 2 and 12. Furthermore the occurrences should be -symetrical meaning there should be roughly the same amount of 2's as 12's, the +symetrical meaning there should be roughly the same amount of 2's as 12's, the same amount of 3's as 11's, 4's as 10's and so on until you reach the middle, 7. But notice in the skewed dice roll, 6 is the most rolled number not 7, and the -rest of the numbers are not symetrical, there are many more 2's than 12's. -So the lesson is test your code. +rest of the numbers are not symetrical, there are many more 2's than 12's. +So the lesson is test your code. The proper way to model a dice throw, in almost every language is `INT(6*RND(1)+1)` or `INT(6*RND(1))+1` -SideNote: `X` was used already in the -previous code block discussed but its value was never used. This is another -poor coding practice: **Don't reuse variable names for different purposes.** +SideNote: `X` was used already in the +previous code block discussed but its value was never used. This is another +poor coding practice: **Don't reuse variable names for different purposes.** 50 IF X=7 THEN 180 55 IF X=11 THEN 180 @@ -147,17 +147,17 @@ as long as the correct dice algorithm is also changed. 62 IF X=2 THEN 195 .... 70 IF X=2 THEN 200 -The check for a 2 has already been made and the jump is done. Line 70 is -therefore redundant and can be left out. The purpose of line 62 is only to -print a special output, "SNAKE EYES!" which we'll see in the next block creates -duplicate code. +The check for a 2 has already been made and the jump is done. Line 70 is +therefore redundant and can be left out. The purpose of line 62 is only to +print a special output, "SNAKE EYES!" which we'll see in the next block creates +duplicate code. Lines 125-170 are also pointlessly checked because we know previous values have been ruled out, only these last values must remain, and they are all going to -the same place, line 220. Line 125-170 could have simply been replaced with +the same place, line 220. Line 125-170 could have simply been replaced with `GOTO 220` - - + + 180 PRINT X "- NATURAL....A WINNER!!!!" 185 PRINT X"PAYS EVEN MONEY, YOU WIN"F"DOLLARS" @@ -169,17 +169,17 @@ the same place, line 220. Line 125-170 could have simply been replaced with 200 PRINT X " - CRAPS...YOU LOSE." 205 PRINT "YOU LOSE"F"DOLLARS." 206 LET F=0-F - 210 LET R= R+F + 210 LET R= R+F 211 GOTO 320 -This bit of code manages instant wins or losses due to 7,11 or 2,3,12. As -mentioned previously, lines 196 and 197 are essentially the same as lines +This bit of code manages instant wins or losses due to 7,11 or 2,3,12. As +mentioned previously, lines 196 and 197 are essentially the same as lines 205 and 206. A simpler code would be just to jump after printing the special message of "SNAKE EYES!" to line 205. Lines 197 and 206 just negate the wager by subtracting it from zero. Just saying -`F = -F` would have sufficed. Line 210 updates your running total of winnings -or losses with this bet. +`F = -F` would have sufficed. Line 210 updates your running total of winnings +or losses with this bet. 220 PRINT X "IS THE POINT. I WILL ROLL AGAIN" 230 LET H=INT(7*RND(1)) @@ -190,15 +190,15 @@ or losses with this bet. 255 IF O=0 THEN 230 This code sets the point, the number you must re-roll to win without rolling -a 7, the most probable number to roll. Except in this case again, it has the +a 7, the most probable number to roll. Except in this case again, it has the same incorrect dice rolling code and therefore 6 is the most probable number to roll. The concept of DRY (don't repeat yourself) is a coding practice which encourages non-duplication of code because if there is an error in the code, it can be fixed in one place and not multiple places like in this code. The scenario -might be that a programmer sees some wrong code, fixes it, but neglects to -consider that there might be duplicates of the same wrong code elsewhere. If +might be that a programmer sees some wrong code, fixes it, but neglects to +consider that there might be duplicates of the same wrong code elsewhere. If you practice DRY then you never worry much about behaviors in your code diverging -due to duplicate code snippets. +due to duplicate code snippets. 260 IF O=X THEN 310 270 PRINT O " - NO POINT. I WILL ROLL AGAIN" @@ -213,15 +213,12 @@ due to duplicate code snippets. 312 LET F=2*F 313 GOTO 210 -This is the code to keep rolling until the point is made or a seven is rolled. +This is the code to keep rolling until the point is made or a seven is rolled. Again we see the negated `F` wager and lose message duplicated. This code could have been reorganized using a subroutine, or in BASIC, the GOSUB command, but -in your language its most likely just known as a function or method. You can -do a `grep -r 'GOSUB'` from the root directory to see other BASIC programs in +in your language its most likely just known as a function or method. You can +do a `grep -r 'GOSUB'` from the root directory to see other BASIC programs in this set that use GOSUB. The rest of the code if fairly straight forward, replay the game or end with a report of your winnings or losings. - - - diff --git a/29_Craps/craps.bas b/29_Craps/craps.bas index eb470b27e..3a387059f 100644 --- a/29_Craps/craps.bas +++ b/29_Craps/craps.bas @@ -15,7 +15,7 @@ 40 LET E=INT(7*RND(1)) 41 LET S=INT(7*RND(1)) 42 LET X=E+S -50 IF X=7 THEN 180 +50 IF X=7 THEN 180 55 IF X=11 THEN 180 60 IF X=1 THEN 40 62 IF X=2 THEN 195 diff --git a/29_Craps/csharp/.gitignore b/29_Craps/csharp/.gitignore index c1cb0dced..a518e3617 100644 --- a/29_Craps/csharp/.gitignore +++ b/29_Craps/csharp/.gitignore @@ -2,4 +2,3 @@ TestResults bin obj - diff --git a/29_Craps/csharp/Craps/Program.cs b/29_Craps/csharp/Craps/Program.cs index d0aa59614..9d800916b 100644 --- a/29_Craps/csharp/Craps/Program.cs +++ b/29_Craps/csharp/Craps/Program.cs @@ -14,7 +14,7 @@ static void Main(string[] args) ui.Intro(); - do + do { var bet = ui.PlaceBet(); var result = game.Play(out int diceRoll); diff --git a/29_Craps/csharp/Craps/UserInterface.cs b/29_Craps/csharp/Craps/UserInterface.cs index 149a3ecc5..f320db864 100644 --- a/29_Craps/csharp/Craps/UserInterface.cs +++ b/29_Craps/csharp/Craps/UserInterface.cs @@ -139,5 +139,3 @@ private int GetInt() } } } - - diff --git a/29_Craps/csharp/CrapsTester/CrapsTests.cs b/29_Craps/csharp/CrapsTester/CrapsTests.cs index 576c2b820..1d3ab60b9 100644 --- a/29_Craps/csharp/CrapsTester/CrapsTests.cs +++ b/29_Craps/csharp/CrapsTester/CrapsTests.cs @@ -80,7 +80,7 @@ public void DiceRollsAreRandom() } // We'll assume that a variation of 10% in rolls for the different numbers is random enough. - // Perfectly random rolling would produce 100000 rolls per side, +/- 5% of this gives the + // Perfectly random rolling would produce 100000 rolls per side, +/- 5% of this gives the // range 90000..110000. const int minRolls = 95000; const int maxRolls = 105000; diff --git a/29_Craps/java/src/Craps.java b/29_Craps/java/src/Craps.java index 483c16a98..3a99c4481 100644 --- a/29_Craps/java/src/Craps.java +++ b/29_Craps/java/src/Craps.java @@ -6,13 +6,13 @@ */ public class Craps { public static final Random random = new Random(); - + public static void main(String[] args) { System.out.println(""" CRAPS CREATIVE COMPUTING MORRISTOWN, NEW JERSEY - - + + 2,3,12 ARE LOSERS; 4,5,6,8,9,10 ARE POINTS; 7,11 ARE NATURAL WINNERS. """); double winnings = 0.0; diff --git a/29_Craps/javascript/craps.js b/29_Craps/javascript/craps.js index 108f60679..6a0ee90a5 100644 --- a/29_Craps/javascript/craps.js +++ b/29_Craps/javascript/craps.js @@ -12,10 +12,10 @@ function input() { var input_element; var input_str; - + return new Promise(function (resolve) { input_element = document.createElement("INPUT"); - + print("? "); input_element.setAttribute("type", "text"); input_element.setAttribute("length", "50"); @@ -112,7 +112,7 @@ async function main() } else { print("CONGRATULATIONS---YOU CAME OUT EVEN, NOT BAD FOR AN AMATEUR\n"); } - + } main(); diff --git a/29_Craps/python/craps.py b/29_Craps/python/craps.py index 38faeed32..1f788ba8e 100644 --- a/29_Craps/python/craps.py +++ b/29_Craps/python/craps.py @@ -57,7 +57,9 @@ def throw_dice(): winnings -= wager elif roll_2 == roll_1: print(f"{roll_1} - a winner.........congrats!!!!!!!!") - print(f"{roll_1} at 2 to 1 odds pays you...let me see... {2 * wager} dollars") + print( + f"{roll_1} at 2 to 1 odds pays you...let me see... {2 * wager} dollars" + ) winnings += 2 * wager else: print(f"{roll_2} - no point. I will roll again") @@ -69,7 +71,7 @@ def throw_dice(): print(f"You are now ahead ${winnings}") else: print("You are now even at 0") - play_again = (m == "5") + play_again = m == "5" if winnings < 0: print(f"Too bad, you are in the hole. Come again.") diff --git a/29_Craps/ruby/craps.rb b/29_Craps/ruby/craps.rb index dc53813bf..315f4ea07 100644 --- a/29_Craps/ruby/craps.rb +++ b/29_Craps/ruby/craps.rb @@ -81,7 +81,7 @@ def pointRoll point, wager def play displayHeading - + while true do wagerAmount = placeBet roll = rollDice @@ -122,4 +122,3 @@ def endPlay craps = CRAPSGAME.new craps.play - diff --git a/30_Cube/cube.bas b/30_Cube/cube.bas index 1e4462f66..b20198396 100644 --- a/30_Cube/cube.bas +++ b/30_Cube/cube.bas @@ -131,13 +131,13 @@ 1360 GOTO 1380 1370 IF R=O THEN 1400 1380 PRINT "NEXT MOVE: "; -1390 GOTO 930 +1390 GOTO 930 1400 PRINT"******BANG******" 1410 PRINT "YOU LOSE!" 1420 PRINT 1430 PRINT 1440 IF Z=0 THEN 1580 -1450 PRINT +1450 PRINT 1460 LET Z2=A1-Z1 1470 IF Z2>0 THEN 1500 1480 PRINT "YOU BUST." diff --git a/30_Cube/javascript/cube.js b/30_Cube/javascript/cube.js index edbaaedcd..d2b54ff4d 100644 --- a/30_Cube/javascript/cube.js +++ b/30_Cube/javascript/cube.js @@ -12,10 +12,10 @@ function input() { var input_element; var input_str; - + return new Promise(function (resolve) { input_element = document.createElement("INPUT"); - + print("? "); input_element.setAttribute("type", "text"); input_element.setAttribute("length", "50"); diff --git a/30_Cube/python/cube.py b/30_Cube/python/cube.py index 8bb540e09..654efad0b 100755 --- a/30_Cube/python/cube.py +++ b/30_Cube/python/cube.py @@ -24,7 +24,7 @@ def play_game(): mine = [] while True: mine = mine_position() - if not(mine in mines or mine == [1, 1, 1] or mine == [3, 3, 3]): + if not (mine in mines or mine == [1, 1, 1] or mine == [3, 3, 3]): break mines.append(mine) wager = -1 @@ -42,19 +42,26 @@ def play_game(): move = [-1, -1, -1] while move == [-1, -1, -1]: try: - coordinates = [int(item) - for item in input(prompt).split(",")] + coordinates = [int(item) for item in input(prompt).split(",")] if len(coordinates) == 3: move = coordinates else: raise ValueError except (ValueError, IndexError): print("Please enter valid coordinates.") - if (abs(move[0]-position[0]) + abs(move[1]-position[1]) + abs(move[2]-position[2])) > 1: + if ( + abs(move[0] - position[0]) + + abs(move[1] - position[1]) + + abs(move[2] - position[2]) + ) > 1: print("\nIllegal move. You lose") money = money - wager break - elif not move[0] in [1, 2, 3] or not move[1] in [1, 2, 3] or not move[2] in [1, 2, 3]: + elif ( + not move[0] in [1, 2, 3] + or not move[1] in [1, 2, 3] + or not move[2] in [1, 2, 3] + ): print("\nIllegal move. You lose") money = money - wager break @@ -106,8 +113,7 @@ def main(): keep_playing = True while keep_playing: play_game() - keep_playing = input( - "\nPlay again? (yes or no) ").lower().startswith("y") + keep_playing = input("\nPlay again? (yes or no) ").lower().startswith("y") if __name__ == "__main__": diff --git a/30_Cube/ruby/cube.rb b/30_Cube/ruby/cube.rb index a881986e9..3badc8acd 100644 --- a/30_Cube/ruby/cube.rb +++ b/30_Cube/ruby/cube.rb @@ -38,7 +38,7 @@ def greeting puts "When stating the amount of a wager, enter only the number" puts "of dollars (example: 250) You are automatically started with" puts "500 dollars in your account." - puts + puts puts "Good luck!" end end @@ -225,7 +225,7 @@ def gameLoop betAmount puts "" print "IT'S YOUR MOVE: " # allow only integers: strip anything else from input - moveToLocation = gets.strip.tr('^0-9', '') + moveToLocation = gets.strip.tr('^0-9', '') # test for illegal moves # can only change one variable per move @@ -258,4 +258,3 @@ def gameLoop betAmount greeting initializePot gameLoop startGame - diff --git a/31_Depth_Charge/java/DepthCharge.java b/31_Depth_Charge/java/DepthCharge.java index bf17acccc..72e943607 100644 --- a/31_Depth_Charge/java/DepthCharge.java +++ b/31_Depth_Charge/java/DepthCharge.java @@ -9,40 +9,40 @@ *

* Note: The idea was to create a version of the 1970's BASIC game in Java, without introducing * new features - no additional text, error checking, etc has been added. - * + * * Converted from BASIC to Java by Darren Cardenas. */ - -public class DepthCharge { - + +public class DepthCharge { + private final Scanner scan; // For user input - + public DepthCharge() { - + scan = new Scanner(System.in); - - } // End of constructor DepthCharge + + } // End of constructor DepthCharge public void play() { - + showIntro(); startGame(); - - } // End of method play - + + } // End of method play + private static void showIntro() { - + System.out.println(" ".repeat(29) + "DEPTH CHARGE"); System.out.println(" ".repeat(14) + "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY"); System.out.println("\n\n"); - } // End of method showIntro - + } // End of method showIntro + private void startGame() { int searchArea = 0; int shotNum = 0; - int shotTotal = 0; + int shotTotal = 0; int shotX = 0; int shotY = 0; int shotZ = 0; @@ -52,135 +52,135 @@ private void startGame() { int tries = 0; String[] userCoordinates; String userResponse = ""; - + System.out.print("DIMENSION OF SEARCH AREA? "); searchArea = Integer.parseInt(scan.nextLine()); System.out.println(""); - - shotTotal = (int) (Math.log10(searchArea) / Math.log10(2)) + 1; - + + shotTotal = (int) (Math.log10(searchArea) / Math.log10(2)) + 1; + System.out.println("YOU ARE THE CAPTAIN OF THE DESTROYER USS COMPUTER"); System.out.println("AN ENEMY SUB HAS BEEN CAUSING YOU TROUBLE. YOUR"); System.out.println("MISSION IS TO DESTROY IT. YOU HAVE " + shotTotal + " SHOTS."); System.out.println("SPECIFY DEPTH CHARGE EXPLOSION POINT WITH A"); System.out.println("TRIO OF NUMBERS -- THE FIRST TWO ARE THE"); System.out.println("SURFACE COORDINATES; THE THIRD IS THE DEPTH."); - - // Begin outer while loop - while (true) { - + + // Begin outer while loop + while (true) { + System.out.println(""); System.out.println("GOOD LUCK !"); System.out.println(""); - + targetX = (int) ((searchArea + 1) * Math.random()); targetY = (int) ((searchArea + 1) * Math.random()); targetZ = (int) ((searchArea + 1) * Math.random()); - + // Begin loop through all shots for (shotNum = 1; shotNum <= shotTotal; shotNum++) { - + // Get user input System.out.println(""); - System.out.print("TRIAL # " + shotNum + "? "); + System.out.print("TRIAL # " + shotNum + "? "); userResponse = scan.nextLine(); - + // Split on commas userCoordinates = userResponse.split(","); - + // Assign to integer variables shotX = Integer.parseInt(userCoordinates[0].trim()); shotY = Integer.parseInt(userCoordinates[1].trim()); - shotZ = Integer.parseInt(userCoordinates[2].trim()); - + shotZ = Integer.parseInt(userCoordinates[2].trim()); + // Win condition - if (Math.abs(shotX - targetX) + Math.abs(shotY - targetY) + if (Math.abs(shotX - targetX) + Math.abs(shotY - targetY) + Math.abs(shotZ - targetZ) == 0) { System.out.println("B O O M ! ! YOU FOUND IT IN" + shotNum + " TRIES!"); break; - + } - + this.getReport(targetX, targetY, targetZ, shotX, shotY, shotZ); - - System.out.println(""); - + + System.out.println(""); + } // End loop through all shots - + if (shotNum > shotTotal) { - + System.out.println(""); System.out.println("YOU HAVE BEEN TORPEDOED! ABANDON SHIP!"); System.out.println("THE SUBMARINE WAS AT " + targetX + "," + targetY + "," + targetZ); } - + System.out.println(""); System.out.println(""); - System.out.print("ANOTHER GAME (Y OR N)? "); - userResponse = scan.nextLine(); - + System.out.print("ANOTHER GAME (Y OR N)? "); + userResponse = scan.nextLine(); + if (!userResponse.toUpperCase().equals("Y")) { - System.out.print("OK. HOPE YOU ENJOYED YOURSELF."); + System.out.print("OK. HOPE YOU ENJOYED YOURSELF."); return; } - + } // End outer while loop - - } // End of method startGame - + + } // End of method startGame + public void getReport(int a, int b, int c, int x, int y, int z) { - + System.out.print("SONAR REPORTS SHOT WAS "); - + // Handle y coordinate if (y > b) { - - System.out.print("NORTH"); - + + System.out.print("NORTH"); + } else if (y < b) { - + System.out.print("SOUTH"); } - + // Handle x coordinate if (x > a) { - + System.out.print("EAST"); - + } else if (x < a) { - - System.out.print("WEST"); + + System.out.print("WEST"); } - + if ((y != b) || (x != a)) { - + System.out.print(" AND"); } - + // Handle depth if (z > c) { - + System.out.println(" TOO LOW."); - + } else if (z < c) { - + System.out.println(" TOO HIGH."); - + } else { - - System.out.println(" DEPTH OK."); + + System.out.println(" DEPTH OK."); } - + return; - + } // End of method getReport - + public static void main(String[] args) { - + DepthCharge game = new DepthCharge(); game.play(); - + } // End of method main - + } // End of class DepthCharge diff --git a/31_Depth_Charge/javascript/depthcharge.js b/31_Depth_Charge/javascript/depthcharge.js index 6b0a7813f..0c0d43f83 100644 --- a/31_Depth_Charge/javascript/depthcharge.js +++ b/31_Depth_Charge/javascript/depthcharge.js @@ -12,10 +12,10 @@ function input() { var input_element; var input_str; - + return new Promise(function (resolve) { input_element = document.createElement("INPUT"); - + print("? "); input_element.setAttribute("type", "text"); input_element.setAttribute("length", "50"); diff --git a/31_Depth_Charge/perl/README.md b/31_Depth_Charge/perl/README.md index 6c2756f80..71f275434 100644 --- a/31_Depth_Charge/perl/README.md +++ b/31_Depth_Charge/perl/README.md @@ -14,4 +14,3 @@ Perl makes life easy. * We use ternarys to generate the message if you miss the sub. * We use join to stitch the pieces of the string together. * If we have a ternary where we don't want to return anything we return an empty list rather than an empty string - if you return the latter you still get the padding spaces. - diff --git a/31_Depth_Charge/python/depth_charge.py b/31_Depth_Charge/python/depth_charge.py index f367962ee..1d68c83b1 100644 --- a/31_Depth_Charge/python/depth_charge.py +++ b/31_Depth_Charge/python/depth_charge.py @@ -36,7 +36,7 @@ def get_num_charges(): def ask_for_new_game(): answer = input("Another game (Y or N): ") - if answer.lower().strip()[0] == 'y': + if answer.lower().strip()[0] == "y": start_new_game() else: print("OK. Hope you enjoyed yourself") @@ -58,7 +58,7 @@ def show_shot_result(shot, location): if shot[2] > location[2]: result += "too low." - elif shot[2] < location [2]: + elif shot[2] < location[2]: result += "too high." else: result += "depth OK." @@ -76,7 +76,7 @@ def get_shot_input(): print(f"Example: 3 2 1") continue try: - x, y, z = [int(num) for num in [x, y, z]] + x, y, z = (int(num) for num in [x, y, z]) return x, y, z except ValueError: print("Please enter whole numbers only") @@ -92,7 +92,7 @@ def play_game(search_area, num_charges): print("\nGood luck!\n") # Generate position for submarine - a, b, c = [random.randint(0, search_area) for _ in range(3)] + a, b, c = (random.randint(0, search_area) for _ in range(3)) # Get inputs until win or lose for i in range(num_charges): @@ -116,5 +116,5 @@ def start_new_game(): play_game(search_area, num_charges) -if __name__ == '__main__': +if __name__ == "__main__": start_new_game() diff --git a/32_Diamond/java/Diamond.java b/32_Diamond/java/Diamond.java index da56efe46..2989ce2d6 100644 --- a/32_Diamond/java/Diamond.java +++ b/32_Diamond/java/Diamond.java @@ -8,126 +8,126 @@ *

* Note: The idea was to create a version of the 1970's BASIC game in Java, without introducing * new features - no additional text, error checking, etc has been added. - * + * * Converted from BASIC to Java by Darren Cardenas. */ - -public class Diamond { - + +public class Diamond { + private static final int LINE_WIDTH = 60; - + private static final String PREFIX = "CC"; - + private static final char SYMBOL = '!'; - - private final Scanner scan; // For user input - - + + private final Scanner scan; // For user input + + public Diamond() { - - scan = new Scanner(System.in); - - } // End of constructor Diamond - - + + scan = new Scanner(System.in); + + } // End of constructor Diamond + + public void play() { showIntro(); startGame(); - } // End of method play - - - private void showIntro() { - + } // End of method play + + + private void showIntro() { + System.out.println(" ".repeat(32) + "DIAMOND"); System.out.println(" ".repeat(14) + "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY"); System.out.println("\n\n"); - - } // End of method showIntro + + } // End of method showIntro - private void startGame() { - + private void startGame() { + int body = 0; int column = 0; int end = 0; int fill = 0; - int increment = 2; - int numPerSide = 0; + int increment = 2; + int numPerSide = 0; int prefixIndex = 0; - int row = 0; - int start = 1; - int userNum = 0; - + int row = 0; + int start = 1; + int userNum = 0; + String lineContent = ""; - + // Get user input System.out.println("FOR A PRETTY DIAMOND PATTERN,"); System.out.print("TYPE IN AN ODD NUMBER BETWEEN 5 AND 21? "); userNum = scan.nextInt(); System.out.println(""); - + // Calcuate number of diamonds to be drawn on each side of screen - numPerSide = (int) (LINE_WIDTH / userNum); + numPerSide = (int) (LINE_WIDTH / userNum); + + end = userNum; - end = userNum; - // Begin loop through each row of diamonds for (row = 1; row <= numPerSide; row++) { - + // Begin loop through top and bottom halves of each diamond for (body = start; increment < 0 ? body >= end : body <= end; body += increment) { lineContent = ""; - + // Add whitespace while (lineContent.length() < ((userNum - body) / 2)) { lineContent += " "; } - + // Begin loop through each column of diamonds for (column = 1; column <= numPerSide; column++) { - + prefixIndex = 1; - + // Begin loop that fills each diamond with characters for (fill = 1; fill <= body; fill++) { - + // Right side of diamond if (prefixIndex > PREFIX.length()) { - - lineContent += SYMBOL; - + + lineContent += SYMBOL; + } // Left side of diamond else { - + lineContent += PREFIX.charAt(prefixIndex - 1); prefixIndex++; - - } - + + } + } // End loop that fills each diamond with characters - + // Column finished if (column == numPerSide) { - + break; - + } // Column not finishd else { - + // Add whitespace while (lineContent.length() < (userNum * column + (userNum - body) / 2)) { lineContent += " "; } - - } - + + } + } // End loop through each column of diamonds - + System.out.println(lineContent); } // End loop through top and bottom half of each diamond @@ -136,28 +136,28 @@ private void startGame() { start = 1; end = userNum; - increment = 2; - + increment = 2; + } else { - + start = userNum - 2; end = 1; - increment = -2; + increment = -2; row--; - } + } } // End loop through each row of diamonds - + } // End of method startGame - - + + public static void main(String[] args) { - + Diamond diamond = new Diamond(); diamond.play(); - + } // End of method main } // End of class Diamond diff --git a/32_Diamond/javascript/diamond.js b/32_Diamond/javascript/diamond.js index bb6f0fe91..e454a2d55 100644 --- a/32_Diamond/javascript/diamond.js +++ b/32_Diamond/javascript/diamond.js @@ -12,10 +12,10 @@ function input() { var input_element; var input_str; - + return new Promise(function (resolve) { input_element = document.createElement("INPUT"); - + print("? "); input_element.setAttribute("type", "text"); input_element.setAttribute("length", "50"); diff --git a/32_Diamond/perl/diamond.pl b/32_Diamond/perl/diamond.pl index 62311c142..fcd4dc402 100755 --- a/32_Diamond/perl/diamond.pl +++ b/32_Diamond/perl/diamond.pl @@ -33,5 +33,3 @@ } exit; - - diff --git a/32_Diamond/ruby/diamond.rb b/32_Diamond/ruby/diamond.rb index 251cee25c..a28f4e55d 100644 --- a/32_Diamond/ruby/diamond.rb +++ b/32_Diamond/ruby/diamond.rb @@ -42,4 +42,4 @@ def main trap "SIGINT" do puts; exit 130 end -main \ No newline at end of file +main diff --git a/33_Dice/csharp/Game.cs b/33_Dice/csharp/Game.cs index 3938e4c41..0a21da35e 100644 --- a/33_Dice/csharp/Game.cs +++ b/33_Dice/csharp/Game.cs @@ -109,4 +109,4 @@ private bool TryAgain() return (pressedKey == 'Y'); } } -} \ No newline at end of file +} diff --git a/33_Dice/csharp/README.md b/33_Dice/csharp/README.md index 23ccd0fe0..3dba781c9 100644 --- a/33_Dice/csharp/README.md +++ b/33_Dice/csharp/README.md @@ -1,4 +1,3 @@ Original source downloaded [from Vintage Basic](http://www.vintage-basic.net/games.html) Conversion to [Microsoft C#](https://docs.microsoft.com/en-us/dotnet/csharp/) by James Curran (http://www.noveltheory.com) - diff --git a/33_Dice/csharp/RollGenerator.cs b/33_Dice/csharp/RollGenerator.cs index 08f2df6b8..e707d45f9 100644 --- a/33_Dice/csharp/RollGenerator.cs +++ b/33_Dice/csharp/RollGenerator.cs @@ -17,4 +17,4 @@ public class RollGenerator } } } -} \ No newline at end of file +} diff --git a/33_Dice/javascript/dice.js b/33_Dice/javascript/dice.js index e33e538a3..d570ea8a3 100644 --- a/33_Dice/javascript/dice.js +++ b/33_Dice/javascript/dice.js @@ -12,10 +12,10 @@ function input() { var input_element; var input_str; - + return new Promise(function (resolve) { input_element = document.createElement("INPUT"); - + print("? "); input_element.setAttribute("type", "text"); input_element.setAttribute("length", "50"); diff --git a/33_Dice/perl/dice.pl b/33_Dice/perl/dice.pl index cb051b0a9..2683b7a3a 100755 --- a/33_Dice/perl/dice.pl +++ b/33_Dice/perl/dice.pl @@ -38,5 +38,3 @@ print "? "; chomp($Z = ); } until (uc($Z) ne "YES"); exit; - - diff --git a/33_Dice/python/dice.py b/33_Dice/python/dice.py index 94cdab6bd..9f46a8d89 100644 --- a/33_Dice/python/dice.py +++ b/33_Dice/python/dice.py @@ -28,7 +28,6 @@ import random - # 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). @@ -66,14 +65,12 @@ # Keep playing? print("") response = input("Try again? ") - if len(response) > 0 and response.upper()[0] == 'Y': + if len(response) > 0 and response.upper()[0] == "Y": # Clear out the frequency list - freq = [0]*13 + freq = [0] * 13 else: # Exit the game loop still_playing = False - - ######################################################## @@ -114,10 +111,3 @@ # rolled each time? # ######################################################## - - - - - - - diff --git a/33_Dice/ruby/dice.rb b/33_Dice/ruby/dice.rb index 583809283..ea1911e79 100644 --- a/33_Dice/ruby/dice.rb +++ b/33_Dice/ruby/dice.rb @@ -48,4 +48,4 @@ def main trap "SIGINT" do puts; exit 130 end -main \ No newline at end of file +main diff --git a/34_Digits/java/Digits.java b/34_Digits/java/Digits.java index 36ee58aef..71c39d95a 100644 --- a/34_Digits/java/Digits.java +++ b/34_Digits/java/Digits.java @@ -183,4 +183,3 @@ private static void printIntro() { } } - diff --git a/34_Digits/javascript/digits.js b/34_Digits/javascript/digits.js index 8f2be6ded..31fd1e2c7 100644 --- a/34_Digits/javascript/digits.js +++ b/34_Digits/javascript/digits.js @@ -12,10 +12,10 @@ function input() { var input_element; var input_str; - + return new Promise(function (resolve) { input_element = document.createElement("INPUT"); - + print("? "); input_element.setAttribute("type", "text"); input_element.setAttribute("length", "50"); diff --git a/34_Digits/python/Digits.py b/34_Digits/python/Digits.py index 48647c129..2830940d5 100644 --- a/34_Digits/python/Digits.py +++ b/34_Digits/python/Digits.py @@ -1,5 +1,6 @@ import random + def printIntro(): print(" DIGITS") print(" CREATIVE COMPUTING MORRISTOWN, NEW JERSEY") @@ -45,6 +46,7 @@ def read10Numbers(): return numbers + def readContinueChoice(): print("\nDO YOU WANT TO TRY AGAIN (1 FOR YES, 0 FOR NO) ? ") try: @@ -53,7 +55,8 @@ def readContinueChoice(): except (ValueError, TypeError) as m: return False -if __name__ == '__main__': + +if __name__ == "__main__": printIntro() if readInstructionChoice(): printInstructions() @@ -90,7 +93,10 @@ def readContinueChoice(): validNumbers = False break - print("\n%-14s%-14s%-14s%-14s" % ("MY GUESS", "YOUR NO.", "RESULT", "NO. RIGHT")) + print( + "\n%-14s%-14s%-14s%-14s" + % ("MY GUESS", "YOUR NO.", "RESULT", "NO. RIGHT") + ) for number in numbers: s = 0 @@ -118,7 +124,9 @@ def readContinueChoice(): k[int(z2)][number] = k[int(z2)][number] + 1 z = z - (z / 9) * 9 z = 3 * z + number - print("\n%-14d%-14d%-14s%-14d" % (myGuess, number, result, runningCorrect)) + print( + "\n%-14d%-14d%-14s%-14d" % (myGuess, number, result, runningCorrect) + ) z1 = z - (z / 9) * 9 z2 = number @@ -128,7 +136,7 @@ def readContinueChoice(): if runningCorrect > 10: print() print("I GUESSED MORE THAN 1/3 OF YOUR NUMBERS.") - print("I WIN." + u"\u0007") + print("I WIN." + "\u0007") elif runningCorrect < 10: print("I GUESSED LESS THAN 1/3 OF YOUR NUMBERS.") print("YOU BEAT ME. CONGRATULATIONS *****") @@ -138,4 +146,4 @@ def readContinueChoice(): continueGame = readContinueChoice() - print("\nTHANKS FOR THE GAME.") \ No newline at end of file + print("\nTHANKS FOR THE GAME.") diff --git a/35_Even_Wins/evenwins.bas b/35_Even_Wins/evenwins.bas index b1d0365da..4e663c681 100644 --- a/35_Even_Wins/evenwins.bas +++ b/35_Even_Wins/evenwins.bas @@ -8,7 +8,7 @@ 40 PRINT "TO PLAY THE GAME, THE PLAYERS NEED 27 MARBLES OR" 50 PRINT "OTHER OBJECTS ON A TABLE." 60 PRINT -70 PRINT +70 PRINT 80 PRINT " THE 2 PLAYERS ALTERNATE TURNS, WITH EACH PLAYER" 90 PRINT "REMOVING FROM 1 TO 4 MARBLES ON EACH MOVE. THE GAME" 100 PRINT "ENDS WHEN THERE ARE NO MARBLES LEFT, AND THE WINNER" diff --git a/35_Even_Wins/javascript/evenwins.js b/35_Even_Wins/javascript/evenwins.js index 90f273f1e..3ccaa9ad6 100644 --- a/35_Even_Wins/javascript/evenwins.js +++ b/35_Even_Wins/javascript/evenwins.js @@ -12,10 +12,10 @@ function input() { var input_element; var input_str; - + return new Promise(function (resolve) { input_element = document.createElement("INPUT"); - + print("? "); input_element.setAttribute("type", "text"); input_element.setAttribute("length", "50"); @@ -122,7 +122,7 @@ async function main() break; } } - + y1 += y; t -= y; if (t == 0) diff --git a/35_Even_Wins/javascript/gameofevenwins.js b/35_Even_Wins/javascript/gameofevenwins.js index 945bc0bad..b807a260e 100644 --- a/35_Even_Wins/javascript/gameofevenwins.js +++ b/35_Even_Wins/javascript/gameofevenwins.js @@ -12,10 +12,10 @@ function input() { var input_element; var input_str; - + return new Promise(function (resolve) { input_element = document.createElement("INPUT"); - + print("? "); input_element.setAttribute("type", "text"); input_element.setAttribute("length", "50"); diff --git a/35_Even_Wins/perl/evenwins.pl b/35_Even_Wins/perl/evenwins.pl index c2fdc2d89..0eb37bdb6 100644 --- a/35_Even_Wins/perl/evenwins.pl +++ b/35_Even_Wins/perl/evenwins.pl @@ -8,7 +8,7 @@ sub main { &print_intro; &game_play; -} +} sub game_play { my $marbles = 27; @@ -26,7 +26,7 @@ sub game_play { $computer_total = $computer_total + $computer_choice; print "MY TOTAL IS $computer_total\n"; - print "TOTAL= $marbles\n"; + print "TOTAL= $marbles\n"; if ($marbles == 0) {&determine_winner($computer_total,$player_total)}; @@ -35,7 +35,7 @@ sub game_play { $player_total = $player_total + $player_choice; print "YOUR TOTAL IS $player_total\n"; $turn++; - print "TOTAL= $marbles\n"; + print "TOTAL= $marbles\n"; if ($marbles == 0) {&determine_winner($computer_total,$player_total)}; } } @@ -48,8 +48,8 @@ sub game_play { $turn++; print "YOUR TOTAL IS $player_total\n"; - print "TOTAL= $marbles\n"; - + print "TOTAL= $marbles\n"; + if ($marbles == 0) {&determine_winner($computer_total,$player_total)}; my $computer_choice = &computer_select($marbles,$turn,$player_total); @@ -57,7 +57,7 @@ sub game_play { $computer_total = $computer_total + $computer_choice; print "MY TOTAL IS $computer_total\n"; - print "TOTAL= $marbles\n"; + print "TOTAL= $marbles\n"; if ($marbles == 0) {&determine_winner($computer_total,$player_total)}; @@ -123,7 +123,7 @@ sub computer_select { else { until ($validity eq "valid") { my $R=$marbles-6*int(($marbles/6)); - + if (int($player_total/2) == $player_total/2) { if ($R < 1.5 || $R > 5.3) { $num = 1; @@ -132,7 +132,7 @@ sub computer_select { $num = $R - 1; } } - + elsif ($marbles < 4.2) { $num = $marbles; } diff --git a/35_Even_Wins/python/evenwins.py b/35_Even_Wins/python/evenwins.py index 3fb9d4afa..99f9b338f 100644 --- a/35_Even_Wins/python/evenwins.py +++ b/35_Even_Wins/python/evenwins.py @@ -1,4 +1,4 @@ -# evenwins.py +# evenwins.py # # This version of evenwins.bas based on game decscription and does *not* @@ -23,43 +23,47 @@ # global variables marbles_in_middle = -1 -human_marbles = -1 -computer_marbles = -1 -whose_turn = '' +human_marbles = -1 +computer_marbles = -1 +whose_turn = "" # Only called during development for serious errors that are due to mistakes # in the program. Should never be called during a regular game. def serious_error(msg): - print('serious_error: ' + msg) + print("serious_error: " + msg) exit(1) + def welcome_screen(): - print('Welcome to Even Wins!') - print('Based on evenwins.bas from Creative Computing') + print("Welcome to Even Wins!") + print("Based on evenwins.bas from Creative Computing") print() - print('Even Wins is a two-person game. You start with') - print('27 marbles in the middle of the table.') + print("Even Wins is a two-person game. You start with") + print("27 marbles in the middle of the table.") print() - print('Players alternate taking marbles from the middle.') - print('A player can take 1 to 4 marbles on their turn, and') - print('turns cannot be skipped. The game ends when there are') - print('no marbles left, and the winner is the one with an even') - print('number of marbles.') + print("Players alternate taking marbles from the middle.") + print("A player can take 1 to 4 marbles on their turn, and") + print("turns cannot be skipped. The game ends when there are") + print("no marbles left, and the winner is the one with an even") + print("number of marbles.") print() + def marbles_str(n): - if n == 1: return '1 marble' - return f'{n} marbles' + if n == 1: + return "1 marble" + return f"{n} marbles" + def choose_first_player(): global whose_turn while True: - ans = input('Do you want to play first? (y/n) --> ') - if ans == 'y': - whose_turn = 'human' + ans = input("Do you want to play first? (y/n) --> ") + if ans == "y": + whose_turn = "human" return - elif ans == 'n': - whose_turn = 'computer' + elif ans == "n": + whose_turn = "computer" return else: print() @@ -67,14 +71,16 @@ def choose_first_player(): print('or "n" if you want to play second.') print() + def next_player(): global whose_turn - if whose_turn == 'human': - whose_turn = 'computer' - elif whose_turn == 'computer': - whose_turn = 'human' + if whose_turn == "human": + whose_turn = "computer" + elif whose_turn == "computer": + whose_turn = "human" else: - serious_error(f'play_game: unknown player {whose_turn}') + serious_error(f"play_game: unknown player {whose_turn}") + # Converts a string s to an int, if possible. def to_int(s): @@ -84,16 +90,18 @@ def to_int(s): except: return False, 0 + def print_board(): global marbles_in_middle global human_marbles global computer_marbles print() - print(f' marbles in the middle: {marbles_in_middle} ' + marbles_in_middle*'*') - print(f' # marbles you have: {human_marbles}') - print(f'# marbles computer has: {computer_marbles}') + print(f" marbles in the middle: {marbles_in_middle} " + marbles_in_middle * "*") + print(f" # marbles you have: {human_marbles}") + print(f"# marbles computer has: {computer_marbles}") print() + def human_turn(): global marbles_in_middle global human_marbles @@ -102,72 +110,75 @@ def human_turn(): max_choice = min(4, marbles_in_middle) print("It's your turn!") while True: - s = input(f'Marbles to take? (1 - {max_choice}) --> ') + s = input(f"Marbles to take? (1 - {max_choice}) --> ") ok, n = to_int(s) if not ok: print() - print(f' Please enter a whole number from 1 to {max_choice}') + print(f" Please enter a whole number from 1 to {max_choice}") print() continue if n < 1: print() - print(' You must take at least 1 marble!') + print(" You must take at least 1 marble!") print() continue if n > max_choice: print() - print(f' You can take at most {marbles_str(max_choice)}') + print(f" You can take at most {marbles_str(max_choice)}") print() continue print() - print(f'Okay, taking {marbles_str(n)} ...') + print(f"Okay, taking {marbles_str(n)} ...") marbles_in_middle -= n human_marbles += n return + def game_over(): global marbles_in_middle global human_marbles global computer_marbles print() - print('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!') - print('!! All the marbles are taken: Game Over!') - print('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!') + print("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!") + print("!! All the marbles are taken: Game Over!") + print("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!") print() print_board() if human_marbles % 2 == 0: - print('You are the winner! Congratulations!') + print("You are the winner! Congratulations!") else: - print('The computer wins: all hail mighty silicon!') - print('') + print("The computer wins: all hail mighty silicon!") + print("") + def computer_turn(): - global marbles_in_middle - global computer_marbles - global human_marbles - - marbles_to_take=0 - - print("It's the computer's turn ...") - r = marbles_in_middle - 6 * int((marbles_in_middle/6)) #line 500 - - if int(human_marbles/2) == human_marbles/2: #line 510 - if r < 1.5 or r > 5.3: #lines 710 and 720 - marbles_to_take = 1 - else: - marbles_to_take = r - 1 - - elif marbles_in_middle < 4.2: #line 580 - marbles_to_take = marbles_in_middle - elif r > 3.4: #line 530 - if r < 4.7 or r > 3.5: - marbles_to_take = 4 - else: - marbles_to_take = r + 1 - - print(f'Computer takes {marbles_str(marbles_to_take)} ...') - marbles_in_middle -= marbles_to_take - computer_marbles += marbles_to_take + global marbles_in_middle + global computer_marbles + global human_marbles + + marbles_to_take = 0 + + print("It's the computer's turn ...") + r = marbles_in_middle - 6 * int(marbles_in_middle / 6) # line 500 + + if int(human_marbles / 2) == human_marbles / 2: # line 510 + if r < 1.5 or r > 5.3: # lines 710 and 720 + marbles_to_take = 1 + else: + marbles_to_take = r - 1 + + elif marbles_in_middle < 4.2: # line 580 + marbles_to_take = marbles_in_middle + elif r > 3.4: # line 530 + if r < 4.7 or r > 3.5: + marbles_to_take = 4 + else: + marbles_to_take = r + 1 + + print(f"Computer takes {marbles_str(marbles_to_take)} ...") + marbles_in_middle -= marbles_to_take + computer_marbles += marbles_to_take + def play_game(): global marbles_in_middle @@ -184,16 +195,17 @@ def play_game(): if marbles_in_middle == 0: game_over() return - elif whose_turn == 'human': + elif whose_turn == "human": human_turn() print_board() next_player() - elif whose_turn == 'computer': + elif whose_turn == "computer": computer_turn() print_board() next_player() else: - serious_error(f'play_game: unknown player {whose_turn}') + serious_error(f"play_game: unknown player {whose_turn}") + def main(): global whose_turn @@ -206,16 +218,17 @@ def main(): # ask if the user if they want to play again print() - again = input('Would you like to play again? (y/n) --> ') - if again == 'y': + again = input("Would you like to play again? (y/n) --> ") + if again == "y": print() print("Ok, let's play again ...") print() else: print() - print('Ok, thanks for playing ... goodbye!') + print("Ok, thanks for playing ... goodbye!") print() return -if __name__ == '__main__': + +if __name__ == "__main__": main() diff --git a/36_Flip_Flop/csharp/FlipFlop.cs b/36_Flip_Flop/csharp/FlipFlop.cs index 53c613e82..a6cc5bb12 100644 --- a/36_Flip_Flop/csharp/FlipFlop.cs +++ b/36_Flip_Flop/csharp/FlipFlop.cs @@ -59,7 +59,7 @@ startNewGame = true; } - + if (moveIndex == 0) { // To reset the line to all X, same game @@ -83,8 +83,8 @@ do { - moveIndex = equalToLastMove - ? GetMoveIndexWhenEqualeLastMove(moveIndex, gameEntropyRate) + moveIndex = equalToLastMove + ? GetMoveIndexWhenEqualeLastMove(moveIndex, gameEntropyRate) : GetMoveIndex(moveIndex, gameEntropyRate); board[moveIndex] = board[moveIndex] == "O" ? "X" : "O"; @@ -194,4 +194,4 @@ void PrintGameInfo() Print("OTHERS, TWO WILL CHANGE. TO RESET LINE TO ALL X'S, TYPE 0"); Print("(ZERO) AND TO START OVER IN THE MIDDLE OF A GAME, TYPE "); Print("11 (ELEVEN)."); -} \ No newline at end of file +} diff --git a/36_Flip_Flop/java/FlipFlop.java b/36_Flip_Flop/java/FlipFlop.java index afca236f8..fe8309d5d 100644 --- a/36_Flip_Flop/java/FlipFlop.java +++ b/36_Flip_Flop/java/FlipFlop.java @@ -9,55 +9,55 @@ *

* Note: The idea was to create a version of the 1970's BASIC game in Java, without introducing * new features - no additional text, error checking, etc has been added. - * + * * Converted from BASIC to Java by Darren Cardenas. */ - -public class FlipFlop { - - private final Scanner scan; // For user input - + +public class FlipFlop { + + private final Scanner scan; // For user input + private enum Step { - RANDOMIZE, INIT_BOARD, GET_NUMBER, ILLEGAL_ENTRY, FLIP_POSITION, SET_X_FIRST, SET_X_SECOND, + RANDOMIZE, INIT_BOARD, GET_NUMBER, ILLEGAL_ENTRY, FLIP_POSITION, SET_X_FIRST, SET_X_SECOND, GENERATE_R_FIRST, GENERATE_R_SECOND, PRINT_BOARD, QUERY_RETRY - } - + } + public FlipFlop() { - + scan = new Scanner(System.in); - - } // End of constructor FlipFlop + + } // End of constructor FlipFlop public void play() { - + showIntro(); startGame(); - - } // End of method play - + + } // End of method play + private static void showIntro() { - + System.out.println(" ".repeat(31) + "FLIPFLOP"); System.out.println(" ".repeat(14) + "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY"); System.out.println(""); - } // End of method showIntro - + } // End of method showIntro + private void startGame() { double mathVal = 0; - double randVal = 0; + double randVal = 0; double tmpVal = 0; - + int index = 0; int match = 0; int numFlip = 0; - int numGuesses = 0; - + int numGuesses = 0; + Step nextStep = Step.RANDOMIZE; - + String userResponse = ""; - + String[] board = new String[21]; System.out.println("THE OBJECT OF THIS PUZZLE IS TO CHANGE THIS:"); @@ -73,59 +73,59 @@ private void startGame() { System.out.println("OTHERS, TWO WILL CHANGE. TO RESET LINE TO ALL X'S, TYPE 0"); System.out.println("(ZERO) AND TO START OVER IN THE MIDDLE OF A GAME, TYPE "); System.out.println("11 (ELEVEN)."); - System.out.println(""); + System.out.println(""); // Begin outer while loop while (true) { - + // Begin switch switch (nextStep) { - - case RANDOMIZE: - + + case RANDOMIZE: + randVal = Math.random(); System.out.println("HERE IS THE STARTING LINE OF X'S."); System.out.println(""); - - numGuesses = 0; - nextStep = Step.INIT_BOARD; + + numGuesses = 0; + nextStep = Step.INIT_BOARD; break; - + case INIT_BOARD: - + System.out.println("1 2 3 4 5 6 7 8 9 10"); System.out.println("X X X X X X X X X X"); System.out.println(""); - + // Avoid out of bounds error by starting at zero for (index = 0; index <= 10; index++) { - board[index] = "X"; - } + board[index] = "X"; + } - nextStep = Step.GET_NUMBER; + nextStep = Step.GET_NUMBER; break; - + case GET_NUMBER: - + System.out.print("INPUT THE NUMBER? "); - userResponse = scan.nextLine(); - + userResponse = scan.nextLine(); + try { - numFlip = Integer.parseInt(userResponse); - } - catch (NumberFormatException ex) { + numFlip = Integer.parseInt(userResponse); + } + catch (NumberFormatException ex) { nextStep = Step.ILLEGAL_ENTRY; break; - } - + } + // Command to start a new game if (numFlip == 11) { nextStep = Step.RANDOMIZE; - break; - } - - if (numFlip > 11) { + break; + } + + if (numFlip > 11) { nextStep = Step.ILLEGAL_ENTRY; break; } @@ -135,153 +135,153 @@ private void startGame() { nextStep = Step.INIT_BOARD; break; } - + if (match == numFlip) { nextStep = Step.FLIP_POSITION; break; } - + match = numFlip; - - if (board[numFlip].equals("O")) { + + if (board[numFlip].equals("O")) { nextStep = Step.SET_X_FIRST; break; } - + board[numFlip] = "O"; nextStep = Step.GENERATE_R_FIRST; - break; - + break; + case ILLEGAL_ENTRY: System.out.println("ILLEGAL ENTRY--TRY AGAIN."); nextStep = Step.GET_NUMBER; break; - + case GENERATE_R_FIRST: - - mathVal = Math.tan(randVal + numFlip / randVal - numFlip) - Math.sin(randVal / numFlip) + 336 + + mathVal = Math.tan(randVal + numFlip / randVal - numFlip) - Math.sin(randVal / numFlip) + 336 * Math.sin(8 * numFlip); - - tmpVal = mathVal - (int)Math.floor(mathVal); - - numFlip = (int)(10 * tmpVal); - + + tmpVal = mathVal - (int)Math.floor(mathVal); + + numFlip = (int)(10 * tmpVal); + if (board[numFlip].equals("O")) { nextStep = Step.SET_X_FIRST; - break; + break; } - + board[numFlip] = "O"; - nextStep = Step.PRINT_BOARD; - break; - - case SET_X_FIRST: + nextStep = Step.PRINT_BOARD; + break; + + case SET_X_FIRST: board[numFlip] = "X"; - + if (match == numFlip) { - nextStep = Step.GENERATE_R_FIRST; + nextStep = Step.GENERATE_R_FIRST; } else { - nextStep = Step.PRINT_BOARD; + nextStep = Step.PRINT_BOARD; } - break; - + break; + case FLIP_POSITION: - - if (board[numFlip].equals("O")) { + + if (board[numFlip].equals("O")) { nextStep = Step.SET_X_SECOND; break; - } - + } + board[numFlip] = "O"; nextStep = Step.GENERATE_R_SECOND; break; case GENERATE_R_SECOND: - - mathVal = 0.592 * (1 / Math.tan(randVal / numFlip + randVal)) / Math.sin(numFlip * 2 + randVal) + + mathVal = 0.592 * (1 / Math.tan(randVal / numFlip + randVal)) / Math.sin(numFlip * 2 + randVal) - Math.cos(numFlip); - + tmpVal = mathVal - (int)mathVal; numFlip = (int)(10 * tmpVal); - + if (board[numFlip].equals("O")) { nextStep = Step.SET_X_SECOND; break; } - + board[numFlip] = "O"; - nextStep = Step.PRINT_BOARD; + nextStep = Step.PRINT_BOARD; break; - + case SET_X_SECOND: - + board[numFlip] = "X"; if (match == numFlip) { nextStep = Step.GENERATE_R_SECOND; - break; + break; } - - nextStep = Step.PRINT_BOARD; + + nextStep = Step.PRINT_BOARD; break; - + case PRINT_BOARD: System.out.println("1 2 3 4 5 6 7 8 9 10"); - + for (index = 1; index <= 10; index++) { - System.out.print(board[index] + " "); + System.out.print(board[index] + " "); } - + numGuesses++; - + System.out.println(""); - + for (index = 1; index <= 10; index++) { if (!board[index].equals("O")) { - nextStep = Step.GET_NUMBER; + nextStep = Step.GET_NUMBER; break; } - } - + } + if (nextStep == Step.GET_NUMBER) { - break; + break; } - - if (numGuesses > 12) { - System.out.println("TRY HARDER NEXT TIME. IT TOOK YOU " + numGuesses + " GUESSES."); - } else { - System.out.println("VERY GOOD. YOU GUESSED IT IN ONLY " + numGuesses + " GUESSES."); + + if (numGuesses > 12) { + System.out.println("TRY HARDER NEXT TIME. IT TOOK YOU " + numGuesses + " GUESSES."); + } else { + System.out.println("VERY GOOD. YOU GUESSED IT IN ONLY " + numGuesses + " GUESSES."); } - nextStep = Step.QUERY_RETRY; - break; - - case QUERY_RETRY: - - System.out.print("DO YOU WANT TO TRY ANOTHER PUZZLE? "); + nextStep = Step.QUERY_RETRY; + break; + + case QUERY_RETRY: + + System.out.print("DO YOU WANT TO TRY ANOTHER PUZZLE? "); userResponse = scan.nextLine(); - - if (userResponse.toUpperCase().charAt(0) == 'N') { + + if (userResponse.toUpperCase().charAt(0) == 'N') { return; - } + } System.out.println(""); - nextStep = Step.RANDOMIZE; + nextStep = Step.RANDOMIZE; break; - + default: System.out.println("INVALID STEP"); nextStep = Step.QUERY_RETRY; - break; + break; } // End of switch - - } // End outer while loop - - } // End of method startGame + + } // End outer while loop + + } // End of method startGame public static void main(String[] args) { - + FlipFlop game = new FlipFlop(); game.play(); - + } // End of method main - + } // End of class FlipFlop diff --git a/36_Flip_Flop/javascript/flipflop.js b/36_Flip_Flop/javascript/flipflop.js index fad83d64d..c74c61cae 100644 --- a/36_Flip_Flop/javascript/flipflop.js +++ b/36_Flip_Flop/javascript/flipflop.js @@ -12,10 +12,10 @@ function input() { var input_element; var input_str; - + return new Promise(function (resolve) { input_element = document.createElement("INPUT"); - + print("? "); input_element.setAttribute("type", "text"); input_element.setAttribute("length", "50"); diff --git a/36_Flip_Flop/python/flipflop.py b/36_Flip_Flop/python/flipflop.py index 9b6e2323f..9ca5e4c14 100644 --- a/36_Flip_Flop/python/flipflop.py +++ b/36_Flip_Flop/python/flipflop.py @@ -21,8 +21,8 @@ # The original author of this game was # Michael Kass of New Hyde Park, New # York. -import random import math +import random from typing import Callable, List, Tuple flip_dict = {"X": "O", "O": "X"} diff --git a/36_Flip_Flop/ruby/flipflop.rb b/36_Flip_Flop/ruby/flipflop.rb index 3a65a4c29..74ceadeec 100644 --- a/36_Flip_Flop/ruby/flipflop.rb +++ b/36_Flip_Flop/ruby/flipflop.rb @@ -49,7 +49,7 @@ def print_starting_message 1 2 3 4 5 6 7 8 9 10 X X X X X X X X X X - + EOS end @@ -75,7 +75,7 @@ def shuffle_board(game, index, shuffle_function) end #Shuffle logic copied from original BASIC code -def shuffle_function1(game, index) +def shuffle_function1(game, index) r = Math.tan(game.seed + index / game.seed - index) - Math.sin(game.seed / index) + 336 * Math.sin(8 * index) n = r - r.floor (10 * n).floor @@ -132,9 +132,9 @@ def play_game game.guesses += 1 puts '1 2 3 4 5 6 7 8 9 10' puts game.state.join(' ') - + if game.state.all? { |x| x == 'O' } - if game.guesses > 12 + if game.guesses > 12 puts "TRY HARDER NEXT TIME. IT TOOK YOU #{game.guesses} GUESSES." else puts "VERY GOOD. YOU GUESSED IT IN ONLY #{game.guesses} GUESSES." diff --git a/37_Football/football.bas b/37_Football/football.bas index 07e416a32..9ee2192f3 100644 --- a/37_Football/football.bas +++ b/37_Football/football.bas @@ -58,7 +58,7 @@ 790 P=P-Y(T)*K 794 IF W(T)*P190 THEN 500 -348 NEXT J -350 GOTO 1100 +344 IF F(0)>190 THEN 500 +348 NEXT J +350 GOTO 1100 500 PRINT -501 PRINT "YOU MAY NOT HAVE THAT MANY FURS." -502 PRINT "DO NOT TRY TO CHEAT. I CAN ADD." +501 PRINT "YOU MAY NOT HAVE THAT MANY FURS." +502 PRINT "DO NOT TRY TO CHEAT. I CAN ADD." 503 PRINT "YOU MUST START AGAIN." -504 GOTO 15 +504 GOTO 15 508 PRINT 511 PRINT "DO YOU WANT TO TRADE FURS NEXT YEAR?" -513 GOTO 18 +513 GOTO 18 1091 PRINT "YOU ARE THE LEADER OF A FRENCH FUR TRADING EXPEDITION IN " -1092 PRINT "1776 LEAVING THE LAKE ONTARIO AREA TO SELL FURS AND GET" +1092 PRINT "1776 LEAVING THE LAKE ONTARIO AREA TO SELL FURS AND GET" 1093 PRINT "SUPPLIES FOR THE NEXT YEAR. YOU HAVE A CHOICE OF THREE" 1094 PRINT "FORTS AT WHICH YOU MAY TRADE. THE COST OF SUPPLIES" -1095 PRINT "AND THE AMOUNT YOU RECEIVE FOR YOUR FURS WILL DEPEND" -1096 PRINT "ON THE FORT THAT YOU CHOOSE." -1099 RETURN +1095 PRINT "AND THE AMOUNT YOU RECEIVE FOR YOUR FURS WILL DEPEND" +1096 PRINT "ON THE FORT THAT YOU CHOOSE." +1099 RETURN 1100 PRINT "YOU MAY TRADE YOUR FURS AT FORT 1, FORT 2," 1102 PRINT "OR FORT 3. FORT 1 IS FORT HOCHELAGA (MONTREAL)" -1103 PRINT "AND IS UNDER THE PROTECTION OF THE FRENCH ARMY." -1104 PRINT "FORT 2 IS FORT STADACONA (QUEBEC) AND IS UNDER THE" +1103 PRINT "AND IS UNDER THE PROTECTION OF THE FRENCH ARMY." +1104 PRINT "FORT 2 IS FORT STADACONA (QUEBEC) AND IS UNDER THE" 1105 PRINT "PROTECTION OF THE FRENCH ARMY. HOWEVER, YOU MUST" -1106 PRINT "MAKE A PORTAGE AND CROSS THE LACHINE RAPIDS." -1108 PRINT "FORT 3 IS FORT NEW YORK AND IS UNDER DUTCH CONTROL." +1106 PRINT "MAKE A PORTAGE AND CROSS THE LACHINE RAPIDS." +1108 PRINT "FORT 3 IS FORT NEW YORK AND IS UNDER DUTCH CONTROL." 1109 PRINT "YOU MUST CROSS THROUGH IROQUOIS LAND." 1110 PRINT "ANSWER 1, 2, OR 3." 1111 INPUT B -1112 IF B=1 THEN 1120 -1113 IF B=2 THEN 1135 -1115 IF B=3 THEN 1147 -1116 GOTO 1110 -1120 PRINT "YOU HAVE CHOSEN THE EASIEST ROUTE. HOWEVER, THE FORT" -1121 PRINT "IS FAR FROM ANY SEAPORT. THE VALUE" -1122 PRINT "YOU RECEIVE FOR YOUR FURS WILL BE LOW AND THE COST" +1112 IF B=1 THEN 1120 +1113 IF B=2 THEN 1135 +1115 IF B=3 THEN 1147 +1116 GOTO 1110 +1120 PRINT "YOU HAVE CHOSEN THE EASIEST ROUTE. HOWEVER, THE FORT" +1121 PRINT "IS FAR FROM ANY SEAPORT. THE VALUE" +1122 PRINT "YOU RECEIVE FOR YOUR FURS WILL BE LOW AND THE COST" 1123 PRINT "OF SUPPLIES HIGHER THAN AT FORTS STADACONA OR NEW YORK." -1125 GOSUB 1400 +1125 GOSUB 1400 1129 IF B$="YES" THEN 1110 1130 GOTO 1160 -1135 PRINT "YOU HAVE CHOSEN A HARD ROUTE. IT IS, IN COMPARSION," -1136 PRINT "HARDER THAN THE ROUTE TO HOCHELAGA BUT EASIER THAN" +1135 PRINT "YOU HAVE CHOSEN A HARD ROUTE. IT IS, IN COMPARSION," +1136 PRINT "HARDER THAN THE ROUTE TO HOCHELAGA BUT EASIER THAN" 1137 PRINT "THE ROUTE TO NEW YORK. YOU WILL RECEIVE AN AVERAGE VALUE" 1138 PRINT "FOR YOUR FURS AND THE COST OF YOUR SUPPLIES WILL BE AVERAGE." -1141 GOSUB 1400 +1141 GOSUB 1400 1144 IF B$="YES" THEN 1110 1145 GOTO 1198 1147 PRINT "YOU HAVE CHOSEN THE MOST DIFFICULT ROUTE. AT" -1148 PRINT "FORT NEW YORK YOU WILL RECEIVE THE HIGHEST VALUE" +1148 PRINT "FORT NEW YORK YOU WILL RECEIVE THE HIGHEST VALUE" 1149 PRINT "FOR YOUR FURS. THE COST OF YOUR SUPPLIES" -1150 PRINT "WILL BE LOWER THAN AT ALL THE OTHER FORTS." -1152 GOSUB 1400 +1150 PRINT "WILL BE LOWER THAN AT ALL THE OTHER FORTS." +1152 GOSUB 1400 1155 IF B$="YES" THEN 1110 1156 GOTO 1250 1160 LET I=I-160 @@ -87,7 +87,7 @@ 1177 LET D1=INT((.2*RND(1)+.8)*10^2+.5)/10^2 1180 PRINT "SUPPLIES AT FORT HOCHELAGA COST $150.00." 1181 PRINT "YOUR TRAVEL EXPENSES TO HOCHELAGA WERE $10.00." -1190 GOTO 1410 +1190 GOTO 1410 1198 LET I=I-140 1201 PRINT 1205 LET M1=INT((.3*RND(1)+.85)*10^2+.5)/10^2 @@ -99,26 +99,26 @@ 1213 IF P<=8 THEN 1226 1215 IF P<=10 THEN 1235 1216 LET F(2)=0 -1218 PRINT "YOUR BEAVER WERE TOO HEAVY TO CARRY ACROSS" -1219 PRINT "THE PORTAGE. YOU HAD TO LEAVE THE PELTS, BUT FOUND" +1218 PRINT "YOUR BEAVER WERE TOO HEAVY TO CARRY ACROSS" +1219 PRINT "THE PORTAGE. YOU HAD TO LEAVE THE PELTS, BUT FOUND" 1220 PRINT "THEM STOLEN WHEN YOU RETURNED." -1221 GOSUB 1244 -1222 GOTO 1414 -1224 PRINT "YOU ARRIVED SAFELY AT FORT STADACONA." -1225 GOTO 1239 -1226 GOSUB 1430 -1230 PRINT "YOUR CANOE UPSET IN THE LACHINE RAPIDS. YOU" -1231 PRINT "LOST ALL YOUR FURS." -1232 GOSUB 1244 -1233 GOTO 1418 -1235 LET F(4)=0 +1221 GOSUB 1244 +1222 GOTO 1414 +1224 PRINT "YOU ARRIVED SAFELY AT FORT STADACONA." +1225 GOTO 1239 +1226 GOSUB 1430 +1230 PRINT "YOUR CANOE UPSET IN THE LACHINE RAPIDS. YOU" +1231 PRINT "LOST ALL YOUR FURS." +1232 GOSUB 1244 +1233 GOTO 1418 +1235 LET F(4)=0 1237 PRINT "YOUR FOX PELTS WERE NOT CURED PROPERLY." 1238 PRINT "NO ONE WILL BUY THEM." -1239 GOSUB 1244 -1240 GOTO 1410 +1239 GOSUB 1244 +1240 GOTO 1410 1244 PRINT "SUPPLIES AT FORT STADACONA COST $125.00." 1246 PRINT "YOUR TRAVEL EXPENSES TO STADACONA WERE $15.00." -1248 RETURN +1248 RETURN 1250 LET I=I-105 1254 PRINT 1260 LET M1=INT((.15*RND(1)+1.05)*10^2+.5)/10^2 @@ -129,30 +129,30 @@ 1273 IF P<=8 THEN 1295 1274 IF P<=10 THEN 1306 1281 PRINT "YOU WERE ATTACKED BY A PARTY OF IROQUOIS." -1282 PRINT "ALL PEOPLE IN YOUR TRADING GROUP WERE" -1283 PRINT "KILLED. THIS ENDS THE GAME." -1284 STOP +1282 PRINT "ALL PEOPLE IN YOUR TRADING GROUP WERE" +1283 PRINT "KILLED. THIS ENDS THE GAME." +1284 STOP 1291 PRINT "YOU WERE LUCKY. YOU ARRIVED SAFELY" 1292 PRINT "AT FORT NEW YORK." -1293 GOTO 1311 -1295 GOSUB 1430 +1293 GOTO 1311 +1295 GOSUB 1430 1300 PRINT "YOU NARROWLY ESCAPED AN IROQUOIS RAIDING PARTY." 1301 PRINT "HOWEVER, YOU HAD TO LEAVE ALL YOUR FURS BEHIND." -1303 GOSUB 1320 -1304 GOTO 1418 +1303 GOSUB 1320 +1304 GOTO 1418 1306 LET B1=B1/2 1307 LET M1=M1/2 1308 PRINT "YOUR MINK AND BEAVER WERE DAMAGED ON YOUR TRIP." 1309 PRINT "YOU RECEIVE ONLY HALF THE CURRENT PRICE FOR THESE FURS." 1311 GOSUB 1320 -1312 GOTO 1410 -1320 PRINT "SUPPLIES AT NEW YORK COST $80.00." +1312 GOTO 1410 +1320 PRINT "SUPPLIES AT NEW YORK COST $80.00." 1321 PRINT "YOUR TRAVEL EXPENSES TO NEW YORK WERE $25.00." -1322 RETURN +1322 RETURN 1400 PRINT "DO YOU WANT TO TRADE AT ANOTHER FORT?" 1402 PRINT "ANSWER YES OR NO", 1403 INPUT B$ -1404 RETURN +1404 RETURN 1410 PRINT 1412 PRINT "YOUR BEAVER SOLD FOR $";B1*F(2); 1414 PRINT "YOUR FOX SOLD FOR $";D1*F(4) @@ -162,9 +162,9 @@ 1420 PRINT 1422 PRINT "YOU NOW HAVE $";I;" INCLUDING YOUR PREVIOUS SAVINGS" 1425 GOTO 508 -1430 FOR J=1 TO 4 -1432 LET F(J)=0 -1434 NEXT J -1436 RETURN +1430 FOR J=1 TO 4 +1432 LET F(J)=0 +1434 NEXT J +1436 RETURN 2000 DATA "MINK","BEAVER","ERMINE","FOX" 2046 END diff --git a/38_Fur_Trader/javascript/furtrader.js b/38_Fur_Trader/javascript/furtrader.js index c27ab0494..206facd4c 100644 --- a/38_Fur_Trader/javascript/furtrader.js +++ b/38_Fur_Trader/javascript/furtrader.js @@ -12,10 +12,10 @@ function input() { var input_element; var input_str; - + return new Promise(function (resolve) { input_element = document.createElement("INPUT"); - + print("? "); input_element.setAttribute("type", "text"); input_element.setAttribute("length", "50"); @@ -178,7 +178,7 @@ async function main() } print("SUPPLIES AT FORT STADACONA COST $125.00.\n"); print("YOUR TRAVEL EXPENSES TO STADACONA WERE $15.00.\n"); - + d1 = Math.floor((0.2 * Math.random() + 0.8) * Math.pow(10, 2) + 0.5) / Math.pow(10, 2); } else if (b == 3) { i -= 105; diff --git a/38_Fur_Trader/python/README.md b/38_Fur_Trader/python/README.md index d90f8449d..cda8ed790 100644 --- a/38_Fur_Trader/python/README.md +++ b/38_Fur_Trader/python/README.md @@ -5,21 +5,20 @@ Conversion to [Python](https://www.python.org/about/) ##### Translator Notes: I tried to preserve as much of the original layout and flow of the code as possible. However I did use quasi enumerated types for the Fort numbers -and Fur types. I think this was certainly a change for the better, and +and Fur types. I think this was certainly a change for the better, and makes the code much easier to read. I program in many different languages on a daily basis. Most languages -require brackets around expressions, so I just cannot bring myself to -write an expression without brackets. IMHO it makes the code easier to study, +require brackets around expressions, so I just cannot bring myself to +write an expression without brackets. IMHO it makes the code easier to study, but it does contravene the Python PEP-8 Style guide. Interestingly the code seems to have a bug around the prices of Fox Furs. The commodity-rate for these is stored in the variable `D1`, however some -paths through the code do not set this price. So there was a chance of -using this uninitialised, or whatever the previous loop set. I don't +paths through the code do not set this price. So there was a chance of +using this uninitialised, or whatever the previous loop set. I don't think this was the original authors intent. So I preserved the original flow -of the code (using the previous `D1` value), but also catching the +of the code (using the previous `D1` value), but also catching the uninitialised path, and assigning a "best guess" value. krt@krt.com.au 2020-10-10 - diff --git a/38_Fur_Trader/python/furtrader.py b/38_Fur_Trader/python/furtrader.py index b26b2f1ae..7032d50af 100755 --- a/38_Fur_Trader/python/furtrader.py +++ b/38_Fur_Trader/python/furtrader.py @@ -1,68 +1,66 @@ #! /usr/bin/env python3 -import sys # for system function, like exit() -import random # for generating random numbers - +import random # for generating random numbers +import sys # for system function, like exit() ### global variables for storing player's status -player_funds = 0 # no money -player_furs = [ 0, 0, 0, 0 ] # no furs +player_funds = 0 # no money +player_furs = [0, 0, 0, 0] # no furs ### Constants -FUR_MINK = 0 +FUR_MINK = 0 FUR_BEAVER = 1 FUR_ERMINE = 2 -FUR_FOX = 3 -MAX_FURS = 190 -FUR_NAMES = [ "MINK", "BEAVER", "ERMINE", "FOX" ] +FUR_FOX = 3 +MAX_FURS = 190 +FUR_NAMES = ["MINK", "BEAVER", "ERMINE", "FOX"] FORT_MONTREAL = 1 -FORT_QUEBEC = 2 -FORT_NEWYORK = 3 -FORT_NAMES = [ "HOCHELAGA (MONTREAL)", "STADACONA (QUEBEC)", "NEW YORK" ] - +FORT_QUEBEC = 2 +FORT_NEWYORK = 3 +FORT_NAMES = ["HOCHELAGA (MONTREAL)", "STADACONA (QUEBEC)", "NEW YORK"] -def printAtColumn( column:int, words:str ): - """ Print the words at the specified column """ - spaces = ' ' * column # make a fat string of spaces - print( spaces + words ) +def printAtColumn(column: int, words: str): + """Print the words at the specified column""" + spaces = " " * column # make a fat string of spaces + print(spaces + words) def showIntroduction(): - """ Show the player the introductory message """ - print( "YOU ARE THE LEADER OF A FRENCH FUR TRADING EXPEDITION IN " ) - print( "1776 LEAVING THE LAKE ONTARIO AREA TO SELL FURS AND GET" ) - print( "SUPPLIES FOR THE NEXT YEAR. YOU HAVE A CHOICE OF THREE" ) - print( "FORTS AT WHICH YOU MAY TRADE. THE COST OF SUPPLIES" ) - print( "AND THE AMOUNT YOU RECEIVE FOR YOUR FURS WILL DEPEND" ) - print( "ON THE FORT THAT YOU CHOOSE." ) - print( "" ) + """Show the player the introductory message""" + print("YOU ARE THE LEADER OF A FRENCH FUR TRADING EXPEDITION IN ") + print("1776 LEAVING THE LAKE ONTARIO AREA TO SELL FURS AND GET") + print("SUPPLIES FOR THE NEXT YEAR. YOU HAVE A CHOICE OF THREE") + print("FORTS AT WHICH YOU MAY TRADE. THE COST OF SUPPLIES") + print("AND THE AMOUNT YOU RECEIVE FOR YOUR FURS WILL DEPEND") + print("ON THE FORT THAT YOU CHOOSE.") + print("") def getFortChoice(): - """ Show the player the choices of Fort, get their input, if the - input is a valid choice (1,2,3) return it, otherwise keep - prompting the user. """ + """Show the player the choices of Fort, get their input, if the + input is a valid choice (1,2,3) return it, otherwise keep + prompting the user.""" result = 0 - while ( result == 0 ): - print( "" ) - print( "YOU MAY TRADE YOUR FURS AT FORT 1, FORT 2," ) - print( "OR FORT 3. FORT 1 IS FORT HOCHELAGA (MONTREAL)" ) - print( "AND IS UNDER THE PROTECTION OF THE FRENCH ARMY." ) - print( "FORT 2 IS FORT STADACONA (QUEBEC) AND IS UNDER THE" ) - print( "PROTECTION OF THE FRENCH ARMY. HOWEVER, YOU MUST" ) - print( "MAKE A PORTAGE AND CROSS THE LACHINE RAPIDS." ) - print( "FORT 3 IS FORT NEW YORK AND IS UNDER DUTCH CONTROL." ) - print( "YOU MUST CROSS THROUGH IROQUOIS LAND." ) - print( "ANSWER 1, 2, OR 3." ) - - player_choice = input( ">> " ) # get input from the player + while result == 0: + print("") + print("YOU MAY TRADE YOUR FURS AT FORT 1, FORT 2,") + print("OR FORT 3. FORT 1 IS FORT HOCHELAGA (MONTREAL)") + print("AND IS UNDER THE PROTECTION OF THE FRENCH ARMY.") + print("FORT 2 IS FORT STADACONA (QUEBEC) AND IS UNDER THE") + print("PROTECTION OF THE FRENCH ARMY. HOWEVER, YOU MUST") + print("MAKE A PORTAGE AND CROSS THE LACHINE RAPIDS.") + print("FORT 3 IS FORT NEW YORK AND IS UNDER DUTCH CONTROL.") + print("YOU MUST CROSS THROUGH IROQUOIS LAND.") + print("ANSWER 1, 2, OR 3.") + + player_choice = input(">> ") # get input from the player # try to convert the player's string input into an integer try: - result = int( player_choice ) # string to integer + result = int(player_choice) # string to integer except: # Whatever the player typed, it could not be interpreted as a number pass @@ -70,228 +68,255 @@ def getFortChoice(): return result -def showFortComment( which_fort ): - """ Print the description for the fort """ - print( "" ) - if ( which_fort == FORT_MONTREAL ): - print( "YOU HAVE CHOSEN THE EASIEST ROUTE. HOWEVER, THE FORT" ) - print( "IS FAR FROM ANY SEAPORT. THE VALUE" ) - print( "YOU RECEIVE FOR YOUR FURS WILL BE LOW AND THE COST" ) - print( "OF SUPPLIES HIGHER THAN AT FORTS STADACONA OR NEW YORK." ) - elif ( which_fort == FORT_QUEBEC ): - print( "YOU HAVE CHOSEN A HARD ROUTE. IT IS, IN COMPARSION," ) - print( "HARDER THAN THE ROUTE TO HOCHELAGA BUT EASIER THAN" ) - print( "THE ROUTE TO NEW YORK. YOU WILL RECEIVE AN AVERAGE VALUE" ) - print( "FOR YOUR FURS AND THE COST OF YOUR SUPPLIES WILL BE AVERAGE." ) - elif ( which_fort == FORT_NEWYORK ): - print( "YOU HAVE CHOSEN THE MOST DIFFICULT ROUTE. AT" ) - print( "FORT NEW YORK YOU WILL RECEIVE THE HIGHEST VALUE" ) - print( "FOR YOUR FURS. THE COST OF YOUR SUPPLIES" ) - print( "WILL BE LOWER THAN AT ALL THE OTHER FORTS." ) +def showFortComment(which_fort): + """Print the description for the fort""" + print("") + if which_fort == FORT_MONTREAL: + print("YOU HAVE CHOSEN THE EASIEST ROUTE. HOWEVER, THE FORT") + print("IS FAR FROM ANY SEAPORT. THE VALUE") + print("YOU RECEIVE FOR YOUR FURS WILL BE LOW AND THE COST") + print("OF SUPPLIES HIGHER THAN AT FORTS STADACONA OR NEW YORK.") + elif which_fort == FORT_QUEBEC: + print("YOU HAVE CHOSEN A HARD ROUTE. IT IS, IN COMPARSION,") + print("HARDER THAN THE ROUTE TO HOCHELAGA BUT EASIER THAN") + print("THE ROUTE TO NEW YORK. YOU WILL RECEIVE AN AVERAGE VALUE") + print("FOR YOUR FURS AND THE COST OF YOUR SUPPLIES WILL BE AVERAGE.") + elif which_fort == FORT_NEWYORK: + print("YOU HAVE CHOSEN THE MOST DIFFICULT ROUTE. AT") + print("FORT NEW YORK YOU WILL RECEIVE THE HIGHEST VALUE") + print("FOR YOUR FURS. THE COST OF YOUR SUPPLIES") + print("WILL BE LOWER THAN AT ALL THE OTHER FORTS.") else: - print( "Internal error #1, fort " + str( which_fort ) + " does not exist" ) - sys.exit( 1 ) # you have a bug - print( "" ) - + print("Internal error #1, fort " + str(which_fort) + " does not exist") + sys.exit(1) # you have a bug + print("") + def getYesOrNo(): - """ Prompt the player to enter 'YES' or 'NO'. Keep prompting until - valid input is entered. Accept various spellings by only - checking the first letter of input. - Return a single letter 'Y' or 'N' """ + """Prompt the player to enter 'YES' or 'NO'. Keep prompting until + valid input is entered. Accept various spellings by only + checking the first letter of input. + Return a single letter 'Y' or 'N'""" result = 0 - while ( result not in ( 'Y', 'N' ) ): - print( "ANSWER YES OR NO" ) - player_choice = input( ">> " ) + while result not in ("Y", "N"): + print("ANSWER YES OR NO") + player_choice = input(">> ") player_choice = player_choice.strip().upper() # trim spaces, make upper-case - if ( player_choice.startswith( 'Y' ) ): - result = 'Y' - elif ( player_choice.startswith( 'N' ) ): - result = 'N' + if player_choice.startswith("Y"): + result = "Y" + elif player_choice.startswith("N"): + result = "N" return result - + def getFursPurchase(): - """ Prompt the player for how many of each fur type they want. - Accept numeric inputs, re-prompting on incorrect input values """ + """Prompt the player for how many of each fur type they want. + Accept numeric inputs, re-prompting on incorrect input values""" results = [] - print( "YOUR " + str( MAX_FURS ) + " FURS ARE DISTRIBUTED AMONG THE FOLLOWING" ) - print( "KINDS OF PELTS: MINK, BEAVER, ERMINE AND FOX." ) - print( "" ) + print("YOUR " + str(MAX_FURS) + " FURS ARE DISTRIBUTED AMONG THE FOLLOWING") + print("KINDS OF PELTS: MINK, BEAVER, ERMINE AND FOX.") + print("") - for i in ( range( len( FUR_NAMES ) ) ): - print( "HOW MANY " + FUR_NAMES[i] + " DO YOU HAVE" ) - count_str = input( ">> " ) + for i in range(len(FUR_NAMES)): + print("HOW MANY " + FUR_NAMES[i] + " DO YOU HAVE") + count_str = input(">> ") try: - count = int( count_str ) - results.append( count ) + count = int(count_str) + results.append(count) except: # invalid input, prompt again by re-looping i -= 1 return results - ### ### MAIN ### -if ( __name__ == '__main__' ): +if __name__ == "__main__": - printAtColumn( 31, "FUR TRADER" ) - printAtColumn( 15, "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY" ) - printAtColumn( 15, "(Ported to Python Oct 2012 krt@krt.com.au)" ) - print( "\n\n\n" ) + printAtColumn(31, "FUR TRADER") + printAtColumn(15, "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY") + printAtColumn(15, "(Ported to Python Oct 2012 krt@krt.com.au)") + print("\n\n\n") - game_state = 'starting' + game_state = "starting" fox_price = None # sometimes this takes the "last" price (probably this was a bug) - while ( True ): + while True: - if ( game_state == 'starting' ): + if game_state == "starting": showIntroduction() - player_funds = 600 # Initial player start money - player_furs = [ 0, 0, 0, 0 ] # Player fur inventory + player_funds = 600 # Initial player start money + player_furs = [0, 0, 0, 0] # Player fur inventory - print( "DO YOU WISH TO TRADE FURS?" ) + print("DO YOU WISH TO TRADE FURS?") should_trade = getYesOrNo() - if ( should_trade == 'N' ): - sys.exit( 0 ) # STOP - game_state = 'trading' - - elif ( game_state == 'trading' ): - print( "" ) - print( "YOU HAVE $ %1.2f IN SAVINGS" % ( player_funds ) ) - print( "AND " + str( MAX_FURS ) + " FURS TO BEGIN THE EXPEDITION" ) + if should_trade == "N": + sys.exit(0) # STOP + game_state = "trading" + + elif game_state == "trading": + print("") + print("YOU HAVE $ %1.2f IN SAVINGS" % (player_funds)) + print("AND " + str(MAX_FURS) + " FURS TO BEGIN THE EXPEDITION") player_furs = getFursPurchase() - if ( sum( player_furs ) > MAX_FURS ): - print( "" ) - print( "YOU MAY NOT HAVE THAT MANY FURS." ) - print( "DO NOT TRY TO CHEAT. I CAN ADD." ) - print( "YOU MUST START AGAIN." ) - game_state = 'starting' # T/N: Wow, harsh. + if sum(player_furs) > MAX_FURS: + print("") + print("YOU MAY NOT HAVE THAT MANY FURS.") + print("DO NOT TRY TO CHEAT. I CAN ADD.") + print("YOU MUST START AGAIN.") + game_state = "starting" # T/N: Wow, harsh. else: - game_state = 'choosing fort' + game_state = "choosing fort" - elif ( game_state == 'choosing fort' ): + elif game_state == "choosing fort": which_fort = getFortChoice() - showFortComment( which_fort ) - print( "DO YOU WANT TO TRADE AT ANOTHER FORT?" ) + showFortComment(which_fort) + print("DO YOU WANT TO TRADE AT ANOTHER FORT?") change_fort = getYesOrNo() - if ( change_fort == 'N' ): - game_state = 'travelling' - - elif ( game_state == 'travelling' ): - print( "" ) - if ( which_fort == FORT_MONTREAL ): - mink_price = int( ( 0.2 * random.random() + 0.70 ) * 100 + 0.5 ) / 100 #INT((.2*RND(1)+.7)*10^2+.5)/10^2 - ermine_price = int( ( 0.2 * random.random() + 0.65 ) * 100 + 0.5 ) / 100 #INT((.2*RND(1)+.65)*10^2+.5)/10^2 - beaver_price = int( ( 0.2 * random.random() + 0.75 ) * 100 + 0.5 ) / 100 #INT((.2*RND(1)+.75)*10^2+.5)/10^2 - fox_price = int( ( 0.2 * random.random() + 0.80 ) * 100 + 0.5 ) / 100 #INT((.2*RND(1)+.8)*10^2+.5)/10^2 - - print( "SUPPLIES AT FORT HOCHELAGA COST $150.00." ) - print( "YOUR TRAVEL EXPENSES TO HOCHELAGA WERE $10.00." ) + if change_fort == "N": + game_state = "travelling" + + elif game_state == "travelling": + print("") + if which_fort == FORT_MONTREAL: + mink_price = ( + int((0.2 * random.random() + 0.70) * 100 + 0.5) / 100 + ) # INT((.2*RND(1)+.7)*10^2+.5)/10^2 + ermine_price = ( + int((0.2 * random.random() + 0.65) * 100 + 0.5) / 100 + ) # INT((.2*RND(1)+.65)*10^2+.5)/10^2 + beaver_price = ( + int((0.2 * random.random() + 0.75) * 100 + 0.5) / 100 + ) # INT((.2*RND(1)+.75)*10^2+.5)/10^2 + fox_price = ( + int((0.2 * random.random() + 0.80) * 100 + 0.5) / 100 + ) # INT((.2*RND(1)+.8)*10^2+.5)/10^2 + + print("SUPPLIES AT FORT HOCHELAGA COST $150.00.") + print("YOUR TRAVEL EXPENSES TO HOCHELAGA WERE $10.00.") player_funds -= 160 - elif ( which_fort == FORT_QUEBEC ): - mink_price = int( ( 0.30 * random.random() + 0.85 ) * 100 + 0.5 ) / 100 #INT((.3*RND(1)+.85)*10^2+.5)/10^2 - ermine_price = int( ( 0.15 * random.random() + 0.80 ) * 100 + 0.5 ) / 100 #INT((.15*RND(1)+.8)*10^2+.5)/10^2 - beaver_price = int( ( 0.20 * random.random() + 0.90 ) * 100 + 0.5 ) / 100 #INT((.2*RND(1)+.9)*10^2+.5)/10^2 - fox_price = int( ( 0.25 * random.random() + 1.10 ) * 100 + 0.5 ) / 100 #INT((.25*RND(1)+1.1)*10^2+.5)/10^2 - event_picker = int( 10 * random.random() ) + 1 - - if ( event_picker <= 2 ): - print( "YOUR BEAVER WERE TOO HEAVY TO CARRY ACROSS" ) - print( "THE PORTAGE. YOU HAD TO LEAVE THE PELTS, BUT FOUND" ) - print( "THEM STOLEN WHEN YOU RETURNED." ) - player_furs[ FUR_BEAVER ] = 0 - elif ( event_picker <= 6 ): - print( "YOU ARRIVED SAFELY AT FORT STADACONA." ) - elif ( event_picker <= 8 ): - print( "YOUR CANOE UPSET IN THE LACHINE RAPIDS. YOU" ) - print( "LOST ALL YOUR FURS." ) - player_furs = [ 0, 0, 0, 0 ] - elif ( event_picker <= 10 ): - print( "YOUR FOX PELTS WERE NOT CURED PROPERLY." ) - print( "NO ONE WILL BUY THEM." ) - player_furs[ FUR_FOX ] = 0 + elif which_fort == FORT_QUEBEC: + mink_price = ( + int((0.30 * random.random() + 0.85) * 100 + 0.5) / 100 + ) # INT((.3*RND(1)+.85)*10^2+.5)/10^2 + ermine_price = ( + int((0.15 * random.random() + 0.80) * 100 + 0.5) / 100 + ) # INT((.15*RND(1)+.8)*10^2+.5)/10^2 + beaver_price = ( + int((0.20 * random.random() + 0.90) * 100 + 0.5) / 100 + ) # INT((.2*RND(1)+.9)*10^2+.5)/10^2 + fox_price = ( + int((0.25 * random.random() + 1.10) * 100 + 0.5) / 100 + ) # INT((.25*RND(1)+1.1)*10^2+.5)/10^2 + event_picker = int(10 * random.random()) + 1 + + if event_picker <= 2: + print("YOUR BEAVER WERE TOO HEAVY TO CARRY ACROSS") + print("THE PORTAGE. YOU HAD TO LEAVE THE PELTS, BUT FOUND") + print("THEM STOLEN WHEN YOU RETURNED.") + player_furs[FUR_BEAVER] = 0 + elif event_picker <= 6: + print("YOU ARRIVED SAFELY AT FORT STADACONA.") + elif event_picker <= 8: + print("YOUR CANOE UPSET IN THE LACHINE RAPIDS. YOU") + print("LOST ALL YOUR FURS.") + player_furs = [0, 0, 0, 0] + elif event_picker <= 10: + print("YOUR FOX PELTS WERE NOT CURED PROPERLY.") + print("NO ONE WILL BUY THEM.") + player_furs[FUR_FOX] = 0 else: - print( "Internal Error #3, Out-of-bounds event_picker" + str( event_picker ) ) - sys.exit( 1 ) # you have a bug - - print( "" ) - print( "SUPPLIES AT FORT STADACONA COST $125.00." ) - print( "YOUR TRAVEL EXPENSES TO STADACONA WERE $15.00." ) + print( + "Internal Error #3, Out-of-bounds event_picker" + + str(event_picker) + ) + sys.exit(1) # you have a bug + + print("") + print("SUPPLIES AT FORT STADACONA COST $125.00.") + print("YOUR TRAVEL EXPENSES TO STADACONA WERE $15.00.") player_funds -= 140 - elif ( which_fort == FORT_NEWYORK ): - mink_price = int( ( 0.15 * random.random() + 1.05 ) * 100 + 0.5 ) / 100 #INT((.15*RND(1)+1.05)*10^2+.5)/10^2 - ermine_price = int( ( 0.15 * random.random() + 0.95 ) * 100 + 0.5 ) / 100 #INT((.15*RND(1)+.95)*10^2+.5)/10^2 - beaver_price = int( ( 0.25 * random.random() + 1.00 ) * 100 + 0.5 ) / 100 #INT((.25*RND(1)+1.00)*10^2+.5)/10^2 - if ( fox_price == None ): + elif which_fort == FORT_NEWYORK: + mink_price = ( + int((0.15 * random.random() + 1.05) * 100 + 0.5) / 100 + ) # INT((.15*RND(1)+1.05)*10^2+.5)/10^2 + ermine_price = ( + int((0.15 * random.random() + 0.95) * 100 + 0.5) / 100 + ) # INT((.15*RND(1)+.95)*10^2+.5)/10^2 + beaver_price = ( + int((0.25 * random.random() + 1.00) * 100 + 0.5) / 100 + ) # INT((.25*RND(1)+1.00)*10^2+.5)/10^2 + if fox_price == None: # Original Bug? There is no Fox price generated for New York, it will use any previous "D1" price # So if there was no previous value, make one up - fox_price = int( ( 0.25 * random.random() + 1.05 ) * 100 + 0.5 ) / 100 # not in orginal code - event_picker = int( 10 * random.random() ) + 1 - - if ( event_picker <= 2 ): - print( "YOU WERE ATTACKED BY A PARTY OF IROQUOIS." ) - print( "ALL PEOPLE IN YOUR TRADING GROUP WERE" ) - print( "KILLED. THIS ENDS THE GAME." ) - sys.exit( 0 ) - elif ( event_picker <= 6 ): - print( "YOU WERE LUCKY. YOU ARRIVED SAFELY" ) - print( "AT FORT NEW YORK." ) - elif ( event_picker <= 8 ): - print( "YOU NARROWLY ESCAPED AN IROQUOIS RAIDING PARTY." ) - print( "HOWEVER, YOU HAD TO LEAVE ALL YOUR FURS BEHIND." ) - player_furs = [ 0, 0, 0, 0 ] - elif ( event_picker <= 10 ): + fox_price = ( + int((0.25 * random.random() + 1.05) * 100 + 0.5) / 100 + ) # not in orginal code + event_picker = int(10 * random.random()) + 1 + + if event_picker <= 2: + print("YOU WERE ATTACKED BY A PARTY OF IROQUOIS.") + print("ALL PEOPLE IN YOUR TRADING GROUP WERE") + print("KILLED. THIS ENDS THE GAME.") + sys.exit(0) + elif event_picker <= 6: + print("YOU WERE LUCKY. YOU ARRIVED SAFELY") + print("AT FORT NEW YORK.") + elif event_picker <= 8: + print("YOU NARROWLY ESCAPED AN IROQUOIS RAIDING PARTY.") + print("HOWEVER, YOU HAD TO LEAVE ALL YOUR FURS BEHIND.") + player_furs = [0, 0, 0, 0] + elif event_picker <= 10: mink_price /= 2 - fox_price /= 2 - print( "YOUR MINK AND BEAVER WERE DAMAGED ON YOUR TRIP." ) - print( "YOU RECEIVE ONLY HALF THE CURRENT PRICE FOR THESE FURS." ) + fox_price /= 2 + print("YOUR MINK AND BEAVER WERE DAMAGED ON YOUR TRIP.") + print("YOU RECEIVE ONLY HALF THE CURRENT PRICE FOR THESE FURS.") else: - print( "Internal Error #4, Out-of-bounds event_picker" + str( event_picker ) ) - sys.exit( 1 ) # you have a bug - - print( "" ) - print( "SUPPLIES AT NEW YORK COST $85.00." ) - print( "YOUR TRAVEL EXPENSES TO NEW YORK WERE $25.00." ) + print( + "Internal Error #4, Out-of-bounds event_picker" + + str(event_picker) + ) + sys.exit(1) # you have a bug + + print("") + print("SUPPLIES AT NEW YORK COST $85.00.") + print("YOUR TRAVEL EXPENSES TO NEW YORK WERE $25.00.") player_funds -= 105 - else: - print( "Internal error #2, fort " + str( which_fort ) + " does not exist" ) - sys.exit( 1 ) # you have a bug + print("Internal error #2, fort " + str(which_fort) + " does not exist") + sys.exit(1) # you have a bug # Calculate sales - beaver_value = beaver_price * player_furs[ FUR_BEAVER ] - fox_value = fox_price * player_furs[ FUR_FOX ] - ermine_value = ermine_price * player_furs[ FUR_ERMINE ] - mink_value = mink_price * player_furs[ FUR_MINK ] - - print( "" ) - print( "YOUR BEAVER SOLD FOR $%6.2f" % ( beaver_value ) ) - print( "YOUR FOX SOLD FOR $%6.2f" % ( fox_value ) ) - print( "YOUR ERMINE SOLD FOR $%6.2f" % ( ermine_value ) ) - print( "YOUR MINK SOLD FOR $%6.2f" % ( mink_value ) ) + beaver_value = beaver_price * player_furs[FUR_BEAVER] + fox_value = fox_price * player_furs[FUR_FOX] + ermine_value = ermine_price * player_furs[FUR_ERMINE] + mink_value = mink_price * player_furs[FUR_MINK] + + print("") + print("YOUR BEAVER SOLD FOR $%6.2f" % (beaver_value)) + print("YOUR FOX SOLD FOR $%6.2f" % (fox_value)) + print("YOUR ERMINE SOLD FOR $%6.2f" % (ermine_value)) + print("YOUR MINK SOLD FOR $%6.2f" % (mink_value)) player_funds += beaver_value + fox_value + ermine_value + mink_value - print( "" ) - print( "YOU NOW HAVE $ %1.2f INCLUDING YOUR PREVIOUS SAVINGS" % ( player_funds ) ) + print("") + print( + "YOU NOW HAVE $ %1.2f INCLUDING YOUR PREVIOUS SAVINGS" % (player_funds) + ) - print( "" ) - print( "DO YOU WANT TO TRADE FURS NEXT YEAR?" ) + print("") + print("DO YOU WANT TO TRADE FURS NEXT YEAR?") should_trade = getYesOrNo() - if ( should_trade == 'N' ): - sys.exit( 0 ) # STOP + if should_trade == "N": + sys.exit(0) # STOP else: - game_state = 'trading' - - - + game_state = "trading" diff --git a/39_Golf/csharp/Program.cs b/39_Golf/csharp/Program.cs index abbbaf6b8..623409cde 100644 --- a/39_Golf/csharp/Program.cs +++ b/39_Golf/csharp/Program.cs @@ -1,10 +1,10 @@ // -// 8""""8 8"""88 8 8"""" -// 8 " 8 8 8 8 -// 8e 8 8 8e 8eeee -// 88 ee 8 8 88 88 -// 88 8 8 8 88 88 -// 88eee8 8eeee8 88eee 88 +// 8""""8 8"""88 8 8"""" +// 8 " 8 8 8 8 +// 8e 8 8 8e 8eeee +// 88 ee 8 8 88 88 +// 88 8 8 8 88 88 +// 88eee8 8eeee8 88eee 88 // // GOLF // @@ -20,7 +20,7 @@ // // Windows compile: // dotnet publish -r win-x64 -c Release /p:PublishSingleFile=true -// +// // // INDEX // ----------------- methods @@ -62,79 +62,79 @@ // ToDegrees360 // Odds // -// Despite being a text based game, the code uses simple geometry to simulate a course. +// Despite being a text based game, the code uses simple geometry to simulate a course. // Fairways are 40 yard wide rectangles, surrounded by 5 yards of rough around the perimeter. -// The green is a circle of 10 yards radius around the cup. -// The cup is always at point (0,0). +// The green is a circle of 10 yards radius around the cup. +// The cup is always at point (0,0). // // Using basic trigonometry we can plot the ball's location using the distance of the stroke and -// and the angle of deviation (hook/slice). +// and the angle of deviation (hook/slice). // -// The stroke distances are based on real world averages of different club types. +// The stroke distances are based on real world averages of different club types. // Lots of randomization, "business rules", and luck influence the game play. -// Probabilities are commented in the code. +// Probabilities are commented in the code. // // note: 'courseInfo', 'clubs', & 'scoreCard' arrays each include an empty object so indexing // can begin at 1. Like all good programmers we count from zero, but in this context, // it's more natural when hole number one is at index one // -// -// |-----------------------------| +// +// |-----------------------------| // | rough | -// | ---------------------- | -// | | | | -// | r | = = | r | -// | o | = = | o | -// | u | = . = | u | -// | g | = green = | g | -// | h | = = | h | -// | | = = | | -// | | | | -// | | | | -// | | Fairway | | -// | | | | +// | ---------------------- | +// | | | | +// | r | = = | r | +// | o | = = | o | +// | u | = . = | u | +// | g | = green = | g | +// | h | = = | h | +// | | = = | | +// | | | | +// | | | | +// | | Fairway | | +// | | | | // | | ------ | // | | -- -- | // | | -- hazard --| // | | -- -- | // | | ------ | -// | | | | +// | | | | // | | | | out // | | | | of // | | | | bounds // | | | | -// | | | | -// | tee | -// +// | | | | +// | tee | +// // // Typical green size: 20-30 yards -// Typical golf course fairways are 35 to 45 yards wide +// Typical golf course fairways are 35 to 45 yards wide // Our fairway extends 5 yards past green // Our rough is a 5 yard perimeter around fairway -// +// // We calculate the new position of the ball given the ball's point, the distance // of the stroke, and degrees off line (hook or slice). // // Degrees off (for a right handed golfer): -// Slice: positive degrees = ball goes right +// Slice: positive degrees = ball goes right // Hook: negative degrees = left goes left -// +// // The cup is always at point: 0,0. // We use atan2 to compute the angle between the cup and the ball. -// Setting the cup's vector to 0,-1 on a 360 circle is equivalent to: +// Setting the cup's vector to 0,-1 on a 360 circle is equivalent to: // 0 deg = 12 o'clock; 90 deg = 3 o'clock; 180 deg = 6 o'clock; 270 = 9 o'clock // The reverse angle between the cup and the ball is a difference of PI (using radians). // // Given the angle and stroke distance (hypotenuse), we use cosine to compute // the opposite and adjacent sides of the triangle, which, is the ball's new position. -// +// // 0 // | // 270 - cup - 90 // | // 180 -// -// +// +// // cup // | // | @@ -147,19 +147,19 @@ // |/ // tee // -// <- hook slice -> +// <- hook slice -> // // // Given the large number of combinations needed to describe a particular stroke / ball location, -// we use the technique of "bitwise masking" to describe stroke results. +// we use the technique of "bitwise masking" to describe stroke results. // With bit masking, multiple flags (bits) are combined into a single binary number that can be // tested by applying a mask. A mask is another binary number that isolates a particular bit that // you are interested in. You can then apply your language's bitwise opeartors to test or -// set a flag. +// set a flag. // // Game design by Jason Bonthron, 2021 // www.bonthron.com -// for my father, Raymond Bonthron, an avid golfer +// for my father, Raymond Bonthron, an avid golfer // // Inspired by the 1978 "Golf" from "Basic Computer Games" // by Steve North, who modified an existing golf game by an unknown author @@ -176,7 +176,7 @@ namespace Golf { using Ball = Golf.CircleGameObj; using Hazard = Golf.CircleGameObj; - + // --------------------------------------------------------------------------- Program class Program { @@ -186,7 +186,7 @@ static void Main(string[] args) } } - + // --------------------------------------------------------------------------- Golf public class Golf { @@ -209,7 +209,7 @@ public class Golf List> ScoreCard = new List> { new List() }; - static void w(string s) { Console.WriteLine(s); } // WRITE + static void w(string s) { Console.WriteLine(s); } // WRITE Random RANDOM = new Random(); @@ -238,7 +238,7 @@ public Golf() Wait((z) => { w(" "); - w(" YOUR BAG"); + w(" YOUR BAG"); ReviewBag(); w("Type BAG at any time to review the clubs in your bag."); w(" "); @@ -246,7 +246,7 @@ public Golf() Wait((zz) => { w(" "); - + Ask("PGA handicaps range from 0 to 30.\nWhat is your handicap?", 0, 30, (i) => { Handicap = i; @@ -342,7 +342,7 @@ void TeeUp() }; } - + // -------------------------------------------------------- bitwise Flags int dub = 0b00000000000001; int hook = 0b00000000000010; @@ -412,24 +412,24 @@ void Stroke(double clubAmt, int clubIndex) }; // beginner's luck ! - // If handicap is greater than 15, there's a 10% chance of avoiding all errors + // If handicap is greater than 15, there's a 10% chance of avoiding all errors if ((Handicap > 15) && (Odds(10))) { flags |= luck; }; // ace - // there's a 10% chance of an Ace on a par 3 + // there's a 10% chance of an Ace on a par 3 if (CourseInfo[HOLE_NUM].Par == 3 && Odds(10) && STROKE_NUM == 1) { flags |= ace; }; // distance: // If handicap is < 15, there a 50% chance of reaching club average, - // a 25% of exceeding it, and a 25% of falling short + // a 25% of exceeding it, and a 25% of falling short // If handicap is > 15, there's a 25% chance of reaching club average, // and 75% chance of falling short // The greater the handicap, the more the ball falls short - // If poor distance is a known playerDifficulty, then reduce distance by 10% + // If poor distance is a known playerDifficulty, then reduce distance by 10% double distance; int rnd = RANDOM.Next(1, 101); - + if (Handicap < 15) { if (rnd <= 25) @@ -465,7 +465,7 @@ void Stroke(double clubAmt, int clubIndex) if ((flags & luck) == luck) { distance = clubAmt; } // angle - // For all strokes, there's a possible "drift" of 4 degrees + // For all strokes, there's a possible "drift" of 4 degrees // a hooks or slice increases the angle between 5-10 degrees, hook uses negative degrees int angle = RANDOM.Next(0, 5); if ((flags & slice) == slice) { angle = RANDOM.Next(5, 11); }; @@ -614,7 +614,7 @@ void InterpretResults(Plot plot, int flags) TeeUp(); } - + // --------------------------------------------------------------- ReportCurrentScore void ReportCurrentScore() { @@ -624,18 +624,18 @@ void ReportCurrentScore() if (ScoreCard[HOLE_NUM].Count == (par - 1)) { w("A birdie! One below par."); }; if (ScoreCard[HOLE_NUM].Count == (par - 2)) { w("An Eagle! Two below par."); }; if (ScoreCard[HOLE_NUM].Count == (par - 3)) { w("Double Eagle! Unbelievable."); }; - + int totalPar = 0; for (var i = 1; i <= HOLE_NUM; i++) { totalPar += CourseInfo[i].Par; }; w(" "); - w("-----------------------------------------------------"); + w("-----------------------------------------------------"); Console.WriteLine(" Total par for {0} hole{1} is: {2}. Your total is: {3}.", HOLE_NUM, - ((HOLE_NUM > 1) ? "s" : ""), //plural + ((HOLE_NUM > 1) ? "s" : ""), //plural totalPar, ScoreCardGetTotal()); - w("-----------------------------------------------------"); + w("-----------------------------------------------------"); w(" "); if (HOLE_NUM == 18) @@ -649,7 +649,7 @@ void ReportCurrentScore() }; } - + // --------------------------------------------------------------- FindBall int FindBall(Ball ball, int flags) { @@ -660,7 +660,7 @@ int FindBall(Ball ball, int flags) if (IsInHazard(ball, GameObjType.WATER)) { flags |= inWater; } if (IsInHazard(ball, GameObjType.TREES)) { flags |= inTrees; } if (IsInHazard(ball, GameObjType.SAND)) { flags |= inSand; } - + if (ball.Y < 0) { flags |= passedCup; } // less than 2, it's in the cup @@ -671,14 +671,14 @@ int FindBall(Ball ball, int flags) return flags; } - + // --------------------------------------------------------------- IsOnFairway bool IsOnFairway(Ball ball) { return IsInRectangle(ball, holeGeometry.Fairway); } - + // --------------------------------------------------------------- IsOngreen bool IsOnGreen(Ball ball) { @@ -687,7 +687,7 @@ bool IsOnGreen(Ball ball) return d < holeGeometry.Green.Radius; } - + // --------------------------------------------------------------- IsInHazard bool IsInHazard(Ball ball, GameObjType hazard) { @@ -700,7 +700,7 @@ bool IsInHazard(Ball ball, GameObjType hazard) return result; } - + // --------------------------------------------------------------- IsInRough bool IsInRough(Ball ball) { @@ -708,7 +708,7 @@ bool IsInRough(Ball ball) (IsInRectangle(ball, holeGeometry.Fairway) == false); } - + // --------------------------------------------------------------- IsOutOfBounds bool IsOutOfBounds(Ball ball) { @@ -723,7 +723,7 @@ void ScoreCardStartNewHole() } - // --------------------------------------------------------------- ScoreCardRecordStroke + // --------------------------------------------------------------- ScoreCardRecordStroke void ScoreCardRecordStroke(Ball ball) { var clone = new Ball(ball.X, ball.Y, 0, GameObjType.BALL); @@ -783,7 +783,7 @@ void Ask(string question, int min, int max, Action callback) void Wait(Action callback) { w("Press any key to continue."); - + ConsoleKeyInfo keyinfo; do { keyinfo = Console.ReadKey(true); } while (keyinfo.KeyChar < 0); @@ -828,10 +828,10 @@ void GameOver() { var net = ScoreCardGetTotal() - Handicap; w("Good game!"); - w("Your net score is: " + net); + w("Your net score is: " + net); w("Let's visit the pro shop..."); w(" "); - Wait((z) => { }); + Wait((z) => { }); return; } @@ -840,8 +840,8 @@ void GameOver() // ======================================================== Clubs (string, int)[] Clubs = new (string, int)[] { ("",0), - - // name, average yardage + + // name, average yardage ("Driver", 250), ("3 Wood", 225), ("5 Wood", 200), @@ -861,7 +861,7 @@ void GameOver() HoleInfo[] CourseInfo = new HoleInfo[]{ new HoleInfo(0, 0, 0, new Hazard[]{}, ""), // include a blank so index 1 == hole 1 - + // -------------------------------------------------------- front 9 // hole, yards, par, hazards, (description) @@ -927,8 +927,8 @@ void GameOver() new Hazard(-30, 180, 20, GameObjType.TREES), new Hazard( 14, -8, 5, GameObjType.SAND) }, - ""), - + ""), + // -------------------------------------------------------- back 9 // hole, yards, par, hazards, (description) @@ -999,7 +999,7 @@ void GameOver() "There is a water hazard near the green.") }; - + // -------------------------------------------------------- HoleInfo class HoleInfo { @@ -1114,7 +1114,7 @@ bool IsInRectangle(CircleGameObj pt, RectGameObj rect) (pt.Y < rect.Y + rect.Length)); } - + // -------------------------------------------------------- ToRadians double ToRadians(double angle) { return angle * (Math.PI / 180.0); } diff --git a/39_Golf/csharp/README.md b/39_Golf/csharp/README.md index 126658a1b..c632babb7 100644 --- a/39_Golf/csharp/README.md +++ b/39_Golf/csharp/README.md @@ -2,14 +2,9 @@ Original source downloaded [from Vintage Basic](http://www.vintage-basic.net/gam Conversion to [Microsoft C#](https://docs.microsoft.com/en-us/dotnet/csharp/) -There are 2 compiled executables in the compiled/ directory (windows and linux) that you can play right away! +There are 2 compiled executables in the compiled/ directory (windows and linux) that you can play right away! -Program.cs contains the C# source code. +Program.cs contains the C# source code. It has been written for .NET Core 3.1 The source code is well documented. - - - - - diff --git a/39_Golf/javascript/golf.js b/39_Golf/javascript/golf.js index 814d589e3..660c95ba4 100644 --- a/39_Golf/javascript/golf.js +++ b/39_Golf/javascript/golf.js @@ -12,10 +12,10 @@ function input() { var input_element; var input_str; - + return new Promise(function (resolve) { input_element = document.createElement("INPUT"); - + print("? "); input_element.setAttribute("type", "text"); input_element.setAttribute("length", "50"); @@ -198,7 +198,7 @@ async function main() show_obstacle(); } } - + while (1) { if (a != 1) { print("SELECTION OF CLUBS\n"); diff --git a/40_Gomoko/java/Gomoko.java b/40_Gomoko/java/Gomoko.java index 64ad7c748..75600b2a5 100644 --- a/40_Gomoko/java/Gomoko.java +++ b/40_Gomoko/java/Gomoko.java @@ -208,4 +208,3 @@ public String toString() { } } - diff --git a/40_Gomoko/javascript/gomoko.js b/40_Gomoko/javascript/gomoko.js index 662feabbf..7d57c64ef 100644 --- a/40_Gomoko/javascript/gomoko.js +++ b/40_Gomoko/javascript/gomoko.js @@ -12,10 +12,10 @@ function input() { var input_element; var input_str; - + return new Promise(function (resolve) { input_element = document.createElement("INPUT"); - + print("? "); input_element.setAttribute("type", "text"); input_element.setAttribute("length", "50"); diff --git a/40_Gomoko/perl/gomoko.pl b/40_Gomoko/perl/gomoko.pl index 9bd2f3db3..891e4e186 100644 --- a/40_Gomoko/perl/gomoko.pl +++ b/40_Gomoko/perl/gomoko.pl @@ -112,10 +112,8 @@ sub ValidMove { if ($Board[$X][$Y]!=0) { if ($Val==1) { print "SQUARE OCCUPIED. TRY AGAIN...\n"; } return 0; - } + } #$Board[$X][$Y]= $Val; return 1; } - - diff --git a/40_Gomoko/python/Gomoko.py b/40_Gomoko/python/Gomoko.py index 3ab1ca131..8216a98da 100644 --- a/40_Gomoko/python/Gomoko.py +++ b/40_Gomoko/python/Gomoko.py @@ -2,7 +2,7 @@ def print_n_whitespaces(n: int): - print(" "*n, end="") + print(" " * n, end="") def print_board(): @@ -79,21 +79,21 @@ def check_move(_I, _J, _N) -> bool: # 910 elif check_move(I, J, N) == False: print("ILLEGAL MOVE. TRY AGAIN...") else: - if A[I-1][J-1] != 0: + if A[I - 1][J - 1] != 0: print("SQUARE OCCUPIED. TRY AGAIN...") else: - A[I-1][J-1] = 1 + A[I - 1][J - 1] = 1 # COMPUTER TRIES AN INTELLIGENT MOVE SkipEFLoop = False for E in range(-1, 2): for F in range(-1, 2): - if E+F-E*F == 0 or SkipEFLoop: + if E + F - E * F == 0 or SkipEFLoop: continue X = I + F Y = J + F if check_move(X, Y, N) == False: continue - if A[X-1][Y-1] == 1: + if A[X - 1][Y - 1] == 1: SkipEFLoop = True X = I - E Y = J - F @@ -101,21 +101,21 @@ def check_move(_I, _J, _N) -> bool: # 910 while True: # 610 X = random.randint(1, N) Y = random.randint(1, N) - if check_move(X, Y, N) and A[X-1][Y-1] == 0: - A[X-1][Y-1] = 2 + if check_move(X, Y, N) and A[X - 1][Y - 1] == 0: + A[X - 1][Y - 1] = 2 print_board() break else: - if A[X-1][Y-1] != 0: + if A[X - 1][Y - 1] != 0: while True: X = random.randint(1, N) Y = random.randint(1, N) - if check_move(X, Y, N) and A[X-1][Y-1] == 0: - A[X-1][Y-1] = 2 + if check_move(X, Y, N) and A[X - 1][Y - 1] == 0: + A[X - 1][Y - 1] = 2 print_board() break else: - A[X-1][Y-1] = 2 + A[X - 1][Y - 1] = 2 print_board() print() print("THANKS FOR THE GAME!!") diff --git a/41_Guess/javascript/guess.js b/41_Guess/javascript/guess.js index e313169cd..a9e25edbf 100644 --- a/41_Guess/javascript/guess.js +++ b/41_Guess/javascript/guess.js @@ -12,10 +12,10 @@ function input() { var input_element; var input_str; - + return new Promise(function (resolve) { input_element = document.createElement("INPUT"); - + print("? "); input_element.setAttribute("type", "text"); input_element.setAttribute("length", "50"); @@ -61,7 +61,7 @@ async function main() print("OF A NUMBER BETWEEN 1 AND ANY LIMIT YOU WANT.\n"); print("THEN YOU HAVE TO GUESS WHAT IT IS.\n"); print("\n"); - + print("WHAT LIMIT DO YOU WANT"); l = parseInt(await input()); print("\n"); diff --git a/41_Guess/perl/guess.pl b/41_Guess/perl/guess.pl index f16a3e843..0aac6c523 100755 --- a/41_Guess/perl/guess.pl +++ b/41_Guess/perl/guess.pl @@ -48,5 +48,3 @@ sub ENTERS { #GOSUB 70 } return; } - - diff --git a/41_Guess/python/guess.py b/41_Guess/python/guess.py index 98cde9b7d..d70ecffb7 100644 --- a/41_Guess/python/guess.py +++ b/41_Guess/python/guess.py @@ -62,7 +62,7 @@ def limit_set(): won = False my_guess = int(limit * random() + 1) - print("I'm thinking of a number between 1 and {}".format(limit)) + print(f"I'm thinking of a number between 1 and {limit}") print("Now you try to guess what it is.") while still_guessing: @@ -79,7 +79,7 @@ def limit_set(): print("Too high. Try a smaller answer") guess_count += 1 else: - print("That's it! You got it in {} tries".format(guess_count)) + print(f"That's it! You got it in {guess_count} tries") won = True still_guessing = False @@ -89,7 +89,7 @@ def limit_set(): elif guess_count == limit_goal: print("Good.") else: - print("You should have been able to get it in only {}".format(limit_goal)) + print(f"You should have been able to get it in only {limit_goal}") insert_whitespaces() else: insert_whitespaces() diff --git a/41_Guess/rust/Cargo.toml b/41_Guess/rust/Cargo.toml index 66ea57a59..ecedf3b63 100644 --- a/41_Guess/rust/Cargo.toml +++ b/41_Guess/rust/Cargo.toml @@ -6,4 +6,4 @@ edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] -rand = "0.8.4" \ No newline at end of file +rand = "0.8.4" diff --git a/41_Guess/rust/src/main.rs b/41_Guess/rust/src/main.rs index da1750384..ad0681cb3 100644 --- a/41_Guess/rust/src/main.rs +++ b/41_Guess/rust/src/main.rs @@ -24,7 +24,7 @@ use rand::Rng; use std::io; use std::cmp::Ordering; -// Rust haven't log2 in the standard library so I added fn log_2 +// Rust haven't log2 in the standard library so I added fn log_2 const fn num_bits() -> usize { std::mem::size_of::() * 8 } fn main() { @@ -94,7 +94,7 @@ fn set_limit() -> i64 { if inp >= 2 { inp - } + } else { set_limit() } diff --git a/42_Gunner/csharp/Program.cs b/42_Gunner/csharp/Program.cs index f93c57d5b..c9e458829 100644 --- a/42_Gunner/csharp/Program.cs +++ b/42_Gunner/csharp/Program.cs @@ -5,7 +5,7 @@ class Program static void Main(string[] args) { PrintIntro(); - + string keepPlaying = "Y"; while (keepPlaying == "Y") { @@ -43,7 +43,7 @@ static void PlayGame() Console.WriteLine($"TOTAL ROUNDS EXPENDED WERE:{totalAttempts}"); if (amountOfGames < 4) { - Console.WriteLine("THE FORWARD OBSERVER HAS SIGHTED MORE ENEMY ACTIVITY..."); + Console.WriteLine("THE FORWARD OBSERVER HAS SIGHTED MORE ENEMY ACTIVITY..."); } else { if (totalAttempts > 18) { PrintReturnToBase(); @@ -111,7 +111,7 @@ static int GetElevation() return elevation; } - static void PrintIntro() + static void PrintIntro() { Console.WriteLine(new String(' ', 30) + "GUNNER"); Console.WriteLine(new String(' ', 15) + "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY" + Environment.NewLine + Environment.NewLine + Environment.NewLine); diff --git a/42_Gunner/javascript/gunner.js b/42_Gunner/javascript/gunner.js index 64a427a15..892617dea 100644 --- a/42_Gunner/javascript/gunner.js +++ b/42_Gunner/javascript/gunner.js @@ -12,10 +12,10 @@ function input() { var input_element; var input_str; - + return new Promise(function (resolve) { input_element = document.createElement("INPUT"); - + print("? "); input_element.setAttribute("type", "text"); input_element.setAttribute("length", "50"); @@ -67,7 +67,7 @@ async function main() s = 0; print("DISTANCE TO THE TARGET IS " + t + " YARDS.\n"); print("\n"); - + while (1) { print("\n"); print("ELEVATION"); diff --git a/42_Gunner/python/gunner.py b/42_Gunner/python/gunner.py index e12c0e56d..735283253 100644 --- a/42_Gunner/python/gunner.py +++ b/42_Gunner/python/gunner.py @@ -15,7 +15,7 @@ def gunner(): S1 = 0 while True: - T = int(R * (.1 + .8 * random())) + T = int(R * (0.1 + 0.8 * random())) S = 0 print("\nDISTANCE TO THE TARGET IS", T, "YARDS.") @@ -39,8 +39,10 @@ def gunner(): X = T - I E = int(X) - if (abs(E) < 100): - print("*** TARGET DESTROYED *** ", S, "ROUNDS OF AMMUNITION EXPENDED.") + if abs(E) < 100: + print( + "*** TARGET DESTROYED *** ", S, "ROUNDS OF AMMUNITION EXPENDED." + ) S1 += S if Z == 4: print("\n\nTOTAL ROUNDS EXPENDED WERE: ", S1) @@ -52,7 +54,9 @@ def gunner(): return else: Z += 1 - print("\nTHE FORWARD OBSERVER HAS SIGHTED MORE ENEMY ACTIVITY...") + print( + "\nTHE FORWARD OBSERVER HAS SIGHTED MORE ENEMY ACTIVITY..." + ) break else: if E > 100: @@ -80,6 +84,6 @@ def gunner(): gunner() Y = input("TRY AGAIN (Y OR N)? ") - if (Y != "Y"): + if Y != "Y": print("\nOK. RETURN TO BASE CAMP.") break diff --git a/43_Hammurabi/javascript/hammurabi.js b/43_Hammurabi/javascript/hammurabi.js index 285753c75..6d878db97 100644 --- a/43_Hammurabi/javascript/hammurabi.js +++ b/43_Hammurabi/javascript/hammurabi.js @@ -12,10 +12,10 @@ function input() { var input_element; var input_str; - + return new Promise(function (resolve) { input_element = document.createElement("INPUT"); - + print("? "); input_element.setAttribute("type", "text"); input_element.setAttribute("length", "50"); @@ -49,7 +49,7 @@ function exceeded_grain() { print("HAMURABI: THINK AGAIN. YOU HAVE ONLY\n"); print(s + " BUSHELS OF GRAIN. NOW THEN,\n"); - + } function exceeded_acres() @@ -68,7 +68,7 @@ async function main() print("TRY YOUR HAND AT GOVERNING ANCIENT SUMERIA\n"); print("FOR A TEN-YEAR TERM OF OFFICE.\n"); print("\n"); - + d1 = 0; p1 = 0; z = 0; diff --git a/43_Hammurabi/python/hamurabi.py b/43_Hammurabi/python/hamurabi.py index e7310fc73..c658acfba 100644 --- a/43_Hammurabi/python/hamurabi.py +++ b/43_Hammurabi/python/hamurabi.py @@ -1,5 +1,4 @@ -from random import random -from random import seed +from random import random, seed def gen_random(): @@ -36,12 +35,12 @@ def b_input(promptstring): # emulate BASIC input. It rejects non-numeric values seed() title = "HAMURABI" -title = title.rjust(32, ' ') +title = title.rjust(32, " ") print(title) attribution = "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY" attribution = attribution.rjust(15, " ") print(attribution) -print('\n\n\n') +print("\n\n\n") print("TRY YOUR HAND AT GOVERNING ANCIENT SUMERIA") print("FOR A TEN-YEAR TERM OF OFFICE.\n") @@ -164,11 +163,11 @@ def b_input(promptstring): # emulate BASIC input. It rejects non-numeric values C = int(Q / 20) # REM *** HORROS, A 15% CHANCE OF PLAGUE # yeah, should be HORRORS, but left it - Q = int(10 * (2 * random() - .3)) + Q = int(10 * (2 * random() - 0.3)) if P >= C and Z != 99: # if there are some people without full bellies... # REM *** STARVE ENOUGH FOR IMPEACHMENT? D = P - C - if D > .45 * P: + if D > 0.45 * P: print("\nYOU STARVED", D, "PEOPLE IN ONE YEAR!!!") national_fink() Z = 99 # exit the loop @@ -191,13 +190,13 @@ def b_input(promptstring): # emulate BASIC input. It rejects non-numeric values print("FRANKLY, HATE YOUR GUTS!!") elif P1 > 3 or L < 10: print("YOUR PERFORMANCE COULD HAVE BEEN SOMEWHAT BETTER, BUT") - print("REALLY WASN'T TOO BAD AT ALL. ", int(P * .8 * random()), "PEOPLE") + print("REALLY WASN'T TOO BAD AT ALL. ", int(P * 0.8 * random()), "PEOPLE") print("WOULD DEARLY LIKE TO SEE YOU ASSASSINATED BUT WE ALL HAVE OUR") print("TRIVIAL PROBLEMS.") else: print("A FANTASTIC PERFORMANCE!!! CHARLEMANGE, DISRAELI, AND") print("JEFFERSON COMBINED COULD NOT HAVE DONE BETTER!\n") for N in range(1, 10): - print('\a') + print("\a") print("\nSO LONG FOR NOW.\n") diff --git a/44_Hangman/csharp/Graphic.cs b/44_Hangman/csharp/Graphic.cs index ba01fcac7..62eea111f 100644 --- a/44_Hangman/csharp/Graphic.cs +++ b/44_Hangman/csharp/Graphic.cs @@ -108,22 +108,22 @@ public void AddRightHand() { _graphic[2, 2] = '/'; } - + public void AddLeftHand() { _graphic[2, 10] = '\\'; } - + public void AddRightFoot() { _graphic[11, 9] = '\\'; _graphic[11, 10] = '-'; } - + public void AddLeftFoot() { _graphic[11, 3] = '/'; _graphic[11, 2] = '-'; } } -} \ No newline at end of file +} diff --git a/44_Hangman/csharp/Program.cs b/44_Hangman/csharp/Program.cs index 7ecb09df9..f5658daef 100644 --- a/44_Hangman/csharp/Program.cs +++ b/44_Hangman/csharp/Program.cs @@ -44,7 +44,7 @@ static void MainLoop() words.Remove(word); GameLoop(word); - + // Game finished. Ask if player wants another one. Console.WriteLine("WANT ANOTHER WORD? "); var response = Console.ReadLine(); @@ -106,7 +106,7 @@ static void GameLoop(string word) if (displayedWord.Contains('-')) { Console.WriteLine(displayedWord); - + // Give the player a chance to guess the whole word. var wordGuess = GetWordFromPlayer(); if (word == wordGuess) @@ -161,7 +161,7 @@ private static char GetLetterFromPlayer(char[] displayedWord, List usedLet Console.WriteLine("WHAT IS YOUR GUESS?"); var guess = char.ToUpper(Console.ReadKey().KeyChar); Console.WriteLine(); - + if (usedLetters.Contains(guess)) { // After this the loop will continue. @@ -244,7 +244,7 @@ private static void DrawBody(Graphic graphic, int wrongGuesses) } graphic.Print(); } - + ///

/// Get a list of words to use in the game. /// @@ -310,4 +310,4 @@ private static void DrawBody(Graphic graphic, int wrongGuesses) /// The result string. private static string Tab(int length) => new string(' ', length); } -} \ No newline at end of file +} diff --git a/44_Hangman/java/Hangman.java b/44_Hangman/java/Hangman.java index 629ea52fa..994255671 100644 --- a/44_Hangman/java/Hangman.java +++ b/44_Hangman/java/Hangman.java @@ -54,7 +54,7 @@ public static void main(String[] args) { System.out.print("\nWANT ANOTHER WORD? "); } final String anotherWordChoice = scan.next(); - + if (anotherWordChoice.toUpperCase().equals("YES") || anotherWordChoice.toUpperCase().equals("Y")) { continueGame = true; } diff --git a/44_Hangman/javascript/hangman.js b/44_Hangman/javascript/hangman.js index 322fd94f0..c7f6b8c5c 100644 --- a/44_Hangman/javascript/hangman.js +++ b/44_Hangman/javascript/hangman.js @@ -12,10 +12,10 @@ function input() { var input_element; var input_str; - + return new Promise(function (resolve) { input_element = document.createElement("INPUT"); - + print("? "); input_element.setAttribute("type", "text"); input_element.setAttribute("length", "50"); diff --git a/44_Hangman/perl/hangman.pl b/44_Hangman/perl/hangman.pl index 45a6da9bc..3fa83ca4c 100755 --- a/44_Hangman/perl/hangman.pl +++ b/44_Hangman/perl/hangman.pl @@ -175,7 +175,7 @@ sub addchar { } if ($hangCount == 7) { print "Now we put up a hand.\n"; - addchar(2,10,"\\"); + addchar(2,10,"\\"); } if ($hangCount == 8) { print "Next the other hand.\n"; @@ -188,7 +188,7 @@ sub addchar { } if ($hangCount == 10) { print "Here's the other foot -- you're hung!!\n"; - addchar(11,2,"-"); + addchar(11,2,"-"); addchar(11,3, "/"); } @@ -208,7 +208,7 @@ sub addchar { } # PLAY block # This block is reached either by the player winning (see the "next PLAY") -# statement) or by the user losing (as the PLAY block is complete and +# statement) or by the user losing (as the PLAY block is complete and # execution naturally comes to this continue block). continue { print "Want another word ? "; diff --git a/44_Hangman/python/hangman.py b/44_Hangman/python/hangman.py index e883bf015..c5521d1e7 100755 --- a/44_Hangman/python/hangman.py +++ b/44_Hangman/python/hangman.py @@ -7,7 +7,7 @@ class Canvas: - """ For drawing text-based figures """ + """For drawing text-based figures""" def __init__(self, width=12, height=12, fill=" "): self._buffer = [] @@ -26,7 +26,7 @@ def clear(self, fill=" "): def render(self): lines = [] - for line in self._buffer: + for line in self._buffer: # Joining by the empty string ("") smooshes all of the # individual characters together as one line. lines.append("".join(line)) @@ -114,19 +114,62 @@ def draw_right_foot(canvas): ("Now we put up a hand.", draw_left_hand), ("Next the other hand.", draw_right_hand), ("Now we draw one foot", draw_left_foot), - ("Here's the other foot -- you're hung!!", draw_right_foot) + ("Here's the other foot -- you're hung!!", draw_right_foot), ) -words = ["GUM", "SIN", "FOR", "CRY", "LUG", "BYE", "FLY", - "UGLY", "EACH", "FROM", "WORK", "TALK", "WITH", "SELF", - "PIZZA", "THING", "FEIGN", "FIEND", "ELBOW", "FAULT", "DIRTY", - "BUDGET", "SPIRIT", "QUAINT", "MAIDEN", "ESCORT", "PICKAX", - "EXAMPLE", "TENSION", "QUININE", "KIDNEY", "REPLICA", "SLEEPER", - "TRIANGLE", "KANGAROO", "MAHOGANY", "SERGEANT", "SEQUENCE", - "MOUSTACHE", "DANGEROUS", "SCIENTIST", "DIFFERENT", "QUIESCENT", - "MAGISTRATE", "ERRONEOUSLY", "LOUDSPEAKER", "PHYTOTOXIC", - "MATRIMONIAL", "PARASYMPATHOMIMETIC", "THIGMOTROPISM"] +words = [ + "GUM", + "SIN", + "FOR", + "CRY", + "LUG", + "BYE", + "FLY", + "UGLY", + "EACH", + "FROM", + "WORK", + "TALK", + "WITH", + "SELF", + "PIZZA", + "THING", + "FEIGN", + "FIEND", + "ELBOW", + "FAULT", + "DIRTY", + "BUDGET", + "SPIRIT", + "QUAINT", + "MAIDEN", + "ESCORT", + "PICKAX", + "EXAMPLE", + "TENSION", + "QUININE", + "KIDNEY", + "REPLICA", + "SLEEPER", + "TRIANGLE", + "KANGAROO", + "MAHOGANY", + "SERGEANT", + "SEQUENCE", + "MOUSTACHE", + "DANGEROUS", + "SCIENTIST", + "DIFFERENT", + "QUIESCENT", + "MAGISTRATE", + "ERRONEOUSLY", + "LOUDSPEAKER", + "PHYTOTOXIC", + "MATRIMONIAL", + "PARASYMPATHOMIMETIC", + "THIGMOTROPISM", +] def play_game(guess_target): @@ -158,7 +201,9 @@ def play_game(guess_target): guess_list.append(guess_letter) guess_count += 1 if guess_letter in guess_target: - indices = [i for i, letter in enumerate(guess_target) if letter == guess_letter] + indices = [ + i for i, letter in enumerate(guess_target) if letter == guess_letter + ] for i in indices: guess_progress[i] = guess_letter if guess_progress == guess_target: @@ -207,11 +252,12 @@ def main(): print("You did all the words!!") keep_playing = False else: - keep_playing = input("Want another word? (yes or no) ").lower().startswith("y") + keep_playing = ( + input("Want another word? (yes or no) ").lower().startswith("y") + ) print("It's been fun! Bye for now.") if __name__ == "__main__": main() - diff --git a/45_Hello/java/Hello.java b/45_Hello/java/Hello.java index 7807a2ddb..bb9d701b7 100644 --- a/45_Hello/java/Hello.java +++ b/45_Hello/java/Hello.java @@ -8,47 +8,47 @@ *

* Note: The idea was to create a version of the 1970's BASIC game in Java, without introducing * new features - no additional text, error checking, etc has been added. - * + * * Converted from BASIC to Java by Darren Cardenas. */ public class Hello { - + private static final int MONEY_WAIT_MS = 3000; - - private final boolean goodEnding = false; - + + private final boolean goodEnding = false; + private final Scanner scan; // For user input public Hello() { - + scan = new Scanner(System.in); - - } // End of constructor Hello - + + } // End of constructor Hello + public void play() { - + showIntro(); startGame(); - - } // End of method play - + + } // End of method play + private static void showIntro() { - + System.out.println(" ".repeat(32) + "HELLO"); System.out.println(" ".repeat(14) + "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY"); System.out.println("\n\n"); - - } // End of method showIntro - + + } // End of method showIntro + private void startGame() { - + boolean moreProblems = true; - + String userCategory = ""; String userName = ""; String userResponse = ""; - + // Name question System.out.println("HELLO. MY NAME IS CREATIVE COMPUTER.\n\n"); System.out.print("WHAT'S YOUR NAME? "); @@ -56,49 +56,49 @@ private void startGame() { System.out.println(""); // Enjoyment question - System.out.print("HI THERE, " + userName + ", ARE YOU ENJOYING YOURSELF HERE? "); - + System.out.print("HI THERE, " + userName + ", ARE YOU ENJOYING YOURSELF HERE? "); + while (true) { userResponse = scan.nextLine(); System.out.println(""); - + if (userResponse.toUpperCase().equals("YES")) { System.out.println("I'M GLAD TO HEAR THAT, " + userName + ".\n"); break; - } + } else if (userResponse.toUpperCase().equals("NO")) { System.out.println("OH, I'M SORRY TO HEAR THAT, " + userName + ". MAYBE WE CAN"); - System.out.println("BRIGHTEN UP YOUR VISIT A BIT."); + System.out.println("BRIGHTEN UP YOUR VISIT A BIT."); break; } else { System.out.println(userName + ", I DON'T UNDERSTAND YOUR ANSWER OF '" + userResponse + "'."); - System.out.print("PLEASE ANSWER 'YES' OR 'NO'. DO YOU LIKE IT HERE? "); + System.out.print("PLEASE ANSWER 'YES' OR 'NO'. DO YOU LIKE IT HERE? "); } } // Category question System.out.println(""); - System.out.println("SAY, " + userName + ", I CAN SOLVE ALL KINDS OF PROBLEMS EXCEPT"); + System.out.println("SAY, " + userName + ", I CAN SOLVE ALL KINDS OF PROBLEMS EXCEPT"); System.out.println("THOSE DEALING WITH GREECE. WHAT KIND OF PROBLEMS DO"); - System.out.print("YOU HAVE (ANSWER SEX, HEALTH, MONEY, OR JOB)? "); - + System.out.print("YOU HAVE (ANSWER SEX, HEALTH, MONEY, OR JOB)? "); + while (moreProblems) { userCategory = scan.nextLine(); System.out.println(""); // Sex advice - if (userCategory.toUpperCase().equals("SEX")) { - System.out.print("IS YOUR PROBLEM TOO MUCH OR TOO LITTLE? "); + if (userCategory.toUpperCase().equals("SEX")) { + System.out.print("IS YOUR PROBLEM TOO MUCH OR TOO LITTLE? "); userResponse = scan.nextLine(); System.out.println(""); - - while (true) { + + while (true) { if (userResponse.toUpperCase().equals("TOO MUCH")) { System.out.println("YOU CALL THAT A PROBLEM?!! I SHOULD HAVE SUCH PROBLEMS!"); System.out.println("IF IT BOTHERS YOU, " + userName + ", TAKE A COLD SHOWER."); break; - } + } else if (userResponse.toUpperCase().equals("TOO LITTLE")) { System.out.println("WHY ARE YOU HERE IN SUFFERN, " + userName + "? YOU SHOULD BE"); System.out.println("IN TOKYO OR NEW YORK OR AMSTERDAM OR SOMEPLACE WITH SOME"); @@ -109,29 +109,29 @@ else if (userResponse.toUpperCase().equals("TOO LITTLE")) { System.out.println("DON'T GET ALL SHOOK, " + userName + ", JUST ANSWER THE QUESTION"); System.out.print("WITH 'TOO MUCH' OR 'TOO LITTLE'. WHICH IS IT? "); userResponse = scan.nextLine(); - } - } - } + } + } + } // Health advice else if (userCategory.toUpperCase().equals("HEALTH")) { System.out.println("MY ADVICE TO YOU " + userName + " IS:"); - System.out.println(" 1. TAKE TWO ASPRIN"); + System.out.println(" 1. TAKE TWO ASPRIN"); System.out.println(" 2. DRINK PLENTY OF FLUIDS (ORANGE JUICE, NOT BEER!)"); System.out.println(" 3. GO TO BED (ALONE)"); } // Money advice else if (userCategory.toUpperCase().equals("MONEY")) { System.out.println("SORRY, " + userName + ", I'M BROKE TOO. WHY DON'T YOU SELL"); - System.out.println("ENCYCLOPEADIAS OR MARRY SOMEONE RICH OR STOP EATING"); + System.out.println("ENCYCLOPEADIAS OR MARRY SOMEONE RICH OR STOP EATING"); System.out.println("SO YOU WON'T NEED SO MUCH MONEY?"); - } + } // Job advice else if (userCategory.toUpperCase().equals("JOB")) { System.out.println("I CAN SYMPATHIZE WITH YOU " + userName + ". I HAVE TO WORK"); - System.out.println("VERY LONG HOURS FOR NO PAY -- AND SOME OF MY BOSSES"); + System.out.println("VERY LONG HOURS FOR NO PAY -- AND SOME OF MY BOSSES"); System.out.println("REALLY BEAT ON MY KEYBOARD. MY ADVICE TO YOU, " + userName + ","); System.out.println("IS TO OPEN A RETAIL COMPUTER STORE. IT'S GREAT FUN."); - } + } else { System.out.println("OH, " + userName + ", YOUR ANSWER OF " + userCategory + " IS GREEK TO ME."); } @@ -139,50 +139,50 @@ else if (userCategory.toUpperCase().equals("JOB")) { // More problems question while (true) { System.out.println(""); - System.out.print("ANY MORE PROBLEMS YOU WANT SOLVED, " + userName + "? "); + System.out.print("ANY MORE PROBLEMS YOU WANT SOLVED, " + userName + "? "); userResponse = scan.nextLine(); - System.out.println(""); - + System.out.println(""); + if (userResponse.toUpperCase().equals("YES")) { System.out.print("WHAT KIND (SEX, MONEY, HEALTH, JOB)? "); break; - } + } else if (userResponse.toUpperCase().equals("NO")) { moreProblems = false; break; } else { System.out.println("JUST A SIMPLE 'YES' OR 'NO' PLEASE, " + userName + "."); - } - } - } - + } + } + } + // Payment question System.out.println(""); System.out.println("THAT WILL BE $5.00 FOR THE ADVICE, " + userName + "."); System.out.println("PLEASE LEAVE THE MONEY ON THE TERMINAL."); - // Pause - try { - Thread.sleep(MONEY_WAIT_MS); - } catch (Exception e) { - System.out.println("Caught Exception: " + e.getMessage()); + // Pause + try { + Thread.sleep(MONEY_WAIT_MS); + } catch (Exception e) { + System.out.println("Caught Exception: " + e.getMessage()); } - + System.out.println("\n\n"); - + while (true) { System.out.print("DID YOU LEAVE THE MONEY? "); userResponse = scan.nextLine(); - System.out.println(""); - + System.out.println(""); + if (userResponse.toUpperCase().equals("YES")) { System.out.println("HEY, " + userName + "??? YOU LEFT NO MONEY AT ALL!"); System.out.println("YOU ARE CHEATING ME OUT OF MY HARD-EARNED LIVING."); System.out.println(""); System.out.println("WHAT A RIP OFF, " + userName + "!!!\n"); break; - } + } else if (userResponse.toUpperCase().equals("NO")) { System.out.println("THAT'S HONEST, " + userName + ", BUT HOW DO YOU EXPECT"); System.out.println("ME TO GO ON WITH MY PSYCHOLOGY STUDIES IF MY PATIENTS"); @@ -192,25 +192,25 @@ else if (userResponse.toUpperCase().equals("NO")) { else { System.out.println("YOUR ANSWER OF '" + userResponse + "' CONFUSES ME, " + userName + "."); System.out.println("PLEASE RESPOND WITH 'YES' OR 'NO'."); - } - } - + } + } + // Legacy included unreachable code if (goodEnding) { - System.out.println("NICE MEETING YOU, " + userName + ", HAVE A NICE DAY."); + System.out.println("NICE MEETING YOU, " + userName + ", HAVE A NICE DAY."); } else { System.out.println(""); - System.out.println("TAKE A WALK, " + userName + ".\n"); + System.out.println("TAKE A WALK, " + userName + ".\n"); } - - } // End of method startGame - + + } // End of method startGame + public static void main(String[] args) { - + Hello hello = new Hello(); hello.play(); - + } // End of method main - + } // End of class Hello diff --git a/45_Hello/javascript/hello.js b/45_Hello/javascript/hello.js index d79b15f8e..ff72fd841 100644 --- a/45_Hello/javascript/hello.js +++ b/45_Hello/javascript/hello.js @@ -12,10 +12,10 @@ function input() { var input_element; var input_str; - + return new Promise(function (resolve) { input_element = document.createElement("INPUT"); - + print("? "); input_element.setAttribute("type", "text"); input_element.setAttribute("length", "50"); diff --git a/46_Hexapawn/javascript/hexapawn.js b/46_Hexapawn/javascript/hexapawn.js index 6e36428cb..4a4e3397c 100644 --- a/46_Hexapawn/javascript/hexapawn.js +++ b/46_Hexapawn/javascript/hexapawn.js @@ -12,10 +12,10 @@ function input() { var input_element; var input_str; - + return new Promise(function (resolve) { input_element = document.createElement("INPUT"); - + print("? "); input_element.setAttribute("type", "text"); input_element.setAttribute("length", "50"); @@ -199,12 +199,12 @@ async function main() print("ILLEGAL CO-ORDINATES.\n"); } } - + // Move player's pawn s[m1] = 0; s[m2] = 1; show_board(); - + // Find computer pawns for (i = 1; i <= 9; i++) { if (s[i] == -1) @@ -313,7 +313,7 @@ async function main() if (s[i - 2] == -1 || s[i - 4] == -1) break; } - + } if (i > 9) { print("YOU CAN'T MOVE, SO "); diff --git a/47_Hi-Lo/csharp/Program.cs b/47_Hi-Lo/csharp/Program.cs index c5cfb3ec3..24971be0b 100644 --- a/47_Hi-Lo/csharp/Program.cs +++ b/47_Hi-Lo/csharp/Program.cs @@ -80,4 +80,3 @@ static int ReadInt(string question) Console.WriteLine("!Invalid Number Entered."); } } - diff --git a/47_Hi-Lo/java/src/HiLo.java b/47_Hi-Lo/java/src/HiLo.java index 2d0263e9b..b7b3e106f 100644 --- a/47_Hi-Lo/java/src/HiLo.java +++ b/47_Hi-Lo/java/src/HiLo.java @@ -211,4 +211,4 @@ private int randomNumber() { return (int) (Math.random() * (HIGH_NUMBER_RANGE - LOW_NUMBER_RANGE + 1) + LOW_NUMBER_RANGE); } -} \ No newline at end of file +} diff --git a/47_Hi-Lo/javascript/hi-lo.js b/47_Hi-Lo/javascript/hi-lo.js index fc7b1dbf3..362e40a3f 100644 --- a/47_Hi-Lo/javascript/hi-lo.js +++ b/47_Hi-Lo/javascript/hi-lo.js @@ -12,10 +12,10 @@ function input() { var input_element; var input_str; - + return new Promise(function (resolve) { input_element = document.createElement("INPUT"); - + print("? "); input_element.setAttribute("type", "text"); input_element.setAttribute("length", "50"); diff --git a/47_Hi-Lo/kotlin/HiLo.kt b/47_Hi-Lo/kotlin/HiLo.kt index 7c4b6b65f..de52f573a 100644 --- a/47_Hi-Lo/kotlin/HiLo.kt +++ b/47_Hi-Lo/kotlin/HiLo.kt @@ -6,7 +6,7 @@ fun main() { winnings += playGame() println("YOUR TOTAL WINNINGS ARE NOW $winnings DOLLARS") } while(playAgain()) - + println("SO LONG. HOPE YOU ENJOYED YOURSELF!!!") } @@ -37,14 +37,14 @@ fun playAgain():Boolean { val introText = """ HI LO CREATIVE COMPUTING MORRISTOWN, NEW JERSEY - - + + THIS IS THE GAME OF HI LO. - + YOU WILL HAVE 6 TRIES TO GUESS THE AMOUNT OF MONEY IN THE HI LO JACKPOT, WHICH IS BETWEEN 1 AND 100 DOLLARS. IF YOU GUESS THE AMOUNT, YOU WIN ALL THE MONEY IN THE JACKPOT! THEN YOU GET ANOTHER CHANCE TO WIN MORE MONEY. HOWEVER, IF YOU DO NOT GUESS THE AMOUNT, THE GAME ENDS -""".trimIndent() \ No newline at end of file +""".trimIndent() diff --git a/47_Hi-Lo/perl/hi-lo.pl b/47_Hi-Lo/perl/hi-lo.pl index 08173a56c..234c59816 100755 --- a/47_Hi-Lo/perl/hi-lo.pl +++ b/47_Hi-Lo/perl/hi-lo.pl @@ -25,7 +25,7 @@ } else { print "YOUR GUESS IS TOO LOW.\n"; } - print "\n"; + print "\n"; } if ($A==$Y) { @@ -41,5 +41,3 @@ } until (uc($A) ne "YES"); print "\n"; print "SO LONG. HOPE YOU ENJOYED YOURSELF!!!\n"; exit; - - diff --git a/47_Hi-Lo/python/hilo.py b/47_Hi-Lo/python/hilo.py index 370999a78..6341311a5 100755 --- a/47_Hi-Lo/python/hilo.py +++ b/47_Hi-Lo/python/hilo.py @@ -2,17 +2,18 @@ import random MAX_ATTEMPTS = 6 -QUESTION_PROMPT='? ' +QUESTION_PROMPT = "? " + def play(): - print('HI LO') - print('CREATIVE COMPUTING MORRISTOWN, NEW JERSEY\n\n\n') - print('THIS IS THE GAME OF HI LO.\n') - print('YOU WILL HAVE 6 TRIES TO GUESS THE AMOUNT OF MONEY IN THE') - print('HI LO JACKPOT, WHICH IS BETWEEN 1 AND 100 DOLLARS. IF YOU') - print('GUESS THE AMOUNT, YOU WIN ALL THE MONEY IN THE JACKPOT!') - print('THEN YOU GET ANOTHER CHANCE TO WIN MORE MONEY. HOWEVER,') - print('IF YOU DO NOT GUESS THE AMOUNT, THE GAME ENDS.\n\n') + print("HI LO") + print("CREATIVE COMPUTING MORRISTOWN, NEW JERSEY\n\n\n") + print("THIS IS THE GAME OF HI LO.\n") + print("YOU WILL HAVE 6 TRIES TO GUESS THE AMOUNT OF MONEY IN THE") + print("HI LO JACKPOT, WHICH IS BETWEEN 1 AND 100 DOLLARS. IF YOU") + print("GUESS THE AMOUNT, YOU WIN ALL THE MONEY IN THE JACKPOT!") + print("THEN YOU GET ANOTHER CHANCE TO WIN MORE MONEY. HOWEVER,") + print("IF YOU DO NOT GUESS THE AMOUNT, THE GAME ENDS.\n\n") total_winnings = 0 while True: @@ -21,31 +22,32 @@ def play(): guessed_correctly = False for attempt in range(MAX_ATTEMPTS): - print('YOUR GUESS', end=QUESTION_PROMPT) + print("YOUR GUESS", end=QUESTION_PROMPT) guess = int(input()) if guess == secret: - print('GOT IT!!!!!!!!!! YOU WIN {} DOLLARS.'.format(secret)) + print(f"GOT IT!!!!!!!!!! YOU WIN {secret} DOLLARS.") guessed_correctly = True break elif guess > secret: - print('YOUR GUESS IS TOO HIGH.') + print("YOUR GUESS IS TOO HIGH.") else: - print('YOUR GUESS IS TOO LOW.') + print("YOUR GUESS IS TOO LOW.") if guessed_correctly: total_winnings += secret - print('YOUR TOTAL WINNINGS ARE NOW {} DOLLARS.'.format(total_winnings)) + print(f"YOUR TOTAL WINNINGS ARE NOW {total_winnings} DOLLARS.") else: - print('YOU BLEW IT...TOO BAD...THE NUMBER WAS {}'.format(secret)) + print(f"YOU BLEW IT...TOO BAD...THE NUMBER WAS {secret}") - print('\n') - print('PLAY AGAIN (YES OR NO)', end=QUESTION_PROMPT) + print("\n") + print("PLAY AGAIN (YES OR NO)", end=QUESTION_PROMPT) answer = input().upper() - if answer != 'YES': + if answer != "YES": break - print('\nSO LONG. HOPE YOU ENJOYED YOURSELF!!!') + print("\nSO LONG. HOPE YOU ENJOYED YOURSELF!!!") + -if __name__ == '__main__': +if __name__ == "__main__": play() diff --git a/48_High_IQ/d/highiq.d b/48_High_IQ/d/highiq.d index 784455452..f6016bcf4 100644 --- a/48_High_IQ/d/highiq.d +++ b/48_High_IQ/d/highiq.d @@ -63,7 +63,7 @@ struct Board (" 6_ │ │ │ │ ").to!(dchar[]), (" ├───┼───┼───┤ ").to!(dchar[]), (" 7_ │ │ │ │ ").to!(dchar[]), - (" └───┴───┴───┘ ").to!(dchar[])]; + (" └───┴───┴───┘ ").to!(dchar[])]; foreach (y, row; state) foreach (x, field; row) if (field == taken) diff --git a/48_High_IQ/javascript/highiq.js b/48_High_IQ/javascript/highiq.js index 3dbb6aa15..e3b4f1b0f 100644 --- a/48_High_IQ/javascript/highiq.js +++ b/48_High_IQ/javascript/highiq.js @@ -12,10 +12,10 @@ function input() { var input_element; var input_str; - + return new Promise(function (resolve) { input_element = document.createElement("INPUT"); - + print("? "); input_element.setAttribute("type", "text"); input_element.setAttribute("length", "50"); diff --git a/48_High_IQ/python/High_IQ.py b/48_High_IQ/python/High_IQ.py index 4e14ddc13..66d1879c2 100644 --- a/48_High_IQ/python/High_IQ.py +++ b/48_High_IQ/python/High_IQ.py @@ -1,15 +1,48 @@ - def new_board(): # Using a dictionary in python to store the board, since we are not including all numbers within a given range. board = {} - for i in [13, 14, 15, 22, 23, 24, 29, 30, 31, 32, 33, 34, 35, 38, 39, 40, 42, 43, 44, 47, 48, 49, 50, 51, 52, 53, 58, 59, 60, 67, 68, 69]: - board[i] = '!' - board[41] = 'O' + for i in [ + 13, + 14, + 15, + 22, + 23, + 24, + 29, + 30, + 31, + 32, + 33, + 34, + 35, + 38, + 39, + 40, + 42, + 43, + 44, + 47, + 48, + 49, + 50, + 51, + 52, + 53, + 58, + 59, + 60, + 67, + 68, + 69, + ]: + board[i] = "!" + board[41] = "O" return board def print_instructions(): - print(""" + print( + """ HERE IS THE BOARD: ! ! ! @@ -36,18 +69,45 @@ def print_instructions(): TO SAVE TYPING TIME, A COMPRESSED VERSION OF THE GAME BOARD WILL BE USED DURING PLAY. REFER TO THE ABOVE ONE FOR PEG NUMBERS. OK, LET'S BEGIN. - """) + """ + ) + def print_board(board): """Prints the boards using indexes in the passed parameter""" print(" " * 2 + board[13] + board[14] + board[15]) print(" " * 2 + board[22] + board[23] + board[24]) - print(board[29] + board[30] + board[31] + board[32] + board[33] + board[34] + board[35]) - print(board[38] + board[39] + board[40] + board[41] + board[42] + board[43] + board[44]) - print(board[47] + board[48] + board[49] + board[50] + board[51] + board[52] + board[53]) + print( + board[29] + + board[30] + + board[31] + + board[32] + + board[33] + + board[34] + + board[35] + ) + print( + board[38] + + board[39] + + board[40] + + board[41] + + board[42] + + board[43] + + board[44] + ) + print( + board[47] + + board[48] + + board[49] + + board[50] + + board[51] + + board[52] + + board[53] + ) print(" " * 2 + board[58] + board[59] + board[60]) print(" " * 2 + board[67] + board[68] + board[69]) + def play_game(): # Create new board board = new_board() @@ -57,51 +117,56 @@ def play_game(): print_board(board) while not move(board): print("ILLEGAL MOVE! TRY AGAIN") - + # Check peg count and print the user's score peg_count = 0 for key in board.keys(): - if board[key] == '!': + if board[key] == "!": peg_count += 1 - + print("YOU HAD " + str(peg_count) + " PEGS REMAINING") - + if peg_count == 1: print("BRAVO! YOU MADE A PERFECT SCORE!") print("SAVE THIS PAPER AS A RECORD OF YOUR ACCOMPLISHMENT!") - + + def move(board): """Queries the user to move. Returns false if the user puts in an invalid input or move, returns true if the move was successful""" start_input = input("MOVE WHICH PIECE? ") - + if not start_input.isdigit(): return False - + start = int(start_input) - if start not in board or board[start] != '!': + if start not in board or board[start] != "!": return False - + end_input = input("TO WHERE? ") if not end_input.isdigit(): return False - + end = int(end_input) - if end not in board or board[end] != 'O': + if end not in board or board[end] != "O": return False - + difference = abs(start - end) center = (end + start) / 2 - if (difference == 2 or difference == 18) and board[end] == 'O' and board[center] == '!': - board[start] = 'O' - board[center] = 'O' - board[end] = '!' + if ( + (difference == 2 or difference == 18) + and board[end] == "O" + and board[center] == "!" + ): + board[start] = "O" + board[center] = "O" + board[end] = "!" return True else: return False - + def main(): print(" " * 33 + "H-I-Q") @@ -109,15 +174,20 @@ def main(): print_instructions() play_game() + def is_game_finished(board): # Checks all locations and whether or not a move is possible at that location. for pos in board.keys(): - if board[pos] == '!': - for space in [1,9]: + if board[pos] == "!": + for space in [1, 9]: # Checks if the next location has a peg - nextToPeg = ((pos + space) in board) and board[pos + space] == '!' + nextToPeg = ((pos + space) in board) and board[pos + space] == "!" # Checks both going forward (+ location) or backwards (-location) - hasMovableSpace = (not ((pos - space) in board and board[pos - space] == '!')) or (not ((pos + space * 2) in board and board[pos + space * 2] == '!')) + hasMovableSpace = ( + not ((pos - space) in board and board[pos - space] == "!") + ) or ( + not ((pos + space * 2) in board and board[pos + space * 2] == "!") + ) if nextToPeg and hasMovableSpace: return False return True diff --git a/48_High_IQ/python/README.md b/48_High_IQ/python/README.md index a0738c90b..bc04457a6 100644 --- a/48_High_IQ/python/README.md +++ b/48_High_IQ/python/README.md @@ -2,4 +2,4 @@ Original source downloaded [from Vintage Basic](http://www.vintage-basic.net/gam Conversion to [Python](https://www.python.org/about/) -[Implementation](./High_IQ.py) by [Thomas Kwashnak](https://github.com/LittleTealeaf) \ No newline at end of file +[Implementation](./High_IQ.py) by [Thomas Kwashnak](https://github.com/LittleTealeaf) diff --git a/49_Hockey/hockey.bas b/49_Hockey/hockey.bas index 626b4f561..f0b5a8298 100644 --- a/49_Hockey/hockey.bas +++ b/49_Hockey/hockey.bas @@ -8,37 +8,37 @@ 55 PRINT 60 IF C$="NO" THEN 90 65 IF C$="YES" THEN 80 -70 PRINT "ANSWER YES OR NO!!":GOTO 50 +70 PRINT "ANSWER YES OR NO!!":GOTO 50 80 GOTO 1720 90 DIM A$(7),B$(7),H(20),T(5),T1(5),T2(5),T3(5) -100 PRINT "ENTER THE TWO TEAMS";:INPUT A$(7),B$(7) +100 PRINT "ENTER THE TWO TEAMS";:INPUT A$(7),B$(7) 105 PRINT 110 PRINT "ENTER THE NUMBER OF MINUTES IN A GAME";:INPUT T6 115 PRINT -120 IF T6<1 THEN 110:PRINT -130 PRINT "WOULD THE " A$(7) " COACH ENTER HIS TEAM" +120 IF T6<1 THEN 110:PRINT +130 PRINT "WOULD THE " A$(7) " COACH ENTER HIS TEAM" 135 PRINT -140 FOR I=1 TO 6:PRINT "PLAYER"I;:INPUT A$(I):NEXT I:PRINT +140 FOR I=1 TO 6:PRINT "PLAYER"I;:INPUT A$(I):NEXT I:PRINT 150 PRINT "WOULD THE " B$(7) " COACH DO THE SAME" 155 PRINT -160 FOR T=1 TO 6:PRINT "PLAYER"T;:INPUT B$(T):NEXT T:PRINT -170 PRINT "INPUT THE REFEREE FOR THIS GAME";:INPUT R$ -180 PRINT:PRINT TAB(10);A$(7) " STARTING LINEUP" -190 FOR T=1 TO 6:PRINT A$(T):NEXT T +160 FOR T=1 TO 6:PRINT "PLAYER"T;:INPUT B$(T):NEXT T:PRINT +170 PRINT "INPUT THE REFEREE FOR THIS GAME";:INPUT R$ +180 PRINT:PRINT TAB(10);A$(7) " STARTING LINEUP" +190 FOR T=1 TO 6:PRINT A$(T):NEXT T 200 PRINT:PRINT TAB(10);B$(7)" STARTING LINEUP" 210 FOR T=1 TO 6:PRINT B$(T):NEXT T:PRINT 220 PRINT "WE'RE READY FOR TONIGHTS OPENING FACE-OFF." 230 PRINT R$ " WILL DROP THE PUCK BETWEEN " A$(2) " AND " B$(2) 240 FOR L=1 TO T6:IF L=1 THEN 260 -250 PRINT "AND WE'RE READY FOR THE FACE-OFF" +250 PRINT "AND WE'RE READY FOR THE FACE-OFF" 260 C=INT(2*RND(X))+1:ON C GOTO 270,280 270 PRINT A$(7) " HAS CONTROL OF THE PUCK":GOTO 290 -280 PRINT B$(7) " HAS CONTROL." -290 PRINT "PASS";:INPUT P:FOR N=1 TO 3:H(N)=0:NEXT N +280 PRINT B$(7) " HAS CONTROL." +290 PRINT "PASS";:INPUT P:FOR N=1 TO 3:H(N)=0:NEXT N 300 IF P<0 THEN 290 305 IF P>3 THEN 290 -310 FOR J=1 TO (P+2) -320 H(J)=INT(5*RND(X))+1 +310 FOR J=1 TO (P+2) +320 H(J)=INT(5*RND(X))+1 330 NEXT J:IF H(J-1)=H(J-2) THEN 310 331 IF P+2<3 THEN 350 335 IF H(J-1)=H(J-3) THEN 310 @@ -48,19 +48,19 @@ 360 INPUT "SHOT";S:IF S<1 THEN 360 365 IF S>4 THEN 360 370 ON C GOTO 380,480 -380 PRINT A$(H(J-1));:G=H(J-1):G1=0:G2=0 +380 PRINT A$(H(J-1));:G=H(J-1):G1=0:G2=0 390 ON S GOTO 400,420,440,460 -400 PRINT " LET'S A BOOMER GO FROM THE RED LINE!!" +400 PRINT " LET'S A BOOMER GO FROM THE RED LINE!!" 410 Z=10:GOTO 890 420 PRINT " FLIPS A WRISTSHOT DOWN THE ICE" -440 PRINT " BACKHANDS ONE IN ON THE GOALTENDER" +440 PRINT " BACKHANDS ONE IN ON THE GOALTENDER" 450 Z=25:GOTO 890 460 PRINT " SNAPS A LONG FLIP SHOT" 470 Z=17:GOTO 890 480 PRINT B$(H(J-1));:G1=0:G2=0:G=H(J-1):GOTO 390 490 ON C GOTO 500,640 500 ON P GOTO 510,540,570 -510 PRINT A$(H(J-2)) " LEADS " A$(H(J-1)) " WITH A PERFECT PASS." +510 PRINT A$(H(J-2)) " LEADS " A$(H(J-1)) " WITH A PERFECT PASS." 520 PRINT A$(H(J-1)) " CUTTING IN!!!" 530 G=H(J-1):G1=H(J-2):G2=0:Z1=3:GOTO 770 540 PRINT A$(H(J-2)) " GIVES TO A STREAKING " A$(H(J-1)) @@ -74,56 +74,56 @@ 620 PRINT A$(H(J-1)) " DROPS IT TO " A$(H(J-4)) 630 G=H(J-4):G1=H(J-1):G2=H(J-2):Z1=1:GOTO 770 640 ON P GOTO 650,670,720 -650 PRINT B$(H(J-1)) " HITS " B$(H(J-2)) " FLYING DOWN THE LEFT SIDE" +650 PRINT B$(H(J-1)) " HITS " B$(H(J-2)) " FLYING DOWN THE LEFT SIDE" 660 G=H(J-2):G1=H(J-1):G2=0:Z1=3:GOTO 770 670 PRINT "IT'S A ' 3 ON 2 '!" 680 PRINT "ONLY " A$(4) " AND " A$(5) " ARE BACK." 690 PRINT B$(H(J-2)) " GIVES OFF TO " B$(H(J-1)) 700 PRINT B$(H(J-1)) " DROPS TO " B$(H(J-3)) -710 G=H(J-3):G1=H(J-1):G2=H(J-2):Z1=2:GOTO 770 -720 PRINT " A ' 3 ON 2 ' WITH A ' TRAILER '!" -730 PRINT B$(H(J-4)) " GIVES TO " B$(H(J-2)) " WHO SHUFFLES IT OFF TO" +710 G=H(J-3):G1=H(J-1):G2=H(J-2):Z1=2:GOTO 770 +720 PRINT " A ' 3 ON 2 ' WITH A ' TRAILER '!" +730 PRINT B$(H(J-4)) " GIVES TO " B$(H(J-2)) " WHO SHUFFLES IT OFF TO" 740 PRINT B$(H(J-1)) " WHO FIRES A WING TO WING PASS TO " -750 PRINT B$(H(J-3)) " AS HE CUTS IN ALONE!!" -760 G=H(J-3):G1=H(J-1):G2=H(J-2):Z1=1:GOTO 770 +750 PRINT B$(H(J-3)) " AS HE CUTS IN ALONE!!" +760 G=H(J-3):G1=H(J-1):G2=H(J-2):Z1=1:GOTO 770 770 PRINT "SHOT";:INPUT S:IF S>4 THEN 770:IF S<1 THEN 770 780 ON C GOTO 790,880 -790 PRINT A$(G);:ON S GOTO 800,820,840,860 -800 PRINT " LET'S A BIG SLAP SHOT GO!!" +790 PRINT A$(G);:ON S GOTO 800,820,840,860 +800 PRINT " LET'S A BIG SLAP SHOT GO!!" 810 Z=4:Z=Z+Z1:GOTO 890 -820 PRINT " RIPS A WRIST SHOT OFF" +820 PRINT " RIPS A WRIST SHOT OFF" 830 Z=2:Z=Z+Z1:GOTO 890 -840 PRINT " GETS A BACKHAND OFF" +840 PRINT " GETS A BACKHAND OFF" 850 Z=3:Z=Z+Z1:GOTO 890 -860 PRINT " SNAPS OFF A SNAP SHOT" +860 PRINT " SNAPS OFF A SNAP SHOT" 870 Z=2:Z=Z+Z1:GOTO 890 -880 PRINT B$(G);:ON S GOTO 800,820,840,860 +880 PRINT B$(G);:ON S GOTO 800,820,840,860 890 PRINT "AREA";:INPUT A:IF A<1 THEN 890 895 IF A>4 THEN 890 900 ON C GOTO 910,920 -910 S2=S2+1:GOTO 930 +910 S2=S2+1:GOTO 930 920 S3=S3+1 930 A1=INT(4*RND(X))+1:IF A<>A1 THEN 1200 940 H(20)=INT(100*RND(X))+1 950 IF INT(H(20)/Z)=H(20)/Z THEN 1160 960 ON C GOTO 970,980 -970 PRINT "GOAL " A$(7):H(9)=H(9)+1:GOTO 990 -980 PRINT "SCORE " B$(7):H(8)=H(8)+1 +970 PRINT "GOAL " A$(7):H(9)=H(9)+1:GOTO 990 +980 PRINT "SCORE " B$(7):H(8)=H(8)+1 990 FOR B1=1 TO 25:PRINT CHR$(7);:NEXT B1:PRINT 1000 PRINT "SCORE: ";:IF H(8)>H(9) THEN 1020 1010 PRINT A$(7)":";H(9),B$(7)":";H(8):GOTO 1030 -1020 PRINT B$(7)":";H(8),A$(7)":";H(9) +1020 PRINT B$(7)":";H(8),A$(7)":";H(9) 1030 ON C GOTO 1040,1100 1040 PRINT "GOAL SCORED BY: " A$(G):IF G1=0 THEN 1070 1050 IF G2=0 THEN 1080 -1060 PRINT " ASSISTED BY: " A$(G1) " AND " A$(G2):GOTO 1090 +1060 PRINT " ASSISTED BY: " A$(G1) " AND " A$(G2):GOTO 1090 1070 PRINT " UNASSISTED.":GOTO 1090 1080 PRINT " ASSISTED BY: " A$(G1) 1090 T(G)=T(G)+1:T1(G1)=T1(G1)+1:T1(G2)=T1(G2)+1:GOTO 1540 1100 PRINT "GOAL SCORED BY: " B$(G); 1110 IF G1=0 THEN 1130 1115 IF G2=0 THEN 1140 -1120 PRINT " ASSISTED BY: " B$(G1) " AND " B$(G2):GOTO 1150 +1120 PRINT " ASSISTED BY: " B$(G1) " AND " B$(G2):GOTO 1150 1130 PRINT " UNASSISTED":GOTO 1150 1140 PRINT " ASSISTED BY: " B$(G1):GOTO 1150 1150 T2(G)=T2(G)+1:T3(G1)=T3(G1)+1:T3(G2)=T3(G2)+1:GOTO 1540 @@ -132,39 +132,39 @@ 1170 ON C GOTO 1180,1190 1180 PRINT "SAVE " B$(6) " -- REBOUND":GOTO 940 1190 PRINT "SAVE " A$(6) " -- FOLLOW UP":GOTO 940 -1200 S1=INT(6*RND(X))+1 +1200 S1=INT(6*RND(X))+1 1210 ON C GOTO 1220,1380 -1220 ON S1 GOTO 1230,1260,1290,1300,1330,1350 +1220 ON S1 GOTO 1230,1260,1290,1300,1330,1350 1230 PRINT "KICK SAVE AND A BEAUTY BY " B$(6) 1240 PRINT "CLEARED OUT BY " B$(3) -1250 GOTO 260 +1250 GOTO 260 1260 PRINT "WHAT A SPECTACULAR GLOVE SAVE BY " B$(6) 1270 PRINT "AND " B$(6) " GOLFS IT INTO THE CROWD" 1280 GOTO 1540 -1290 PRINT "SKATE SAVE ON A LOW STEAMER BY " B$(6):GOTO 260 -1300 PRINT "PAD SAVE BY " B$(6) " OFF THE STICK" +1290 PRINT "SKATE SAVE ON A LOW STEAMER BY " B$(6):GOTO 260 +1300 PRINT "PAD SAVE BY " B$(6) " OFF THE STICK" 1310 PRINT "OF "A$(G) " AND " B$(6) " COVERS UP" 1320 GOTO 1540 -1330 PRINT "WHISTLES ONE OVER THE HEAD OF " B$(6) -1340 GOTO 260 +1330 PRINT "WHISTLES ONE OVER THE HEAD OF " B$(6) +1340 GOTO 260 1350 PRINT B$(6) " MAKES A FACE SAVE!! AND HE IS HURT" -1360 PRINT "THE DEFENSEMAN " B$(5) " COVERS UP FOR HIM" +1360 PRINT "THE DEFENSEMAN " B$(5) " COVERS UP FOR HIM" 1370 GOTO 1540 -1380 ON S1 GOTO 1390,1410,1440,1470,1490,1520 -1390 PRINT "STICK SAVE BY " A$(6) -1400 PRINT "AND CLEARED OUT BY " A$(4):GOTO 260 -1410 PRINT "OH MY GOD!! " B$(G) " RATTLES ONE OFF THE POST" -1420 PRINT "TO THE RIGHT OF " A$(6) " AND " A$(6) " COVERS "; -1430 PRINT "ON THE LOOSE PUCK!":GOTO 1540 +1380 ON S1 GOTO 1390,1410,1440,1470,1490,1520 +1390 PRINT "STICK SAVE BY " A$(6) +1400 PRINT "AND CLEARED OUT BY " A$(4):GOTO 260 +1410 PRINT "OH MY GOD!! " B$(G) " RATTLES ONE OFF THE POST" +1420 PRINT "TO THE RIGHT OF " A$(6) " AND " A$(6) " COVERS "; +1430 PRINT "ON THE LOOSE PUCK!":GOTO 1540 1440 PRINT "SKATE SAVE BY " A$(6) -1450 PRINT A$(6) " WHACKS THE LOOSE PUCK INTO THE STANDS" +1450 PRINT A$(6) " WHACKS THE LOOSE PUCK INTO THE STANDS" 1460 GOTO 1540 -1470 PRINT "STICK SAVE BY " A$(6) " AND HE CLEARS IT OUT HIMSELF" -1480 GOTO 260 -1490 PRINT "KICKED OUT BY " A$(6) -1500 PRINT "AND IT REBOUNDS ALL THE WAY TO CENTER ICE" -1510 GOTO 260 -1520 PRINT "GLOVE SAVE " A$(6) " AND HE HANGS ON" +1470 PRINT "STICK SAVE BY " A$(6) " AND HE CLEARS IT OUT HIMSELF" +1480 GOTO 260 +1490 PRINT "KICKED OUT BY " A$(6) +1500 PRINT "AND IT REBOUNDS ALL THE WAY TO CENTER ICE" +1510 GOTO 260 +1520 PRINT "GLOVE SAVE " A$(6) " AND HE HANGS ON" 1530 GOTO 1540 1540 NEXT L:FOR N=1 TO 30:PRINT CHR$(7);:NEXT N:PRINT "THAT'S THE SIREN" 1550 PRINT:PRINT TAB(15);"FINAL SCORE:" @@ -175,14 +175,14 @@ 1600 PRINT TAB(25);A$(7) 1610 PRINT TAB(5);"NAME";TAB(20);"GOALS";TAB(35);"ASSISTS" 1620 PRINT TAB(5);"----";TAB(20);"-----";TAB(35);"-------" -1630 FOR I=1 TO 5:PRINT TAB(5);A$(I);TAB(21);T(I);TAB(36);T1(I) -1640 NEXT I:PRINT +1630 FOR I=1 TO 5:PRINT TAB(5);A$(I);TAB(21);T(I);TAB(36);T1(I) +1640 NEXT I:PRINT 1650 PRINT TAB(25);B$(7) -1660 PRINT TAB(5);"NAME";TAB(20);"GOALS";TAB(35);"ASSISTS" +1660 PRINT TAB(5);"NAME";TAB(20);"GOALS";TAB(35);"ASSISTS" 1670 PRINT TAB(5);"----";TAB(20);"-----";TAB(35);"-------" 1680 FOR T=1 TO 5:PRINT TAB(5);B$(T);TAB(21);T2(T);TAB(36);T3(T) -1690 NEXT T:PRINT -1700 PRINT "SHOTS ON NET":PRINT A$(7)":";S2:PRINT B$(7)":";S3 +1690 NEXT T:PRINT +1700 PRINT "SHOTS ON NET":PRINT A$(7)":";S2:PRINT B$(7)":";S3 1710 END 1720 PRINT: PRINT "THIS IS A SIMULATED HOCKEY GAME." 1730 PRINT "QUESTION RESPONSE" diff --git a/49_Hockey/javascript/hockey.js b/49_Hockey/javascript/hockey.js index 16d5f19e2..d58a56a97 100644 --- a/49_Hockey/javascript/hockey.js +++ b/49_Hockey/javascript/hockey.js @@ -12,10 +12,10 @@ function input() { var input_element; var input_str; - + return new Promise(function (resolve) { input_element = document.createElement("INPUT"); - + print("? "); input_element.setAttribute("type", "text"); input_element.setAttribute("length", "50"); @@ -154,7 +154,7 @@ async function main() else print(bs[7] + " HAS CONTROL.\n"); do { - + print("PASS"); p = parseInt(await input()); for (n = 1; n <= 3; n++) diff --git a/50_Horserace/javascript/horserace.js b/50_Horserace/javascript/horserace.js index 882e66e69..39e12b0fd 100644 --- a/50_Horserace/javascript/horserace.js +++ b/50_Horserace/javascript/horserace.js @@ -12,10 +12,10 @@ function input() { var input_element; var input_str; - + return new Promise(function (resolve) { input_element = document.createElement("INPUT"); - + print("? "); input_element.setAttribute("type", "text"); input_element.setAttribute("length", "50"); diff --git a/50_Horserace/python/horserace.py b/50_Horserace/python/horserace.py index cf7c266e6..ab989dd9e 100644 --- a/50_Horserace/python/horserace.py +++ b/50_Horserace/python/horserace.py @@ -1,7 +1,8 @@ -import random import math +import random import time + def basic_print(*zones, **kwargs): """Simulates the PRINT command from BASIC to some degree. Supports `printing zones` if given multiple arguments.""" @@ -10,7 +11,7 @@ def basic_print(*zones, **kwargs): if len(zones) == 1: line = str(zones[0]) else: - line = "".join(["{:<14}".format(str(zone)) for zone in zones]) + line = "".join([f"{str(zone):<14}" for zone in zones]) identation = kwargs.get("indent", 0) end = kwargs.get("end", "\n") print(" " * identation + line, end=end) @@ -40,7 +41,7 @@ def basic_input(prompt, type_conversion=None): "JOLLY", "HORSE", "JELLY DO NOT", - "MIDNIGHT" + "MIDNIGHT", ] @@ -88,7 +89,7 @@ def setup_horses(): # rounding odds to two decimals for nicer output, # this is not in the origin implementation - return [round(total/odd, 2) for odd in odds] + return [round(total / odd, 2) for odd in odds] def print_horse_odds(odds): @@ -117,7 +118,7 @@ def get_bets(player_names): basic_print(" YOU CAN'T DO THAT!") amount = None bets.append((horse, amount)) - + basic_print("") return bets @@ -127,7 +128,7 @@ def get_distance(odd): """Advances a horse during one step of the racing simulation. The amount travelled is random, but scaled by the odds of the horse""" - d = random.randrange(1,100) + d = random.randrange(1, 100) s = math.ceil(odd) if d < 10: return 1 @@ -160,7 +161,7 @@ def print_race_state(total_distance, race_pos): # race_pos is stored by last to first horse in the race. # we get the next horse we need to print out next_pos = next(race_pos_iter) - + # start line basic_print("XXXXSTARTXXXX") @@ -195,7 +196,7 @@ def simulate_race(odds): # e.g. race_pos[0] => last horse # race_pos[-1] => winning horse race_pos = list(range(num_horses)) - + basic_print("\n1 2 3 4 5 6 7 8") while True: @@ -205,14 +206,14 @@ def simulate_race(odds): total_distance[i] += get_distance(odds[i]) # bubble sort race_pos based on total distance travelled - # in the original implementation, race_pos is reset for each + # in the original implementation, race_pos is reset for each # simulation step, so we keep this behaviour here race_pos = list(range(num_horses)) for l in range(num_horses): - for i in range(num_horses-1-l): - if total_distance[race_pos[i]] < total_distance[race_pos[i+1]]: + for i in range(num_horses - 1 - l): + if total_distance[race_pos[i]] < total_distance[race_pos[i + 1]]: continue - race_pos[i], race_pos[i+1] = race_pos[i+1], race_pos[i] + race_pos[i], race_pos[i + 1] = race_pos[i + 1], race_pos[i] # print current state of the race print_race_state(total_distance, race_pos) @@ -221,7 +222,7 @@ def simulate_race(odds): # check if the winning horse is already over the finish line if total_distance[race_pos[-1]] >= 28: return race_pos - + # this was not in the original BASIC implementation, but it makes the # race visualization a nice animation (if the terminal size is set to 31 rows) time.sleep(1) @@ -246,7 +247,7 @@ def print_race_results(race_positions, odds, bets, player_names): if horse == winning_horse_idx: basic_print("") basic_print(f"{name} WINS ${amount * odds[winning_horse_idx]}") - + def main_loop(player_names, horse_odds): """Main game loop""" @@ -272,7 +273,7 @@ def main(): # main loop of the game, the player can play multiple races, with the # same odds main_loop(player_names, horse_odds) - + if __name__ == "__main__": - main() \ No newline at end of file + main() diff --git a/51_Hurkle/csharp/.gitignore b/51_Hurkle/csharp/.gitignore index d417b1866..468a39766 100644 --- a/51_Hurkle/csharp/.gitignore +++ b/51_Hurkle/csharp/.gitignore @@ -357,4 +357,4 @@ MigrationBackup/ # Ionide (cross platform F# VS Code tools) working folder .ionide/ -# End of https://www.toptal.com/developers/gitignore/api/csharp \ No newline at end of file +# End of https://www.toptal.com/developers/gitignore/api/csharp diff --git a/51_Hurkle/csharp/CardinalDirection.cs b/51_Hurkle/csharp/CardinalDirection.cs index 969c9b2b1..324edbd29 100644 --- a/51_Hurkle/csharp/CardinalDirection.cs +++ b/51_Hurkle/csharp/CardinalDirection.cs @@ -12,4 +12,4 @@ internal enum CardinalDirection West, NorthWest } -} \ No newline at end of file +} diff --git a/51_Hurkle/csharp/ConsoleHurkleView.cs b/51_Hurkle/csharp/ConsoleHurkleView.cs index 40366ad27..b587d12ce 100644 --- a/51_Hurkle/csharp/ConsoleHurkleView.cs +++ b/51_Hurkle/csharp/ConsoleHurkleView.cs @@ -64,4 +64,4 @@ public void ShowVictory(VictoryViewModel victoryViewModel) Console.WriteLine($"YOU FOUND HIM IN {victoryViewModel.CurrentGuessNumber} GUESSES!"); } } -} \ No newline at end of file +} diff --git a/51_Hurkle/csharp/FailedGuessViewModel.cs b/51_Hurkle/csharp/FailedGuessViewModel.cs index 25042dde0..541573e44 100644 --- a/51_Hurkle/csharp/FailedGuessViewModel.cs +++ b/51_Hurkle/csharp/FailedGuessViewModel.cs @@ -4,4 +4,4 @@ internal class FailedGuessViewModel { public CardinalDirection Direction { get; init; } } -} \ No newline at end of file +} diff --git a/51_Hurkle/csharp/GamePoint.cs b/51_Hurkle/csharp/GamePoint.cs index f715a41d2..7abde808c 100644 --- a/51_Hurkle/csharp/GamePoint.cs +++ b/51_Hurkle/csharp/GamePoint.cs @@ -6,7 +6,7 @@ internal class GamePoint public int Y {get;init;} public CardinalDirection GetDirectionTo(GamePoint target) - { + { if(X == target.X) { if(Y > target.Y) @@ -53,4 +53,4 @@ public CardinalDirection GetDirectionTo(GamePoint target) } } } -} \ No newline at end of file +} diff --git a/51_Hurkle/csharp/GuessViewModel.cs b/51_Hurkle/csharp/GuessViewModel.cs index b0c5227c2..fe8524a98 100644 --- a/51_Hurkle/csharp/GuessViewModel.cs +++ b/51_Hurkle/csharp/GuessViewModel.cs @@ -4,4 +4,4 @@ internal class GuessViewModel { public int CurrentGuessNumber {get;init;} } -} \ No newline at end of file +} diff --git a/51_Hurkle/csharp/HurkleGame.cs b/51_Hurkle/csharp/HurkleGame.cs index 88620bbcc..438676a89 100644 --- a/51_Hurkle/csharp/HurkleGame.cs +++ b/51_Hurkle/csharp/HurkleGame.cs @@ -25,7 +25,7 @@ public void PlayGame() X = _random.Next(0, gridSize), Y = _random.Next(0, gridSize) }; - + for(var K=1;K<=guesses;K++) { var guessPoint = _view.GetGuess(new GuessViewModel{CurrentGuessNumber = K}); @@ -41,8 +41,8 @@ public void PlayGame() continue; } } - + _view.ShowLoss(new LossViewModel{MaxGuesses = guesses, HurkleLocation = hurklePoint } ); } } -} \ No newline at end of file +} diff --git a/51_Hurkle/csharp/IHurkleView.cs b/51_Hurkle/csharp/IHurkleView.cs index e5ce3a1a7..dbaf00f38 100644 --- a/51_Hurkle/csharp/IHurkleView.cs +++ b/51_Hurkle/csharp/IHurkleView.cs @@ -7,4 +7,4 @@ internal interface IHurkleView void ShowDirection(FailedGuessViewModel failedGuessViewModel); void ShowLoss(LossViewModel lossViewModel); } -} \ No newline at end of file +} diff --git a/51_Hurkle/csharp/LossViewModel.cs b/51_Hurkle/csharp/LossViewModel.cs index 2329be873..fe6eb1a9b 100644 --- a/51_Hurkle/csharp/LossViewModel.cs +++ b/51_Hurkle/csharp/LossViewModel.cs @@ -5,4 +5,4 @@ internal class LossViewModel public int MaxGuesses { get; init; } public GamePoint HurkleLocation { get; init; } } -} \ No newline at end of file +} diff --git a/51_Hurkle/csharp/Program.cs b/51_Hurkle/csharp/Program.cs index e5c3f6afb..483aa2b04 100644 --- a/51_Hurkle/csharp/Program.cs +++ b/51_Hurkle/csharp/Program.cs @@ -57,7 +57,7 @@ 280 PRINT Console.WriteLine("THANKS FOR PLAYING!"); break; } - + } } } diff --git a/51_Hurkle/csharp/VictoryViewModel.cs b/51_Hurkle/csharp/VictoryViewModel.cs index ce25311c1..f19f6f864 100644 --- a/51_Hurkle/csharp/VictoryViewModel.cs +++ b/51_Hurkle/csharp/VictoryViewModel.cs @@ -1,7 +1,7 @@ namespace hurkle { internal class VictoryViewModel - { + { public int CurrentGuessNumber {get; init;} } -} \ No newline at end of file +} diff --git a/51_Hurkle/javascript/hurkle.js b/51_Hurkle/javascript/hurkle.js index 1e3301e52..94d992a80 100644 --- a/51_Hurkle/javascript/hurkle.js +++ b/51_Hurkle/javascript/hurkle.js @@ -12,10 +12,10 @@ function input() { var input_element; var input_str; - + return new Promise(function (resolve) { input_element = document.createElement("INPUT"); - + print("? "); input_element.setAttribute("type", "text"); input_element.setAttribute("length", "50"); diff --git a/51_Hurkle/perl/hurkle.pl b/51_Hurkle/perl/hurkle.pl index 1497e50c0..aef3ee7a2 100755 --- a/51_Hurkle/perl/hurkle.pl +++ b/51_Hurkle/perl/hurkle.pl @@ -29,7 +29,7 @@ HERE # The PLAY block is a complete game from start -# to finish. The continue block prints the +# to finish. The continue block prints the # "let's play again" message and then a new # game is started. PLAY: while (1) { @@ -42,11 +42,11 @@ my($G1,$G2); # The CHECK loop will execute while we # attempt to collect valid input from - # the player + # the player CHECK: while (1) { chomp(my $in = ); - # Use a regex to attempt to parse out + # Use a regex to attempt to parse out # two integers separated by a comma. if ($in =~ m{(\d+)\s*,\s*(\d+)}) { $G1 = $1; $G2 = $2; diff --git a/51_Hurkle/python/hurkle.py b/51_Hurkle/python/hurkle.py index dfe40d8df..62cffecbf 100644 --- a/51_Hurkle/python/hurkle.py +++ b/51_Hurkle/python/hurkle.py @@ -53,7 +53,7 @@ def direction(A, B, X, Y): # read coordinates in `X, Y` format, split the string # at `,`, and then parse the coordinates to `int` and # store them in `X` and `Y` respectively. - [ X, Y ] = [int(c) for c in input("X,Y? ").split(",")] + [X, Y] = [int(c) for c in input("X,Y? ").split(",")] if abs(X - A) + abs(Y - B) == 0: print("\nYOU FOUND HIM IN", k + 1, "GUESSES!") diff --git a/52_Kinema/javascript/kinema.js b/52_Kinema/javascript/kinema.js index abd2bb1c5..91cd443ba 100644 --- a/52_Kinema/javascript/kinema.js +++ b/52_Kinema/javascript/kinema.js @@ -12,10 +12,10 @@ function input() { var input_element; var input_str; - + return new Promise(function (resolve) { input_element = document.createElement("INPUT"); - + print("? "); input_element.setAttribute("type", "text"); input_element.setAttribute("length", "50"); diff --git a/52_Kinema/python/kinema.py b/52_Kinema/python/kinema.py index e5529d683..347fff2a7 100644 --- a/52_Kinema/python/kinema.py +++ b/52_Kinema/python/kinema.py @@ -38,7 +38,7 @@ def do_quiz(): print(f"A BALL IS THROWN UPWARDS AT {v0} METERS PER SECOND.") print() - answer = v0 ** 2 / (2 * g) + answer = v0**2 / (2 * g) num_questions_correct += ask_player("HOW HIGH WILL IT GO (IN METERS)?", answer) answer = 2 * v0 / g diff --git a/53_King/README.md b/53_King/README.md index 0687224d4..c8cc45d57 100644 --- a/53_King/README.md +++ b/53_King/README.md @@ -27,7 +27,7 @@ A quick fix for this bug in the original code would be 1450 V3=ABS(INT(V1-V2)) 1451 A=INT(A+V3) - + ...judging from the description of tourist income on basic line 1410 1410 PRINT " YOU MADE";ABS(INT(V1-V2));"RALLODS FROM TOURIST TRADE." diff --git a/53_King/javascript/king.js b/53_King/javascript/king.js index faaeb253a..d8514a316 100644 --- a/53_King/javascript/king.js +++ b/53_King/javascript/king.js @@ -12,10 +12,10 @@ function input() { var input_element; var input_str; - + return new Promise(function (resolve) { input_element = document.createElement("INPUT"); - + print("? "); input_element.setAttribute("type", "text"); input_element.setAttribute("length", "50"); diff --git a/53_King/king.bas b/53_King/king.bas index e8ec834d5..7352fa588 100644 --- a/53_King/king.bas +++ b/53_King/king.bas @@ -248,7 +248,7 @@ 1969 PRINT "HOW MUCH DID YOU HAVE IN THE TREASURY"; 1970 INPUT A 1971 IF A<0 THEN 1590 -1975 PRINT "HOW MANY COUNTRYMEN"; +1975 PRINT "HOW MANY COUNTRYMEN"; 1976 INPUT B 1977 IF B<0 THEN 1590 1980 PRINT "HOW MANY WORKERS"; diff --git a/53_King/king_variable_update.bas b/53_King/king_variable_update.bas index c88edf935..7f88e1014 100644 --- a/53_King/king_variable_update.bas +++ b/53_King/king_variable_update.bas @@ -285,7 +285,7 @@ REM I think tourism calculations are actually wrong in the original code! 1969 PRINT "HOW MUCH DID YOU HAVE IN THE TREASURY"; 1970 INPUT RALLODS 1971 IF RALLODS<0 THEN 1590 -1975 PRINT "HOW MANY COUNTRYMEN"; +1975 PRINT "HOW MANY COUNTRYMEN"; 1976 INPUT COUNTRYMEN 1977 IF COUNTRYMEN<0 THEN 1590 1980 PRINT "HOW MANY WORKERS"; diff --git a/53_King/kotlin/King.kt b/53_King/kotlin/King.kt index 169cd6a0f..5947d2782 100644 --- a/53_King/kotlin/King.kt +++ b/53_King/kotlin/King.kt @@ -145,15 +145,15 @@ sealed class YearOutcome { // The misspelling of "successfully" is in the original code. println( """ - + CONGRATULATIONS!!!!!!!!!!!!!!!!!! YOU HAVE SUCCESFULLY COMPLETED YOUR $yearsRequired YEAR TERM OF OFFICE. YOU WERE, OF COURSE, EXTREMELY LUCKY, BUT NEVERTHELESS, IT'S QUITE AN ACHIEVEMENT. GOODBYE AND GOOD LUCK - YOU'LL PROBABLY NEED IT IF YOU'RE THE TYPE THAT PLAYS THIS GAME. - - + + """.trimIndent() ) } @@ -180,8 +180,8 @@ sealed class YearOutcome { override fun displayConsequences() { println( """ - - + + OVER ONE THIRD OF THE POPULTATION HAS DIED SINCE YOU WERE ELECTED TO OFFICE. THE PEOPLE (REMAINING) HATE YOUR GUTS. diff --git a/54_Letter/csharp/Program.cs b/54_Letter/csharp/Program.cs index 9a1c29dbc..63bd4a129 100644 --- a/54_Letter/csharp/Program.cs +++ b/54_Letter/csharp/Program.cs @@ -1,3 +1,3 @@ using Letter; -Game.Play(); \ No newline at end of file +Game.Play(); diff --git a/54_Letter/java/src/Letter.java b/54_Letter/java/src/Letter.java index 365828944..ffe478cf0 100644 --- a/54_Letter/java/src/Letter.java +++ b/54_Letter/java/src/Letter.java @@ -139,4 +139,4 @@ private String displayTextAndGetInput(String text) { System.out.print(text); return kbScanner.next(); } -} \ No newline at end of file +} diff --git a/54_Letter/javascript/letter.js b/54_Letter/javascript/letter.js index 7aef3de9a..9129c0756 100644 --- a/54_Letter/javascript/letter.js +++ b/54_Letter/javascript/letter.js @@ -12,10 +12,10 @@ function input() { var input_element; var input_str; - + return new Promise(function (resolve) { input_element = document.createElement("INPUT"); - + print("? "); input_element.setAttribute("type", "text"); input_element.setAttribute("length", "50"); @@ -61,7 +61,7 @@ async function main() print("\n"); print("O.K., I HAVE A LETTER. START GUESSING.\n"); while (1) { - + print("\n"); print("WHAT IS YOUR GUESS"); g++; diff --git a/54_Letter/python/letter.py b/54_Letter/python/letter.py index 845265821..d80b368a4 100644 --- a/54_Letter/python/letter.py +++ b/54_Letter/python/letter.py @@ -14,6 +14,7 @@ BELLS_ON_SUCCESS = False + def print_with_tab(space_count, msg): if space_count > 0: spaces = " " * space_count @@ -22,6 +23,7 @@ def print_with_tab(space_count, msg): print(spaces + msg) + def print_instructions(): print("LETTER GUESSING GAME") print() @@ -29,38 +31,40 @@ def print_instructions(): print("TRY TO GUESS MY LETTER AND I'LL GIVE YOU CLUES") print("AS TO HOW CLOSE YOU'RE GETTING TO MY LETTER.") + def play_game(): - target_value = random.randint(ord('A'), ord('Z')) + target_value = random.randint(ord("A"), ord("Z")) num_guesses = 0 print() print("O.K., I HAVE A LETTER. START GUESSING.") print() while True: - print("WHAT IS YOUR GUESS?") - num_guesses += 1 - guess = ord(input()) - print() - if guess == target_value: - print() - print(f"YOU GOT IT IN {num_guesses} GUESSES!!") - if num_guesses > 5: - print("BUT IT SHOULDN'T TAKE MORE THAN 5 GUESSES!") - # goto 515 - print("GOOD JOB !!!!!") - - if BELLS_ON_SUCCESS: - bellStr = chr(7) * 15 - print(bellStr) - - print() - print("LET'S PLAY AGAIN.....") - return - elif guess > target_value: - print("TOO HIGH. TRY A LOWER LETTER.") - continue - else: - print("TOO LOW. TRY A HIGHER LETTER.") - continue + print("WHAT IS YOUR GUESS?") + num_guesses += 1 + guess = ord(input()) + print() + if guess == target_value: + print() + print(f"YOU GOT IT IN {num_guesses} GUESSES!!") + if num_guesses > 5: + print("BUT IT SHOULDN'T TAKE MORE THAN 5 GUESSES!") + # goto 515 + print("GOOD JOB !!!!!") + + if BELLS_ON_SUCCESS: + bellStr = chr(7) * 15 + print(bellStr) + + print() + print("LET'S PLAY AGAIN.....") + return + elif guess > target_value: + print("TOO HIGH. TRY A LOWER LETTER.") + continue + else: + print("TOO LOW. TRY A HIGHER LETTER.") + continue + def main(): print_with_tab(33, "LETTER") @@ -74,5 +78,6 @@ def main(): while True: play_game() + if __name__ == "__main__": main() diff --git a/55_Life/csharp/Program.cs b/55_Life/csharp/Program.cs index eeb004652..0eadf0eaf 100644 --- a/55_Life/csharp/Program.cs +++ b/55_Life/csharp/Program.cs @@ -47,12 +47,12 @@ void PrintCentered(string text) Console.Write(new string(' ', spaceCount)); Console.WriteLine(text); } - + PrintCentered("LIFE"); PrintCentered("CREATIVE COMPUTING MORRISTOWN, NEW JERSEY"); Console.WriteLine(); Console.WriteLine(); - Console.WriteLine(); + Console.WriteLine(); } Simulation InitializeSimulation(Pattern pattern, Matrix matrixToInitialize) { @@ -65,7 +65,7 @@ Simulation InitializeSimulation(Pattern pattern, Matrix matrixToInitialize) { { if (pattern.Content[x][y] == ' ') continue; - + matrixToInitialize[minX + x, minY + y] = CellState.Stable; newSimulation.IncreasePopulation(); } @@ -77,7 +77,7 @@ Simulation InitializeSimulation(Pattern pattern, Matrix matrixToInitialize) { TimeSpan GetPauseBetweenIterations() { if (args.Length != 2) return TimeSpan.Zero; - + var parameter = args[0].ToLower(); if (parameter.Contains("wait")) { @@ -93,17 +93,17 @@ void ProcessSimulation() { var pauseBetweenIterations = GetPauseBetweenIterations(); var isInvalid = false; - + while (true) { var invalidText = isInvalid ? "INVALID!" : ""; Console.WriteLine($"GENERATION: {simulation.Generation}\tPOPULATION: {simulation.Population} {invalidText}"); - + simulation.StartNewGeneration(); - var nextMinX = maxHeight - 1; + var nextMinX = maxHeight - 1; var nextMinY = maxWidth - 1; - var nextMaxX = 0; + var nextMaxX = 0; var nextMaxY = 0; var matrixOutput = new StringBuilder(); @@ -114,7 +114,7 @@ void ProcessSimulation() matrixOutput.AppendLine(); } - // refreshes the matrix and updates search area + // refreshes the matrix and updates search area for (var x = minX; x <= maxX; x++) { var printedLine = Enumerable.Repeat(' ', maxWidth).ToList(); @@ -161,13 +161,13 @@ void UpdateSearchArea() const int limitX = 21; const int limitY = 67; - + if (minX < 2) { minX = 2; isInvalid = true; } - + if (maxX > limitX) { maxX = limitX; @@ -227,12 +227,12 @@ int CountNeighbors() } } - // expands search area to accommodate new cells + // expands search area to accommodate new cells minX--; minY--; maxX++; maxY++; - + if (pauseBetweenIterations > TimeSpan.Zero) Thread.Sleep(pauseBetweenIterations); } @@ -305,7 +305,7 @@ public Matrix(int height, int width) get => _matrix[x, y]; set => _matrix[x, y] = value; } - + public override string ToString() { var stringBuilder = new StringBuilder(); @@ -321,4 +321,4 @@ public override string ToString() } return stringBuilder.ToString(); } -} \ No newline at end of file +} diff --git a/55_Life/csharp/README.md b/55_Life/csharp/README.md index 5b4ffe62f..ee62b3822 100644 --- a/55_Life/csharp/README.md +++ b/55_Life/csharp/README.md @@ -10,7 +10,7 @@ This program requires you to install [.NET 6 SDK](https://dotnet.microsoft.com/e ## Know more about Conway's Game of Life -You can find more about Conway's Game of Life on this page of the [Cornell Math Explorers' Club](http://pi.math.cornell.edu/~lipa/mec/lesson6.html), alongside many examples of patterns you can try. +You can find more about Conway's Game of Life on this page of the [Cornell Math Explorers' Club](http://pi.math.cornell.edu/~lipa/mec/lesson6.html), alongside many examples of patterns you can try. ### Optional parameters diff --git a/55_Life/java/README.md b/55_Life/java/README.md index 19a5ff383..687d300e1 100644 --- a/55_Life/java/README.md +++ b/55_Life/java/README.md @@ -16,4 +16,4 @@ However, the Java code does not have much in common with the original. **Differences in behaviour:** * Input supports the ```.``` character, but it's optional. * Evaluation of ```DONE``` input string is case insensitive. -* Run with the ```-s``` command line argument to halt the program after each generation, and continue when ```ENTER``` is pressed. \ No newline at end of file +* Run with the ```-s``` command line argument to halt the program after each generation, and continue when ```ENTER``` is pressed. diff --git a/55_Life/javascript/life.js b/55_Life/javascript/life.js index 338d48d58..b4b0fe6ba 100644 --- a/55_Life/javascript/life.js +++ b/55_Life/javascript/life.js @@ -12,10 +12,10 @@ function input() { var input_element; var input_str; - + return new Promise(function (resolve) { input_element = document.createElement("INPUT"); - + print("? "); input_element.setAttribute("type", "text"); input_element.setAttribute("length", "50"); diff --git a/55_Life/perl/life.pl b/55_Life/perl/life.pl index 972cb3223..fccadc89b 100644 --- a/55_Life/perl/life.pl +++ b/55_Life/perl/life.pl @@ -91,5 +91,3 @@ $X1=$X1-1; $Y1=$Y1-1; $X2=$X2+1; $Y2=$Y2+1; goto Line210; exit; - - diff --git a/56_Life_for_Two/javascript/lifefortwo.js b/56_Life_for_Two/javascript/lifefortwo.js index a8c90e50c..a38a0af8d 100644 --- a/56_Life_for_Two/javascript/lifefortwo.js +++ b/56_Life_for_Two/javascript/lifefortwo.js @@ -12,10 +12,10 @@ function input() { var input_element; var input_str; - + return new Promise(function (resolve) { input_element = document.createElement("INPUT"); - + print("? "); input_element.setAttribute("type", "text"); input_element.setAttribute("length", "50"); diff --git a/57_Literature_Quiz/csharp/litquiz.cs b/57_Literature_Quiz/csharp/litquiz.cs index 0b9a77377..c2f07a2ae 100644 --- a/57_Literature_Quiz/csharp/litquiz.cs +++ b/57_Literature_Quiz/csharp/litquiz.cs @@ -5,7 +5,7 @@ namespace litquiz class litquiz { public static int Score = 0; - + public static void Main(string[] args) { @@ -27,7 +27,7 @@ public static void Main(string[] args) Console.WriteLine(); One(); - + } @@ -49,7 +49,7 @@ public static void One() { Console.WriteLine("SORRY...FIGARO WAS HIS NAME."); Two(); } - + } public static void Two() @@ -84,7 +84,7 @@ public static void Three() string answerThree; answerThree = Console.ReadLine(); - + if(answerThree == "4") { Console.WriteLine("YEA! YOU'RE A REAL LITERATURE GIANT."); diff --git a/57_Literature_Quiz/java/src/LiteratureQuiz.java b/57_Literature_Quiz/java/src/LiteratureQuiz.java index d98d58a88..20331b1ac 100644 --- a/57_Literature_Quiz/java/src/LiteratureQuiz.java +++ b/57_Literature_Quiz/java/src/LiteratureQuiz.java @@ -173,4 +173,4 @@ private String displayTextAndGetInput(String text) { System.out.print(text); return kbScanner.next(); } -} \ No newline at end of file +} diff --git a/57_Literature_Quiz/javascript/literature-quiz-node.mjs b/57_Literature_Quiz/javascript/literature-quiz-node.mjs index 0d38d5403..5dadd50b9 100644 --- a/57_Literature_Quiz/javascript/literature-quiz-node.mjs +++ b/57_Literature_Quiz/javascript/literature-quiz-node.mjs @@ -11,7 +11,7 @@ async function input(prompt = "") { rl.setPrompt(prompt) // show user the question rl.prompt() - // listen for user answer, + // listen for user answer, // callback is triggered as soon as user hits enter key rl.on('line', answer => { rl.close() @@ -52,12 +52,12 @@ async function main(){ println("CREATIVE COMPUTING MORRISTOWN, NEW JERSEY", "center") println();println();println() - score += await evaluateQuestion("IN PINOCCHIO, WHAT WAS THE NAME OF THE CAT?", + score += await evaluateQuestion("IN PINOCCHIO, WHAT WAS THE NAME OF THE CAT?", "1)TIGGER, 2)CICERO, 3)FIGARO, 4)GUIPETTO", 3, "VERY GOOD! HERE'S ANOTHER.", "SORRY...FIGARO WAS HIS NAME.") println() - score += await evaluateQuestion("FROM WHOSE GARDEN DID BUGS BUNNY STEAL THE CARROTS?", + score += await evaluateQuestion("FROM WHOSE GARDEN DID BUGS BUNNY STEAL THE CARROTS?", "1)MR. NIXON'S, 2)ELMER FUDD'S, 3)CLEM JUDD'S, 4)STROMBOLI'S", 2, "PRETTY GOOD!", "TOO BAD...IT WAS ELMER FUDD'S GARDEN.") println() @@ -87,4 +87,4 @@ async function main(){ } } -main() \ No newline at end of file +main() diff --git a/57_Literature_Quiz/javascript/litquiz.js b/57_Literature_Quiz/javascript/litquiz.js index f4d6a4f6e..f652cdf3b 100644 --- a/57_Literature_Quiz/javascript/litquiz.js +++ b/57_Literature_Quiz/javascript/litquiz.js @@ -12,10 +12,10 @@ function input() { var input_element; var input_str; - + return new Promise(function (resolve) { input_element = document.createElement("INPUT"); - + print("? "); input_element.setAttribute("type", "text"); input_element.setAttribute("length", "50"); diff --git a/57_Literature_Quiz/perl/litquiz.pl b/57_Literature_Quiz/perl/litquiz.pl index f7d410752..eed03506d 100755 --- a/57_Literature_Quiz/perl/litquiz.pl +++ b/57_Literature_Quiz/perl/litquiz.pl @@ -78,5 +78,3 @@ print "NOT BAD, BUT YOU MIGHT SPEND A LITTLE MORE TIME\n"; print "READING THE NURSERY GREATS.\n"; exit; - - diff --git a/58_Love/csharp/Strings/Intro.txt b/58_Love/csharp/Strings/Intro.txt index bcf1afe2a..cc10189ec 100644 --- a/58_Love/csharp/Strings/Intro.txt +++ b/58_Love/csharp/Strings/Intro.txt @@ -7,4 +7,3 @@ A tribute to the great American artist, Robert Indiana. His greatest work will be reproduced with a message of your choice up to 60 characters. If you can't think of a message, simply type the word 'LOVE' - diff --git a/58_Love/java/src/Love.java b/58_Love/java/src/Love.java index 89c1c1de6..da8385aa4 100644 --- a/58_Love/java/src/Love.java +++ b/58_Love/java/src/Love.java @@ -167,4 +167,4 @@ public static void main(String[] args) { Love love = new Love(); love.process(); } -} \ No newline at end of file +} diff --git a/58_Love/javascript/love.js b/58_Love/javascript/love.js index d67c6acbc..6a99e72fb 100644 --- a/58_Love/javascript/love.js +++ b/58_Love/javascript/love.js @@ -12,10 +12,10 @@ function input() { var input_element; var input_str; - + return new Promise(function (resolve) { input_element = document.createElement("INPUT"); - + print("? "); input_element.setAttribute("type", "text"); input_element.setAttribute("length", "50"); diff --git a/58_Love/perl/love.pl b/58_Love/perl/love.pl index 9e9f95ccd..31127e050 100755 --- a/58_Love/perl/love.pl +++ b/58_Love/perl/love.pl @@ -50,5 +50,3 @@ for (my $I=1; $I<10; $I++) { print "\n"; } exit; - - diff --git a/58_Love/python/love.py b/58_Love/python/love.py index 81c9ae2ff..4e4967d37 100644 --- a/58_Love/python/love.py +++ b/58_Love/python/love.py @@ -23,43 +23,48 @@ # Image data. Each top-level element is a row. Each row element # contains alternating character and blank run lengths. -DATA = [ [60, ], - [1, 12, 26, 9, 12], - [3, 8, 24, 17, 8], - [4, 6, 23, 21, 6], - [4, 6, 22, 12, 5, 6, 5], - [4, 6, 21, 11, 8, 6, 4], - [4, 6, 21, 10, 10, 5, 4], - [4, 6, 21, 9, 11, 5, 4], - [4, 6, 21, 8, 11, 6, 4], - [4, 6, 21, 7, 11, 7, 4], - [4, 6, 21, 6, 11, 8, 4], - [4, 6, 19, 1, 1, 5, 11, 9, 4], - [4, 6, 19, 1, 1, 5, 10, 10, 4], - [4, 6, 18, 2, 1, 6, 8, 11, 4], - [4, 6, 17, 3, 1, 7, 5, 13, 4], - [4, 6, 15, 5, 2, 23, 5], - [1, 29, 5, 17, 8], - [1, 29, 9, 9, 12], - - [1, 13, 5, 40, 1], - [1, 13, 5, 40, 1], - [4, 6, 13, 3, 10, 6, 12, 5, 1], - [5, 6, 11, 3, 11, 6, 14, 3, 1], - [5, 6, 11, 3, 11, 6, 15, 2, 1], - [6, 6, 9, 3, 12, 6, 16, 1, 1], - [6, 6, 9, 3, 12, 6, 7, 1, 10], - [7, 6, 7, 3, 13, 6, 6, 2, 10], - [7, 6, 7, 3, 13, 14, 10], - [8, 6, 5, 3, 14, 6, 6, 2, 10], - [8, 6, 5, 3, 14, 6, 7, 1, 10], - [9, 6, 3, 3, 15, 6, 16, 1, 1], - [9, 6, 3, 3, 15, 6, 15, 2, 1], - [10, 6, 1, 3, 16, 6, 14, 3, 1], - [10, 10, 16, 6, 12, 5, 1], - [11, 8, 13, 27, 1], - [11, 8, 13, 27, 1], - [60, ] ] +DATA = [ + [ + 60, + ], + [1, 12, 26, 9, 12], + [3, 8, 24, 17, 8], + [4, 6, 23, 21, 6], + [4, 6, 22, 12, 5, 6, 5], + [4, 6, 21, 11, 8, 6, 4], + [4, 6, 21, 10, 10, 5, 4], + [4, 6, 21, 9, 11, 5, 4], + [4, 6, 21, 8, 11, 6, 4], + [4, 6, 21, 7, 11, 7, 4], + [4, 6, 21, 6, 11, 8, 4], + [4, 6, 19, 1, 1, 5, 11, 9, 4], + [4, 6, 19, 1, 1, 5, 10, 10, 4], + [4, 6, 18, 2, 1, 6, 8, 11, 4], + [4, 6, 17, 3, 1, 7, 5, 13, 4], + [4, 6, 15, 5, 2, 23, 5], + [1, 29, 5, 17, 8], + [1, 29, 9, 9, 12], + [1, 13, 5, 40, 1], + [1, 13, 5, 40, 1], + [4, 6, 13, 3, 10, 6, 12, 5, 1], + [5, 6, 11, 3, 11, 6, 14, 3, 1], + [5, 6, 11, 3, 11, 6, 15, 2, 1], + [6, 6, 9, 3, 12, 6, 16, 1, 1], + [6, 6, 9, 3, 12, 6, 7, 1, 10], + [7, 6, 7, 3, 13, 6, 6, 2, 10], + [7, 6, 7, 3, 13, 14, 10], + [8, 6, 5, 3, 14, 6, 6, 2, 10], + [8, 6, 5, 3, 14, 6, 7, 1, 10], + [9, 6, 3, 3, 15, 6, 16, 1, 1], + [9, 6, 3, 3, 15, 6, 15, 2, 1], + [10, 6, 1, 3, 16, 6, 14, 3, 1], + [10, 10, 16, 6, 12, 5, 1], + [11, 8, 13, 27, 1], + [11, 8, 13, 27, 1], + [ + 60, + ], +] # Assume that the total length of the first element @@ -73,7 +78,7 @@ print("A tribute to the great American artist, Robert Indiana.") print("His great work will be reproduced with a message of") print("your choice up to 60 characters. If you can't think of") -print("a message, simple type the word 'love'\n") # (sic) +print("a message, simple type the word 'love'\n") # (sic) # Get message from user message = input("Your message, please? ") @@ -81,7 +86,7 @@ message = "LOVE" # Repeat the message until we get at least one line's worth -while(len(message) < ROW_LEN): +while len(message) < ROW_LEN: message += message # Display image @@ -89,10 +94,10 @@ for row in DATA: print_message = True position = 0 - line_text = '' + line_text = "" for length in row: if print_message: - text = message[position:(position + length)] + text = message[position : (position + length)] print_message = False else: text = " " * length @@ -100,9 +105,8 @@ line_text += text position += length print(line_text) - -print("") +print("") ###################################################################### @@ -146,10 +150,3 @@ # ((5, ), (1, 1, 2), (2, 1, 1)) # ###################################################################### - - - - - - - diff --git a/59_Lunar_LEM_Rocket/javascript/lunar.js b/59_Lunar_LEM_Rocket/javascript/lunar.js index f95d1d16d..69306aa28 100644 --- a/59_Lunar_LEM_Rocket/javascript/lunar.js +++ b/59_Lunar_LEM_Rocket/javascript/lunar.js @@ -12,10 +12,10 @@ function input() { var input_element; var input_str; - + return new Promise(function (resolve) { input_element = document.createElement("INPUT"); - + print("? "); input_element.setAttribute("type", "text"); input_element.setAttribute("length", "50"); diff --git a/59_Lunar_LEM_Rocket/lem.bas b/59_Lunar_LEM_Rocket/lem.bas index aa46895fd..eece9cc1b 100644 --- a/59_Lunar_LEM_Rocket/lem.bas +++ b/59_Lunar_LEM_Rocket/lem.bas @@ -220,7 +220,7 @@ 1085 GOTO 1100 1090 PRINT 1095 PRINT "MISSION ABENDED" -1100 PRINT +1100 PRINT 1105 PRINT "DO YOU WANT TO TRY IT AGAIN (YES/NO)?" 1110 INPUT Z$ 1115 IF Z$="YES" THEN 20 diff --git a/59_Lunar_LEM_Rocket/lunar.bas b/59_Lunar_LEM_Rocket/lunar.bas index 87cb430f8..b12037187 100644 --- a/59_Lunar_LEM_Rocket/lunar.bas +++ b/59_Lunar_LEM_Rocket/lunar.bas @@ -1,19 +1,19 @@ 10 PRINT TAB(33);"LUNAR" -20 PRINT TAB(15);"CREATIVE COMPUTING MORRISTOWN, NEW JERSEY" +20 PRINT TAB(15);"CREATIVE COMPUTING MORRISTOWN, NEW JERSEY" 25 PRINT:PRINT:PRINT -30 PRINT "THIS IS A COMPUTER SIMULATION OF AN APOLLO LUNAR" +30 PRINT "THIS IS A COMPUTER SIMULATION OF AN APOLLO LUNAR" 40 PRINT "LANDING CAPSULE.": PRINT: PRINT -50 PRINT "THE ON-BOARD COMPUTER HAS FAILED (IT WAS MADE BY" +50 PRINT "THE ON-BOARD COMPUTER HAS FAILED (IT WAS MADE BY" 60 PRINT "XEROX) SO YOU HAVE TO LAND THE CAPSULE MANUALLY." -70 PRINT: PRINT "SET BURN RATE OF RETRO ROCKETS TO ANY VALUE BETWEEN" -80 PRINT "0 (FREE FALL) AND 200 (MAXIMUM BURN) POUNDS PER SECOND." -90 PRINT "SET NEW BURN RATE EVERY 10 SECONDS.": PRINT +70 PRINT: PRINT "SET BURN RATE OF RETRO ROCKETS TO ANY VALUE BETWEEN" +80 PRINT "0 (FREE FALL) AND 200 (MAXIMUM BURN) POUNDS PER SECOND." +90 PRINT "SET NEW BURN RATE EVERY 10 SECONDS.": PRINT 100 PRINT "CAPSULE WEIGHT 32,500 LBS; FUEL WEIGHT 16,500 LBS." 110 PRINT: PRINT: PRINT: PRINT "GOOD LUCK" 120 L=0 -130 PRINT: PRINT "SEC","MI + FT","MPH","LB FUEL","BURN RATE":PRINT +130 PRINT: PRINT "SEC","MI + FT","MPH","LB FUEL","BURN RATE":PRINT 140 A=120:V=1:M=33000:N=16500:G=1E-03:Z=1.8 -150 PRINT L,INT(A);INT(5280*(A-INT(A))),3600*V,M-N,:INPUT K:T=10 +150 PRINT L,INT(A);INT(5280*(A-INT(A))),3600*V,M-N,:INPUT K:T=10 160 IF M-N<1E-03 THEN 240 170 IF T<1E-03 THEN 150 180 S=T: IF M>=N+S*K THEN 200 @@ -24,12 +24,12 @@ 230 GOSUB 330: GOTO 160 240 PRINT "FUEL OUT AT";L;"SECONDS":S=(-V+SQR(V*V+2*A*G))/G 250 V=V+G*S: L=L+S -260 W=3600*V: PRINT "ON MOON AT";L;"SECONDS - IMPACT VELOCITY";W;"MPH" -274 IF W<=1.2 THEN PRINT "PERFECT LANDING!": GOTO 440 -280 IF W<=10 THEN PRINT "GOOD LANDING (COULD BE BETTER)":GOTO 440 +260 W=3600*V: PRINT "ON MOON AT";L;"SECONDS - IMPACT VELOCITY";W;"MPH" +274 IF W<=1.2 THEN PRINT "PERFECT LANDING!": GOTO 440 +280 IF W<=10 THEN PRINT "GOOD LANDING (COULD BE BETTER)":GOTO 440 282 IF W>60 THEN 300 -284 PRINT "CRAFT DAMAGE... YOU'RE STRANDED HERE UNTIL A RESCUE" -286 PRINT "PARTY ARRIVES. HOPE YOU HAVE ENOUGH OXYGEN!" +284 PRINT "CRAFT DAMAGE... YOU'RE STRANDED HERE UNTIL A RESCUE" +286 PRINT "PARTY ARRIVES. HOPE YOU HAVE ENOUGH OXYGEN!" 288 GOTO 440 300 PRINT "SORRY THERE WERE NO SURVIVORS. YOU BLEW IT!" 310 PRINT "IN FACT, YOU BLASTED A NEW LUNAR CRATER";W*.227;"FEET DEEP!" diff --git a/59_Lunar_LEM_Rocket/python/lunar.py b/59_Lunar_LEM_Rocket/python/lunar.py index b55fc6f2c..98d8cbd86 100644 --- a/59_Lunar_LEM_Rocket/python/lunar.py +++ b/59_Lunar_LEM_Rocket/python/lunar.py @@ -9,7 +9,6 @@ import collections import math - PAGE_WIDTH = 64 COLUMN_WIDTH = 2 @@ -122,7 +121,7 @@ def show_landing(sim_clock, capsule): def show_out_of_fuel(sim_clock, capsule): print(f"FUEL OUT AT {sim_clock.elapsed_time} SECONDS") delta_t = ( - -capsule.v + math.sqrt(capsule.v ** 2 + 2 * capsule.a * capsule.g) + -capsule.v + math.sqrt(capsule.v**2 + 2 * capsule.a * capsule.g) ) / capsule.g capsule.v += capsule.g * delta_t sim_clock.advance(delta_t) @@ -186,17 +185,17 @@ def predict_motion(self, delta_t): new_velocity = ( self.v + self.g * delta_t - + self.z * (-q - q ** 2 / 2 - q ** 3 / 3 - q ** 4 / 4 - q ** 5 / 5) + + self.z * (-q - q**2 / 2 - q**3 / 3 - q**4 / 4 - q**5 / 5) ) # new altitude new_altitude = ( self.a - - self.g * delta_t ** 2 / 2 + - self.g * delta_t**2 / 2 - self.v * delta_t + self.z * delta_t - * (q / 2 + q ** 2 / 6 + q ** 3 / 12 + q ** 4 / 20 + q ** 5 / 30) + * (q / 2 + q**2 / 6 + q**3 / 12 + q**4 / 20 + q**5 / 30) ) return PhysicalState(altitude=new_altitude, velocity=new_velocity) @@ -246,7 +245,7 @@ def process_final_tick(delta_t, sim_clock, capsule): average_vel = ( capsule.v + math.sqrt( - capsule.v ** 2 + capsule.v**2 + 2 * capsule.a * (capsule.g - capsule.z * capsule.fuel_per_second / capsule.m) @@ -274,7 +273,7 @@ def handle_flyaway(sim_clock, capsule): / ( capsule.z * capsule.fuel_per_second - * math.sqrt(w ** 2 + capsule.v / capsule.z) + * math.sqrt(w**2 + capsule.v / capsule.z) ) ) + 0.05 diff --git a/59_Lunar_LEM_Rocket/rust/README.md b/59_Lunar_LEM_Rocket/rust/README.md index 9ecf50dce..158d6cb1a 100644 --- a/59_Lunar_LEM_Rocket/rust/README.md +++ b/59_Lunar_LEM_Rocket/rust/README.md @@ -9,4 +9,3 @@ This folder for chapter #59 contains three different games. Three folders here - lunar Conversion to [Rust](https://www.rust-lang.org) - diff --git a/59_Lunar_LEM_Rocket/rust/rocket/src/main.rs b/59_Lunar_LEM_Rocket/rust/rocket/src/main.rs index 5aa9a9f44..bd4685c61 100644 --- a/59_Lunar_LEM_Rocket/rust/rocket/src/main.rs +++ b/59_Lunar_LEM_Rocket/rust/rocket/src/main.rs @@ -38,7 +38,7 @@ fn main() { println!();println!(); println!("SEC FEET SPEED FUEL PLOT OF DISTANCE"); println!(); - let mut T=0;let mut H:i32=1000;let mut V=50;let mut F=150; + let mut T=0;let mut H:i32=1000;let mut V=50;let mut F=150; let D:i32; let mut V1:i32; let mut B:i32; 'falling: loop { println!(" {:<4}{:<11}{:<10}{:<8}I{capsule:>high$}", T,H,V,F,high=(H/15) as usize,capsule="*"); @@ -76,7 +76,7 @@ fn main() { println!("CONGRATULATIONS! A PERFECT LANDING!!"); println!("YOUR LICENSE WILL BE RENEWED.......LATER."); } - if V1.abs()>=2 { + if V1.abs()>=2 { println!("***** SORRY, BUT YOU BLEW IT!!!!"); println!("APPROPRIATE CONDOLENCES WILL BE SENT TO YOUR NEXT OF KIN."); } @@ -90,7 +90,7 @@ fn main() { fn input(prompt:&str) -> String { loop { - print!("{} ? ",prompt);io::stdout().flush().unwrap(); + print!("{} ? ",prompt);io::stdout().flush().unwrap(); let innn:String=read!("{}\n"); let out:String = innn.trim().to_string(); if out!="" {return out} @@ -98,10 +98,10 @@ fn input(prompt:&str) -> String { } fn input_int(prompt:&str) -> i32 { loop { - print!("{} ? ",prompt);io::stdout().flush().unwrap(); + print!("{} ? ",prompt);io::stdout().flush().unwrap(); match try_read!() { Ok(n) => return n, Err(_) => println!("Enter a number 0-30"), } } -} \ No newline at end of file +} diff --git a/60_Mastermind/javascript/mastermind.js b/60_Mastermind/javascript/mastermind.js index 40d8139e3..32639fc75 100644 --- a/60_Mastermind/javascript/mastermind.js +++ b/60_Mastermind/javascript/mastermind.js @@ -12,10 +12,10 @@ function input() { var input_element; var input_str; - + return new Promise(function (resolve) { input_element = document.createElement("INPUT"); - + print("? "); input_element.setAttribute("type", "text"); input_element.setAttribute("length", "50"); @@ -280,7 +280,7 @@ async function main() } h += m; show_score(); - + // // Now computer guesses // diff --git a/60_Mastermind/mastermind.bas b/60_Mastermind/mastermind.bas index 774c062c2..e6d548935 100644 --- a/60_Mastermind/mastermind.bas +++ b/60_Mastermind/mastermind.bas @@ -27,7 +27,7 @@ 240 NEXT X 250 PRINT 260 FOR R=1 TO R9 -270 PRINT +270 PRINT 280 PRINT "ROUND NUMBER";R;"----" 290 PRINT 300 PRINT "GUESS MY COMBINATION.":PRINT diff --git a/60_Mastermind/perl/mastermind.pl b/60_Mastermind/perl/mastermind.pl index d27e2e473..873648529 100755 --- a/60_Mastermind/perl/mastermind.pl +++ b/60_Mastermind/perl/mastermind.pl @@ -290,7 +290,7 @@ sub human_guesses { say "You guessed it in $guess_num moves."; return $guess_num; } - + say "You have $rslt->{black} blacks and $rslt->{white} whites."; } diff --git a/60_Mastermind/python/mastermind.py b/60_Mastermind/python/mastermind.py index ccc2ae9c2..61a98ef7d 100644 --- a/60_Mastermind/python/mastermind.py +++ b/60_Mastermind/python/mastermind.py @@ -1,5 +1,5 @@ -import random, sys - +import random +import sys def main(): @@ -14,64 +14,74 @@ def main(): # get user inputs for game conditions print("Mastermind") - print('Creative Computing Morristown, New Jersey') + print("Creative Computing Morristown, New Jersey") while num_colors > 8: - num_colors = int(input("Number of colors (max 8): ")) # C9 in BASIC - num_positions = int(input("Number of positions: ")) # P9 in BASIC - num_rounds = int(input("Number of rounds: ")) # R9 in BASIC + num_colors = int(input("Number of colors (max 8): ")) # C9 in BASIC + num_positions = int(input("Number of positions: ")) # P9 in BASIC + num_rounds = int(input("Number of rounds: ")) # R9 in BASIC possibilities = num_colors**num_positions all_possibilities = [1] * possibilities - print("Number of possibilities {}".format(possibilities)) - print('Color\tLetter') - print('=====\t======') + print(f"Number of possibilities {possibilities}") + print("Color\tLetter") + print("=====\t======") for element in range(0, num_colors): - print("{}\t{}".format(colors[element], colors[element][0])) + print(f"{colors[element]}\t{colors[element][0]}") current_round = 1 while current_round <= num_rounds: - print('Round number {}'.format(current_round)) + print(f"Round number {current_round}") num_moves = 1 guesses = [] turn_over = False - print('Guess my combination ...') - answer = int(possibilities * random.random()) + print("Guess my combination ...") + answer = int(possibilities * random.random()) numeric_answer = [-1] * num_positions for i in range(0, answer): numeric_answer = get_possibility(numeric_answer) - #human_readable_answer = make_human_readable(numeric_answer) - while (num_moves < 10 and not turn_over ): - print('Move # {} Guess : '.format(num_moves)) - user_command = input('Guess ') + # human_readable_answer = make_human_readable(numeric_answer) + while num_moves < 10 and not turn_over: + print(f"Move # {num_moves} Guess : ") + user_command = input("Guess ") if user_command == "BOARD": - print_board(guesses) #2000 - elif user_command == "QUIT": #2500 + print_board(guesses) # 2000 + elif user_command == "QUIT": # 2500 human_readable_answer = make_human_readable(numeric_answer) - print('QUITTER! MY COMBINATION WAS: {}'.format(human_readable_answer)) - print('GOOD BYE') + print(f"QUITTER! MY COMBINATION WAS: {human_readable_answer}") + print("GOOD BYE") quit() - elif len(user_command) != num_positions: #410 + elif len(user_command) != num_positions: # 410 print("BAD NUMBER OF POSITIONS") else: invalid_letters = get_invalid_letters(user_command) if invalid_letters > "": - print("INVALID GUESS: {}".format(invalid_letters)) + print(f"INVALID GUESS: {invalid_letters}") else: - guess_results = compare_two_positions(user_command, make_human_readable(numeric_answer)) - print("Results: {}".format(guess_results)) - if guess_results[1] == num_positions: # correct guess + guess_results = compare_two_positions( + user_command, make_human_readable(numeric_answer) + ) + print(f"Results: {guess_results}") + if guess_results[1] == num_positions: # correct guess turn_over = True - print("You guessed it in {} moves!".format(num_moves)) + print(f"You guessed it in {num_moves} moves!") human_score = human_score + num_moves print_score() else: - print("You have {} blacks and {} whites".format(guess_results[1], guess_results[2])) + print( + "You have {} blacks and {} whites".format( + guess_results[1], guess_results[2] + ) + ) num_moves = num_moves + 1 guesses.append(guess_results) - if not turn_over: # RAN OUT OF MOVES - print ("YOU RAN OUT OF MOVES! THAT'S ALL YOU GET!") - print("THE ACTUAL COMBINATION WAS: {}".format(make_human_readable(numeric_answer))) + if not turn_over: # RAN OUT OF MOVES + print("YOU RAN OUT OF MOVES! THAT'S ALL YOU GET!") + print( + "THE ACTUAL COMBINATION WAS: {}".format( + make_human_readable(numeric_answer) + ) + ) human_score = human_score + num_moves print_score() @@ -79,33 +89,35 @@ def main(): guesses = [] turn_over = False inconsistent_information = False - while(not turn_over and not inconsistent_information ): + while not turn_over and not inconsistent_information: all_possibilities = [1] * possibilities num_moves = 1 inconsistent_information = False - print ("NOW I GUESS. THINK OF A COMBINATION.") + print("NOW I GUESS. THINK OF A COMBINATION.") player_ready = input("HIT RETURN WHEN READY: ") - while (num_moves < 10 and not turn_over and not inconsistent_information): + while num_moves < 10 and not turn_over and not inconsistent_information: found_guess = False computer_guess = int(possibilities * random.random()) - if all_possibilities[computer_guess] == 1: # random guess is possible, use it + if ( + all_possibilities[computer_guess] == 1 + ): # random guess is possible, use it found_guess = True guess = computer_guess else: - for i in range (computer_guess, possibilities): + for i in range(computer_guess, possibilities): if all_possibilities[i] == 1: found_guess = True guess = i break if not found_guess: - for i in range (0, computer_guess): + for i in range(0, computer_guess): if all_possibilities[i] == 1: found_guess = True guess = i break - if not found_guess: # inconsistent info from user - print('YOU HAVE GIVEN ME INCONSISTENT INFORMATION.') - print('TRY AGAIN, AND THIS TIME PLEASE BE MORE CAREFUL.') + if not found_guess: # inconsistent info from user + print("YOU HAVE GIVEN ME INCONSISTENT INFORMATION.") + print("TRY AGAIN, AND THIS TIME PLEASE BE MORE CAREFUL.") turn_over = True inconsistent_information = True else: @@ -113,29 +125,37 @@ def main(): for i in range(0, guess): numeric_guess = get_possibility(numeric_guess) human_readable_guess = make_human_readable(numeric_guess) - print('My guess is: {}'.format(human_readable_guess)) - blacks, whites = input("ENTER BLACKS, WHITES (e.g. 1,2): ").split(",") + print(f"My guess is: {human_readable_guess}") + blacks, whites = input("ENTER BLACKS, WHITES (e.g. 1,2): ").split( + "," + ) blacks = int(blacks) whites = int(whites) - if blacks == num_positions: #Correct guess - print('I GOT IT IN {} MOVES'.format(num_moves)) + if blacks == num_positions: # Correct guess + print(f"I GOT IT IN {num_moves} MOVES") turn_over = True computer_score = computer_score + num_moves print_score() else: num_moves += 1 - for i in range (0, possibilities): - if all_possibilities[i] == 0: #already ruled out + for i in range(0, possibilities): + if all_possibilities[i] == 0: # already ruled out continue numeric_possibility = [-1] * num_positions - for j in range (0, i): - numeric_possibility = get_possibility(numeric_possibility) - human_readable_possibility = make_human_readable(numeric_possibility) #4000 - comparison = compare_two_positions(human_readable_possibility, human_readable_guess) + for j in range(0, i): + numeric_possibility = get_possibility( + numeric_possibility + ) + human_readable_possibility = make_human_readable( + numeric_possibility + ) # 4000 + comparison = compare_two_positions( + human_readable_possibility, human_readable_guess + ) print(comparison) - if ((blacks != comparison[1]) or (whites != comparison[2])): + if (blacks != comparison[1]) or (whites != comparison[2]): all_possibilities[i] = 0 - if not turn_over: # COMPUTER DID NOT GUESS + if not turn_over: # COMPUTER DID NOT GUESS print("I USED UP ALL MY MOVES!") print("I GUESS MY CPU IS JUST HAVING AN OFF DAY.") computer_score = computer_score + num_moves @@ -144,7 +164,8 @@ def main(): print_score(is_final_score=True) sys.exit() -#470 + +# 470 def get_invalid_letters(user_command): """Makes sure player input consists of valid colors for selected game configuration.""" valid_colors = color_letters[:num_colors] @@ -154,37 +175,40 @@ def get_invalid_letters(user_command): invalid_letters = invalid_letters + letter return invalid_letters -#2000 + +# 2000 def print_board(guesses): """Prints previous guesses within the round.""" print("Board") print("Move\tGuess\tBlack White") for idx, guess in enumerate(guesses): - print('{}\t{}\t{} {}'.format(idx+1, guess[0], guess[1], guess[2])) + print(f"{idx + 1}\t{guess[0]}\t{guess[1]} {guess[2]}") -#3500 -# Easily the place for most optimization, since they generate every possibility + +# 3500 +# Easily the place for most optimization, since they generate every possibility # every time when checking for potential solutions -# From the original article: +# From the original article: # "We did try a version that kept an actual list of all possible combinations # (as a string array), which was significantly faster than this versionn but # which ate tremendous amounts of memory." def get_possibility(possibility): - #print(possibility) - if possibility[0] > -1: #3530 - current_position = 0 # Python arrays are zero-indexed + # print(possibility) + if possibility[0] > -1: # 3530 + current_position = 0 # Python arrays are zero-indexed while True: - if possibility[current_position] < num_colors-1: # zero-index again + if possibility[current_position] < num_colors - 1: # zero-index again possibility[current_position] += 1 return possibility else: possibility[current_position] = 0 current_position += 1 - else: #3524 + else: # 3524 possibility = [0] * num_positions return possibility -#4500 + +# 4500 def compare_two_positions(guess, answer): """Returns blacks (correct color and position) and whites (correct color only) for candidate position (guess) versus reference position (answer).""" increment = 0 @@ -194,20 +218,23 @@ def compare_two_positions(guess, answer): for pos in range(0, num_positions): if guess[pos] != answer[pos]: for pos2 in range(0, num_positions): - if not(guess[pos] != answer[pos2] or guess[pos2] == answer[pos2]): # correct color but not correct place + if not ( + guess[pos] != answer[pos2] or guess[pos2] == answer[pos2] + ): # correct color but not correct place whites = whites + 1 - answer = answer[:pos2] + chr(increment) + answer[pos2+1:] - guess = guess[:pos] + chr(increment+1) + guess[pos+1:] + answer = answer[:pos2] + chr(increment) + answer[pos2 + 1 :] + guess = guess[:pos] + chr(increment + 1) + guess[pos + 1 :] increment = increment + 2 - else: #correct color and placement + else: # correct color and placement blacks = blacks + 1 # THIS IS DEVIOUSLY CLEVER - guess = guess[:pos] + chr(increment+1) + guess[pos+1:] - answer = answer[:pos] + chr(increment) + answer[pos+1:] + guess = guess[:pos] + chr(increment + 1) + guess[pos + 1 :] + answer = answer[:pos] + chr(increment) + answer[pos + 1 :] increment = increment + 2 return [initial_guess, blacks, whites] - -#5000 + logic from 1160 + + +# 5000 + logic from 1160 def print_score(is_final_score=False): """Prints score after each turn ends, including final score at end of game.""" if is_final_score: @@ -215,16 +242,18 @@ def print_score(is_final_score=False): print("FINAL SCORE:") else: print("SCORE:") - print(" COMPUTER {}".format(computer_score)) - print(" HUMAN {}".format(human_score)) + print(f" COMPUTER {computer_score}") + print(f" HUMAN {human_score}") -#4000, 5500, 6000 subroutines are all identical + +# 4000, 5500, 6000 subroutines are all identical def make_human_readable(num): """Make the numeric representation of a position human readable.""" - retval = '' + retval = "" for i in range(0, len(num)): retval = retval + color_letters[int(num[i])] return retval + if __name__ == "__main__": main() diff --git a/61_Math_Dice/csharp/README.md b/61_Math_Dice/csharp/README.md index 7017b45ae..e0863abd2 100644 --- a/61_Math_Dice/csharp/README.md +++ b/61_Math_Dice/csharp/README.md @@ -7,4 +7,4 @@ Conversion Notes - There are minor spacing issues which have been preserved in this port. - This implementation uses switch expressions to concisely place the dice pips in the right place. - Random() is only pseudo-random but perfectly adequate for the purposes of simulating dice rolls. -- Console width is assumed to be 120 chars for the purposes of centrally aligned the intro text. \ No newline at end of file +- Console width is assumed to be 120 chars for the purposes of centrally aligned the intro text. diff --git a/61_Math_Dice/java/Die.java b/61_Math_Dice/java/Die.java index 1a6162132..a1c8bbade 100644 --- a/61_Math_Dice/java/Die.java +++ b/61_Math_Dice/java/Die.java @@ -21,15 +21,15 @@ private void throwDie() { this.faceValue = 1 + generator.nextInt(sides); } - - /** + + /** * @return the faceValue */ public int getFaceValue() { return faceValue; } - + public void printDie() { throwDie(); int x = this.getFaceValue(); @@ -70,4 +70,4 @@ private void printZero() { private void printTwo() { System.out.println("| * * |"); } -} \ No newline at end of file +} diff --git a/61_Math_Dice/java/MathDice.java b/61_Math_Dice/java/MathDice.java index bd2ecd705..51494151b 100644 --- a/61_Math_Dice/java/MathDice.java +++ b/61_Math_Dice/java/MathDice.java @@ -35,9 +35,9 @@ public static void main(String[] args) { in.nextLine(); } - if(guess == 0) + if(guess == 0) System.exit(0); - + tries++; } @@ -50,4 +50,4 @@ public static void main(String[] args) { } } -} \ No newline at end of file +} diff --git a/61_Math_Dice/javascript/mathdice.js b/61_Math_Dice/javascript/mathdice.js index f6ccda814..60cfb8a7c 100644 --- a/61_Math_Dice/javascript/mathdice.js +++ b/61_Math_Dice/javascript/mathdice.js @@ -12,10 +12,10 @@ function input() { var input_element; var input_str; - + return new Promise(function (resolve) { input_element = document.createElement("INPUT"); - + print("? "); input_element.setAttribute("type", "text"); input_element.setAttribute("length", "50"); diff --git a/61_Math_Dice/pascal/README.md b/61_Math_Dice/pascal/README.md index 0e40aa9fb..1bdf62cdb 100644 --- a/61_Math_Dice/pascal/README.md +++ b/61_Math_Dice/pascal/README.md @@ -5,11 +5,10 @@ Conversion to [Pascal](https://en.wikipedia.org/wiki/Pascal_(programming_languag ##### Translator Notes: I tried to preserve as much of the original layout and flow of the code as possible. I added a procedure for the printing of the die-face; and -another to read an integer from the player, as I was unhappy with the runtime +another to read an integer from the player, as I was unhappy with the runtime error message spat out when a non-number is given to readln(). -I was torn between using the correct singular term "die" instead of "dice". +I was torn between using the correct singular term "die" instead of "dice". In the end I used a (poor?) combination of both. krt@krt.com.au 2020-10-12 - diff --git a/61_Math_Dice/pascal/mathdice.pas b/61_Math_Dice/pascal/mathdice.pas index 617f898f6..3c9c85aab 100644 --- a/61_Math_Dice/pascal/mathdice.pas +++ b/61_Math_Dice/pascal/mathdice.pas @@ -20,7 +20,7 @@ procedure printDice( face_value: integer ); else writeln( 'I * * I' ); - if ( ( face_value = 2 ) or ( face_value = 4 ) ) then + if ( ( face_value = 2 ) or ( face_value = 4 ) ) then writeln( 'I I' ) else if ( face_value = 6 ) then writeln( 'I * * I' ) @@ -33,7 +33,7 @@ procedure printDice( face_value: integer ); writeln( 'I * I' ) else writeln( 'I * * I' ); - + writeln( ' ----- ' ); end; @@ -61,7 +61,7 @@ function inputNumber(): integer; input_error := 1; while ( input_error <> 0 ) do begin - readln( player_input ); + readln( player_input ); val( player_input, player_answer, input_error ); @@ -126,4 +126,3 @@ function inputNumber(): integer; writeln( 'THE DICE ROLL AGAIN...' ); end; end. - diff --git a/61_Math_Dice/perl/mathdice.pl b/61_Math_Dice/perl/mathdice.pl index 4a2b6f6ee..47a0a4a00 100644 --- a/61_Math_Dice/perl/mathdice.pl +++ b/61_Math_Dice/perl/mathdice.pl @@ -48,7 +48,7 @@ sub game_play { else { print "N0, THE ANSWER IS $sum\n"; } - + } } } diff --git a/61_Math_Dice/python/mathdice.py b/61_Math_Dice/python/mathdice.py index ca84555cf..e131a0e55 100644 --- a/61_Math_Dice/python/mathdice.py +++ b/61_Math_Dice/python/mathdice.py @@ -1,51 +1,56 @@ from random import randint + print("Math Dice") print("https://github.com/coding-horror/basic-computer-games") print() -print("""This program generates images of two dice. +print( + """This program generates images of two dice. When two dice and an equals sign followed by a question mark have been printed, type your answer, and hit the ENTER key. To conclude the program, type 0. -""") +""" +) + def print_dice(n): - def print_0(): print("| |") + def print_2(): print("| * * |") print(" ----- ") - if n in [4,5,6]: + if n in [4, 5, 6]: print_2() - elif n in [2,3]: + elif n in [2, 3]: print("| * |") else: print_0() - if n in [1,3,5]: + if n in [1, 3, 5]: print("| * |") - elif n in [2,4]: + elif n in [2, 4]: print_0() else: print_2() - if n in [4,5,6]: + if n in [4, 5, 6]: print_2() - elif n in [2,3]: + elif n in [2, 3]: print("| * |") else: print_0() print(" ----- ") + def main(): while True: - d1 = randint(1,6) - d2 = randint(1,6) + d1 = randint(1, 6) + d2 = randint(1, 6) guess = 13 print_dice(d1) @@ -70,10 +75,8 @@ def main(): else: print("Correct!") - print("The dice roll again....") - if __name__ == "__main__": - main() \ No newline at end of file + main() diff --git a/61_Math_Dice/ruby/mathdice.rb b/61_Math_Dice/ruby/mathdice.rb index 60853d45e..c265e9cf9 100644 --- a/61_Math_Dice/ruby/mathdice.rb +++ b/61_Math_Dice/ruby/mathdice.rb @@ -18,7 +18,7 @@ def game_play roll = rand(6) + 1 print_dice(roll) sum = sum + roll - if num == 1 + if num == 1 print "\n +\n\n" end if num == 2 diff --git a/61_Math_Dice/rust/README.md b/61_Math_Dice/rust/README.md index 881f0dc1e..375601ae5 100644 --- a/61_Math_Dice/rust/README.md +++ b/61_Math_Dice/rust/README.md @@ -2,4 +2,4 @@ Original source downloaded [from Vintage Basic](http://www.vintage-basic.net/gam Conversion to [Rust](https://www.rust-lang.org/) by Anthony Rubick [AnthonyMichaelTDM](https://github.com/AnthonyMichaelTDM) -If you wish to give the user more than 2 attempts to get the number, change value assigned to the num_tries variable at the start of the main function \ No newline at end of file +If you wish to give the user more than 2 attempts to get the number, change value assigned to the num_tries variable at the start of the main function diff --git a/61_Math_Dice/rust/src/main.rs b/61_Math_Dice/rust/src/main.rs index 352169331..fc92dc16e 100644 --- a/61_Math_Dice/rust/src/main.rs +++ b/61_Math_Dice/rust/src/main.rs @@ -35,7 +35,7 @@ fn main() { if t < num_tries-1 { // user has tries left println!("NO, COUNT THE SPOTS AND GIVE ANOTHER ANSWER."); println!(" ="); - } + } else { //this is their last try println!("NO, THE ANSWER IS {}", dice_1+dice_2); } @@ -49,7 +49,7 @@ fn main() { //play again println!("\nThe dice roll again...."); } - + } /** @@ -68,7 +68,7 @@ fn welcome() { } /** - * print the dice, + * print the dice, */ fn print_dice(dice_value:u8) { //data @@ -120,9 +120,9 @@ fn get_number_from_user_input(prompt: &str, error_message: &str, min:u8, max:u8) if i < min || i > max { //input out of desired range println!("{} ({}-{})", error_message, min,max); continue; // run the loop again - } + } else { - break i;// this escapes the loop, returning i + break i;// this escapes the loop, returning i } }, Err(e) => { @@ -131,4 +131,4 @@ fn get_number_from_user_input(prompt: &str, error_message: &str, min:u8, max:u8) } }; }; -} \ No newline at end of file +} diff --git a/62_Mugwump/csharp/Strings/Intro.txt b/62_Mugwump/csharp/Strings/Intro.txt index 30ede4d68..ea46087a0 100644 --- a/62_Mugwump/csharp/Strings/Intro.txt +++ b/62_Mugwump/csharp/Strings/Intro.txt @@ -12,4 +12,3 @@ is distance above homebase. You get 10 tries. After each try, I will tell you how far you are from each wugwump. - diff --git a/62_Mugwump/java/src/Mugwump.java b/62_Mugwump/java/src/Mugwump.java index 6dbefef1a..a35ce8456 100644 --- a/62_Mugwump/java/src/Mugwump.java +++ b/62_Mugwump/java/src/Mugwump.java @@ -183,4 +183,4 @@ public static void main(String[] args) { Mugwump mugwump = new Mugwump(); mugwump.play(); } -} \ No newline at end of file +} diff --git a/62_Mugwump/javascript/mugwump.js b/62_Mugwump/javascript/mugwump.js index 06f0adb9c..6ae35a87e 100644 --- a/62_Mugwump/javascript/mugwump.js +++ b/62_Mugwump/javascript/mugwump.js @@ -12,10 +12,10 @@ function input() { var input_element; var input_str; - + return new Promise(function (resolve) { input_element = document.createElement("INPUT"); - + print("? "); input_element.setAttribute("type", "text"); input_element.setAttribute("length", "50"); diff --git a/62_Mugwump/perl/mugwump.pl b/62_Mugwump/perl/mugwump.pl index 33835b773..13a50bff9 100755 --- a/62_Mugwump/perl/mugwump.pl +++ b/62_Mugwump/perl/mugwump.pl @@ -10,7 +10,7 @@ # init_mugwump: pick the random places for the Mugwumps sub init_mugwump() { - @MUGWUMP = (); + @MUGWUMP = (); for (1 .. 4) { push @MUGWUMP, [ int(rand 10), int(rand 10) ]; } @@ -44,7 +44,7 @@ () PLAY: while (1) { init_mugwump(); - TURN: for my $turn (1 .. 10) { + TURN: for my $turn (1 .. 10) { printf("\nTurn no %d -- what is your guess ? ", $turn); @@ -88,9 +88,8 @@ () printf("Mugwump %d is at (%d, %d)\n", $i+1, $MUGWUMP[$i]->[0], $MUGWUMP[$i]->[1]) if $MUGWUMP[$i]->[0] != -1; } -} +} continue { print "\nThat was fun! Let's play again.......\n"; print "Four more Mugwumps are now in hiding.\n\n"; } - diff --git a/62_Mugwump/python/mugwump.py b/62_Mugwump/python/mugwump.py index fdcc29450..c5722407f 100644 --- a/62_Mugwump/python/mugwump.py +++ b/62_Mugwump/python/mugwump.py @@ -6,7 +6,7 @@ def introduction(): print( """The object of this game is to find 4 mugwumps hidden on a 10*10 grid. Homebase is position 0,0. -Any guess you make must be two numbers with each +Any guess you make must be two numbers with each number between 0 and 9 inclusive. First number is distance to right of homebase, and second number is the distance above homebase.""" @@ -37,6 +37,7 @@ def calculate_distance(guess, mugwump): d = sqrt(((mugwump[0] - guess[0]) ** 2) + ((mugwump[1] - guess[1]) ** 2)) return d + def play_again(): print("THAT WAS FUN! LET'S PLAY AGAIN.......") choice = input("Press Enter to play again, any other key then Enter to quit.") @@ -45,6 +46,7 @@ def play_again(): else: exit() + def play_round(): mugwumps = generate_mugwumps() turns = 1 diff --git a/63_Name/javascript/name.js b/63_Name/javascript/name.js index cfa33cf44..3c376f599 100644 --- a/63_Name/javascript/name.js +++ b/63_Name/javascript/name.js @@ -12,10 +12,10 @@ function input() { var input_element; var input_str; - + return new Promise(function (resolve) { input_element = document.createElement("INPUT"); - + print("? "); input_element.setAttribute("type", "text"); input_element.setAttribute("length", "50"); diff --git a/63_Name/perl/name.pl b/63_Name/perl/name.pl index d25bcfe0a..512ffbb7e 100755 --- a/63_Name/perl/name.pl +++ b/63_Name/perl/name.pl @@ -31,5 +31,3 @@ print "\n"; print "I REALLY ENJOYED MEETING YOU $A.\n"; print "HAVE A NICE DAY!\n"; exit; - - diff --git a/64_Nicomachus/java/src/Nicomachus.java b/64_Nicomachus/java/src/Nicomachus.java index 53bbbedd7..9996ecd24 100644 --- a/64_Nicomachus/java/src/Nicomachus.java +++ b/64_Nicomachus/java/src/Nicomachus.java @@ -182,4 +182,4 @@ public static void main(String[] args) throws Exception { Nicomachus nicomachus = new Nicomachus(); nicomachus.play(); } -} \ No newline at end of file +} diff --git a/64_Nicomachus/javascript/nicomachus.js b/64_Nicomachus/javascript/nicomachus.js index 7abe1d513..93083d781 100644 --- a/64_Nicomachus/javascript/nicomachus.js +++ b/64_Nicomachus/javascript/nicomachus.js @@ -12,10 +12,10 @@ function input() { var input_element; var input_str; - + return new Promise(function (resolve) { input_element = document.createElement("INPUT"); - + print("? "); input_element.setAttribute("type", "text"); input_element.setAttribute("length", "50"); diff --git a/64_Nicomachus/perl/nicomachus.pl b/64_Nicomachus/perl/nicomachus.pl index 4ed2018ff..254859303 100755 --- a/64_Nicomachus/perl/nicomachus.pl +++ b/64_Nicomachus/perl/nicomachus.pl @@ -42,5 +42,3 @@ print "LET'S TRY ANOTHER.\n"; } #goto Line20; exit; - - diff --git a/65_Nim/javascript/nim.js b/65_Nim/javascript/nim.js index 847c049a0..ddd09d98d 100644 --- a/65_Nim/javascript/nim.js +++ b/65_Nim/javascript/nim.js @@ -12,10 +12,10 @@ function input() { var input_element; var input_str; - + return new Promise(function (resolve) { input_element = document.createElement("INPUT"); - + print("? "); input_element.setAttribute("type", "text"); input_element.setAttribute("length", "50"); @@ -146,7 +146,7 @@ async function main() print("MACHINE LOSES\n"); break; } - + } else { c = 0; for (i = 1; i <= n; i++) { diff --git a/65_Nim/nim.bas b/65_Nim/nim.bas index cda67e30c..d078a0c6a 100644 --- a/65_Nim/nim.bas +++ b/65_Nim/nim.bas @@ -151,6 +151,6 @@ 1680 IF Q9$="NO" THEN 1730 1690 IF Q9$="no" THEN 1730 1700 PRINT "PLEASE. YES OR NO." -1710 GOTO 1650 +1710 GOTO 1650 1720 GOTO 440 1730 END diff --git a/65_Nim/python/Traditional_NIM.py b/65_Nim/python/Traditional_NIM.py index 3507ecc26..a84cc52b5 100644 --- a/65_Nim/python/Traditional_NIM.py +++ b/65_Nim/python/Traditional_NIM.py @@ -1,126 +1,130 @@ import random -#Class of the Game + +# Class of the Game class NIM: + def __init__(self): + + self.Piles = {1: 7, 2: 5, 3: 3, 4: 1} + + def Remove_pegs(self, command): + + try: + + pile, num = command.split(",") + num = int(num) + pile = int(pile) + + except Exception as e: - def __init__(self): + if "not enough values" in str(e): + print( + '\nNot a valid command. Your command should be in the form of "1,3", Try Again\n' + ) - self.Piles = { - 1 : 7, - 2 : 5, - 3 : 3, - 4 : 1 - } + else: + print("\nError, Try again\n") + return None - def Remove_pegs(self, command): + if self._command_integrity(num, pile) == True: + self.Piles[pile] -= num + else: + print("\nInvalid value of either Peg or Pile\n") - try: + def get_AI_move(self): - pile, num = command.split(',') - num = int(num) - pile = int(pile) + possible_pile = [] + for k, v in self.Piles.items(): + if v != 0: + possible_pile.append(k) - except Exception as e: + pile = random.choice(possible_pile) - if 'not enough values' in str(e): - print('\nNot a valid command. Your command should be in the form of "1,3", Try Again\n') + num = random.randint(1, self.Piles[pile]) - else: - print('\nError, Try again\n') - return None + return pile, num - if self._command_integrity(num, pile) == True: - self.Piles[pile] -= num - else: - print('\nInvalid value of either Peg or Pile\n') + def _command_integrity(self, num, pile): - def get_AI_move(self): - - possible_pile = [] - for k,v in self.Piles.items(): - if v != 0: - possible_pile.append(k) + if pile <= 4 and pile >= 1: + if num <= self.Piles[pile]: + return True - pile = random.choice(possible_pile) + return False - num = random.randint(1,self.Piles[pile]) + def print_pegs(self): - return pile, num + for pile, peg in self.Piles.items(): + print("Pile {} : {}".format(pile, "O " * peg)) - def _command_integrity(self, num, pile): + def Help(self): - if pile <= 4 and pile >= 1: - if num <= self.Piles[pile]: - return True - - return False + print("-" * 10) + print('\nThe Game is player with a number of Piles of Objects("O" == one peg)') + print("\nThe Piles are arranged as given below(Tradional NIM)\n") + self.print_pegs() + print( + '\nAny Number of of Objects are removed one pile by "YOU" and the machine alternatively' + ) + print("\nOn your turn, you may take all the objects that remain in any pile") + print("but you must take ATLEAST one object") + print("\nAnd you may take objects from only one pile on a single turn.") + print("\nThe winner is defined as the one that picks the last remaning object") + print("-" * 10) - def print_pegs(self): + def Checkforwin(self): - for pile, peg in self.Piles.items(): - print('Pile {} : {}'.format(pile, 'O '*peg)) - - def Help(self): + sum = 0 + for k, v in self.Piles.items(): + sum += v - print('-'*10) - print('\nThe Game is player with a number of Piles of Objects("O" == one peg)') - print('\nThe Piles are arranged as given below(Tradional NIM)\n') - self.print_pegs() - print('\nAny Number of of Objects are removed one pile by "YOU" and the machine alternatively') - print('\nOn your turn, you may take all the objects that remain in any pile') - print('but you must take ATLEAST one object') - print('\nAnd you may take objects from only one pile on a single turn.') - print('\nThe winner is defined as the one that picks the last remaning object') - print('-'*10) + if sum == 0: + return True - def Checkforwin(self): + else: + return False - sum = 0 - for k,v in self.Piles.items(): - sum += v - - if sum == 0: - return True - - else: - return False -#main program +# main program if __name__ == "__main__": - #Game initialization - game = NIM() - - print('Hello, This is a game of NIM') - help = input('Do You Need Instruction (YES or NO): ') - - if help == 'yes' or help == 'YES' or help == 'Yes': - - #Printing Game Instruction - game.Help() - - #Start game loop - input('\nPress Enter to start the Game:\n') - End = False - while True: - - game.print_pegs() - - #Players Move - command = input('\nYOUR MOVE - Number of PILE, Number of Object? ') - game.Remove_pegs(command) - End = game.Checkforwin() - if End == True: - print('\nPlayer Wins the Game, Congratulations!!') - input('\nPress any key to exit') - break - - #Computers Move - command = game.get_AI_move() - print('\nA.I MOVE - A.I Removed {} pegs from Pile {}'.format(command[1],command[0])) - game.Remove_pegs(str(command[0]) +',' + str(command[1])) - End = game.Checkforwin() - if End == True: - print('\nComputer Wins the Game, Better Luck Next Time\n') - input('Press any key to exit') - break + # Game initialization + game = NIM() + + print("Hello, This is a game of NIM") + help = input("Do You Need Instruction (YES or NO): ") + + if help == "yes" or help == "YES" or help == "Yes": + + # Printing Game Instruction + game.Help() + + # Start game loop + input("\nPress Enter to start the Game:\n") + End = False + while True: + + game.print_pegs() + + # Players Move + command = input("\nYOUR MOVE - Number of PILE, Number of Object? ") + game.Remove_pegs(command) + End = game.Checkforwin() + if End == True: + print("\nPlayer Wins the Game, Congratulations!!") + input("\nPress any key to exit") + break + + # Computers Move + command = game.get_AI_move() + print( + "\nA.I MOVE - A.I Removed {} pegs from Pile {}".format( + command[1], command[0] + ) + ) + game.Remove_pegs(str(command[0]) + "," + str(command[1])) + End = game.Checkforwin() + if End == True: + print("\nComputer Wins the Game, Better Luck Next Time\n") + input("Press any key to exit") + break diff --git a/65_Nim/ruby/nim.rb b/65_Nim/ruby/nim.rb index a326695fc..d6b157b3a 100644 --- a/65_Nim/ruby/nim.rb +++ b/65_Nim/ruby/nim.rb @@ -278,5 +278,3 @@ def yourMove end end end - - diff --git a/66_Number/csharp/program.cs b/66_Number/csharp/program.cs index a94fc7b26..b73c9c7b5 100644 --- a/66_Number/csharp/program.cs +++ b/66_Number/csharp/program.cs @@ -47,7 +47,7 @@ private void GetRandomNumbers(out int Random1, out int Random2, out int Random3, { Random rand = new Random(); - // Get a unique set of random numbers between 1 and 5 + // Get a unique set of random numbers between 1 and 5 // I assume this is what the original BASIC FNR(X)=INT(5*RND(1)+1) is doing Random1 = (int)(5 * rand.NextDouble() + 1); do @@ -77,10 +77,10 @@ private void Play() int Guess = 0; GetRandomNumbers(out Random1, out Random2, out Random3, out Random4, out Random5); - + while (!Win) { - + Guess = PromptForGuess(); if (Guess == Random1) @@ -96,7 +96,7 @@ private void Play() Points += 1; else if (Guess == Random5) Points -= (int)(Points * 0.5); - + if (Points > 500) { Console.WriteLine("!!!!You Win!!!! with {0} points.", Points); @@ -123,4 +123,4 @@ static void Main(string[] args) } } -} \ No newline at end of file +} diff --git a/66_Number/javascript/number.js b/66_Number/javascript/number.js index 5bda2ae67..06e236d5d 100644 --- a/66_Number/javascript/number.js +++ b/66_Number/javascript/number.js @@ -12,10 +12,10 @@ function input() { var input_element; var input_str; - + return new Promise(function (resolve) { input_element = document.createElement("INPUT"); - + print("? "); input_element.setAttribute("type", "text"); input_element.setAttribute("length", "50"); diff --git a/66_Number/perl/number.pl b/66_Number/perl/number.pl index b76dc6e5b..a5a5889b6 100755 --- a/66_Number/perl/number.pl +++ b/66_Number/perl/number.pl @@ -35,5 +35,3 @@ sub FNR { my ($X)= @_; #Useless... return int(5*rand(1)+1); } - - diff --git a/67_One_Check/java/OneCheck.java b/67_One_Check/java/OneCheck.java index 0e69fc304..88194b299 100644 --- a/67_One_Check/java/OneCheck.java +++ b/67_One_Check/java/OneCheck.java @@ -9,39 +9,39 @@ *

* Note: The idea was to create a version of the 1970's BASIC game in Java, without introducing * new features - no additional text, error checking, etc has been added. - * + * * Converted from BASIC to Java by Darren Cardenas. */ - -public class OneCheck { + +public class OneCheck { private final Scanner scan; // For user input - + private enum Step { SHOW_INSTRUCTIONS, SHOW_BOARD, GET_MOVE, GET_SUMMARY, QUERY_RETRY - } - + } + public OneCheck() { - + scan = new Scanner(System.in); - - } // End of constructor OneCheck - + + } // End of constructor OneCheck + public void play() { - + showIntro(); startGame(); - - } // End of method play - + + } // End of method play + private static void showIntro() { - + System.out.println(" ".repeat(29) + "ONE CHECK"); System.out.println(" ".repeat(14) + "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY"); System.out.println("\n\n"); - - } // End of method showIntro - + + } // End of method showIntro + private void startGame() { int fromSquare = 0; @@ -50,26 +50,26 @@ private void startGame() { int square = 0; int startPosition = 0; int toSquare = 0; - + // Move legality test variables int fromTest1 = 0; int fromTest2 = 0; int toTest1 = 0; int toTest2 = 0; - + int[] positions = new int[65]; - + Step nextStep = Step.SHOW_INSTRUCTIONS; - + String lineContent = ""; - String userResponse = ""; + String userResponse = ""; // Begin outer while loop while (true) { - + // Begin switch switch (nextStep) { - + case SHOW_INSTRUCTIONS: System.out.println("SOLITAIRE CHECKER PUZZLE BY DAVID AHL\n"); @@ -82,68 +82,68 @@ private void startGame() { System.out.println("CHECKER AND '0' AN EMPTY SQUARE. WHEN YOU HAVE NO"); System.out.println("POSSIBLE JUMPS REMAINING, INPUT A '0' IN RESPONSE TO"); System.out.println("QUESTION 'JUMP FROM ?'\n"); - System.out.println("HERE IS THE NUMERICAL BOARD:\n"); - + System.out.println("HERE IS THE NUMERICAL BOARD:\n"); + nextStep = Step.SHOW_BOARD; break; - + case SHOW_BOARD: - + // Begin loop through all squares for (square = 1; square <= 57; square += 8) { - + lineContent = String.format("% -4d%-4d%-4d%-4d%-4d%-4d%-4d%-4d", square, square + 1, square + 2, square + 3, square + 4, square + 5, square + 6, square + 7); System.out.println(lineContent); - + } // End loop through all squares - + System.out.println(""); System.out.println("AND HERE IS THE OPENING POSITION OF THE CHECKERS."); - System.out.println(""); - + System.out.println(""); + Arrays.fill(positions, 1); - + // Begin generating start positions for (square = 19; square <= 43; square += 8) { - + for (startPosition = square; startPosition <= square + 3; startPosition++) { - + positions[startPosition] = 0; - - } + + } } // End generating start positions - + numJumps = 0; - - printBoard(positions); - + + printBoard(positions); + nextStep = Step.GET_MOVE; break; - + case GET_MOVE: - + System.out.print("JUMP FROM? "); fromSquare = scan.nextInt(); scan.nextLine(); // Discard newline - + // User requested summary - if (fromSquare == 0) { + if (fromSquare == 0) { nextStep = Step.GET_SUMMARY; - break; + break; } - + System.out.print("TO? "); toSquare = scan.nextInt(); scan.nextLine(); // Discard newline - System.out.println(""); + System.out.println(""); // Check legality of move fromTest1 = (int) Math.floor((fromSquare - 1.0) / 8.0); fromTest2 = fromSquare - 8 * fromTest1; toTest1 = (int) Math.floor((toSquare - 1.0) / 8.0); toTest2 = toSquare - 8 * toTest1; - + if ((fromTest1 > 7) || (toTest1 > 7) || (fromTest2 > 8) || @@ -153,49 +153,49 @@ private void startGame() { (positions[(toSquare + fromSquare) / 2] == 0) || (positions[fromSquare] == 0) || (positions[toSquare] == 1)) { - + System.out.println("ILLEGAL MOVE. TRY AGAIN..."); nextStep = Step.GET_MOVE; - break; + break; } positions[toSquare] = 1; positions[fromSquare] = 0; positions[(toSquare + fromSquare) / 2] = 0; numJumps++; - - printBoard(positions); - + + printBoard(positions); + nextStep = Step.GET_MOVE; break; - + case GET_SUMMARY: - + numPieces = 0; - + // Count remaining pieces - for (square = 1; square <= 64; square++) { - numPieces += positions[square]; + for (square = 1; square <= 64; square++) { + numPieces += positions[square]; } - + System.out.println(""); System.out.println("YOU MADE " + numJumps + " JUMPS AND HAD " + numPieces + " PIECES"); - System.out.println("REMAINING ON THE BOARD.\n"); - - nextStep = Step.QUERY_RETRY; + System.out.println("REMAINING ON THE BOARD.\n"); + + nextStep = Step.QUERY_RETRY; break; - + case QUERY_RETRY: while (true) { System.out.print("TRY AGAIN? "); userResponse = scan.nextLine(); System.out.println(""); - + if (userResponse.toUpperCase().equals("YES")) { nextStep = Step.SHOW_BOARD; break; - } + } else if (userResponse.toUpperCase().equals("NO")) { System.out.println("O.K. HOPE YOU HAD FUN!!"); return; @@ -203,50 +203,50 @@ else if (userResponse.toUpperCase().equals("NO")) { else { System.out.println("PLEASE ANSWER 'YES' OR 'NO'."); } - } + } break; - + default: System.out.println("INVALID STEP"); nextStep = Step.QUERY_RETRY; - break; + break; } // End of switch - - } // End outer while loop - - } // End of method startGame - + + } // End outer while loop + + } // End of method startGame + public void printBoard(int[] positions) { - + int column = 0; - int row = 0; + int row = 0; String lineContent = ""; - + // Begin loop through all rows for (row = 1; row <= 57; row += 8) { - + // Begin loop through all columns for (column = row; column <= row + 7; column++) { - - lineContent += " " + positions[column]; - + + lineContent += " " + positions[column]; + } // End loop through all columns - + System.out.println(lineContent); - lineContent = ""; - + lineContent = ""; + } // End loop through all rows - System.out.println(""); - + System.out.println(""); + } // End of method printBoard - + public static void main(String[] args) { - + OneCheck game = new OneCheck(); game.play(); - + } // End of method main - + } // End of class OneCheck diff --git a/67_One_Check/javascript/onecheck.js b/67_One_Check/javascript/onecheck.js index a9633b466..36876809f 100644 --- a/67_One_Check/javascript/onecheck.js +++ b/67_One_Check/javascript/onecheck.js @@ -12,10 +12,10 @@ function input() { var input_element; var input_str; - + return new Promise(function (resolve) { input_element = document.createElement("INPUT"); - + print("? "); input_element.setAttribute("type", "text"); input_element.setAttribute("length", "50"); diff --git a/67_One_Check/python/onecheck.py b/67_One_Check/python/onecheck.py index b3d828b19..3510da70e 100644 --- a/67_One_Check/python/onecheck.py +++ b/67_One_Check/python/onecheck.py @@ -2,41 +2,43 @@ # Port to python by imiro + def tab(x): - return ' '*x + return " " * x + def main(): - + # Initial instructions - print(tab(30) + "ONE CHECK"); - print(tab(15) + "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY"); - print(); - print(); - print(); - print("SOLITAIRE CHECKER PUZZLE BY DAVID AHL"); - print(); - print("48 CHECKERS ARE PLACED ON THE 2 OUTSIDE SPACES OF A"); - print("STANDARD 64-SQUARE CHECKERBOARD. THE OBJECT IS TO"); - print("REMOVE AS MANY CHECKERS AS POSSIBLE BY DIAGONAL JUMPS"); - print("(AS IN STANDARD CHECKERS). USE THE NUMBERED BOARD TO"); - print("INDICATE THE SQUARE YOU WISH TO JUMP FROM AND TO. ON"); - print("THE BOARD PRINTED OUT ON EACH TURN '1' INDICATES A"); - print("CHECKER AND '0' AN EMPTY SQUARE. WHEN YOU HAVE NO"); - print("POSSIBLE JUMPS REMAINING, INPUT A '0' IN RESPONSE TO"); - print("QUESTION 'JUMP FROM ?'"); - print(); - print("HERE IS THE NUMERICAL BOARD:"); - print(); - - while(True): - for j in range(1,64,8): - for i in range(j,j+7): - print(i, end=(' '*(3 if i < 10 else 2))) - print(j+7) + print(tab(30) + "ONE CHECK") + print(tab(15) + "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY") + print() + print() + print() + print("SOLITAIRE CHECKER PUZZLE BY DAVID AHL") + print() + print("48 CHECKERS ARE PLACED ON THE 2 OUTSIDE SPACES OF A") + print("STANDARD 64-SQUARE CHECKERBOARD. THE OBJECT IS TO") + print("REMOVE AS MANY CHECKERS AS POSSIBLE BY DIAGONAL JUMPS") + print("(AS IN STANDARD CHECKERS). USE THE NUMBERED BOARD TO") + print("INDICATE THE SQUARE YOU WISH TO JUMP FROM AND TO. ON") + print("THE BOARD PRINTED OUT ON EACH TURN '1' INDICATES A") + print("CHECKER AND '0' AN EMPTY SQUARE. WHEN YOU HAVE NO") + print("POSSIBLE JUMPS REMAINING, INPUT A '0' IN RESPONSE TO") + print("QUESTION 'JUMP FROM ?'") + print() + print("HERE IS THE NUMERICAL BOARD:") + print() + + while True: + for j in range(1, 64, 8): + for i in range(j, j + 7): + print(i, end=(" " * (3 if i < 10 else 2))) + print(j + 7) print() print("AND HERE IS THE OPENING POSITION OF THE CHECKERS.") print() - + (jumps, left) = play_game() print() @@ -44,72 +46,83 @@ def main(): print("REMAINING ON THE BOARD.") print() - if not(try_again()): + if not (try_again()): break print() print("O.K. HOPE YOU HAD FUN!!") + def play_game(): # Initialize board # Give more than 64 elements to accomodate 1-based indexing - board = [1]*70 - for j in range(19,44,8): - for i in range(j,j+4): + board = [1] * 70 + for j in range(19, 44, 8): + for i in range(j, j + 4): board[i] = 0 jumps = 0 while True: # print board - for j in range(1,64,8): - for i in range(j,j+7): - print(board[i], end=' ') - print(board[j+7]) + for j in range(1, 64, 8): + for i in range(j, j + 7): + print(board[i], end=" ") + print(board[j + 7]) print() while True: - print("JUMP FROM", end=' ') + print("JUMP FROM", end=" ") f = input() f = int(f) if f == 0: break - print("TO", end=' ') + print("TO", end=" ") t = input() t = int(t) print() # Check legality of move - f1 = ((f-1) // 8) + f1 = (f - 1) // 8 f2 = f - 8 * f1 - t1 = ((t-1) // 8) + t1 = (t - 1) // 8 t2 = t - 8 * t1 - if (f1 > 7 or t1 > 7 or f2 > 8 or t2 > 8 or abs(f1 - t1) != 2 or - abs(f2 - t2) != 2 or board[(t + f) // 2] == 0 or - board[f] == 0 or board[t] == 1): + if ( + f1 > 7 + or t1 > 7 + or f2 > 8 + or t2 > 8 + or abs(f1 - t1) != 2 + or abs(f2 - t2) != 2 + or board[(t + f) // 2] == 0 + or board[f] == 0 + or board[t] == 1 + ): print("ILLEGAL MOVE. TRY AGAIN...") continue break - - if(f == 0): + + if f == 0: break board[t] = 1 board[f] = 0 - board[(t+f) // 2] = 0 + board[(t + f) // 2] = 0 jumps = jumps + 1 left = 0 - for i in range(1,64+1): + for i in range(1, 64 + 1): left = left + board[i] return (str(jumps), str(left)) + def try_again(): - print("TRY AGAIN", end=' ') + print("TRY AGAIN", end=" ") answer = input() - if (answer.upper() == "YES"): + if answer.upper() == "YES": return True - elif (answer.upper() == "NO"): + elif answer.upper() == "NO": return False print("PLEASE ANSWER 'YES' OR 'NO'.") try_again() -if __name__ == '__main__': + +if __name__ == "__main__": main() diff --git a/68_Orbit/java/Orbit.java b/68_Orbit/java/Orbit.java index 13a8026bc..5ecdb770e 100644 --- a/68_Orbit/java/Orbit.java +++ b/68_Orbit/java/Orbit.java @@ -10,29 +10,29 @@ *

* Note: The idea was to create a version of the 1970's BASIC game in Java, without introducing * new features - no additional text, error checking, etc has been added. - * + * * Converted from BASIC to Java by Darren Cardenas. */ - -public class Orbit { + +public class Orbit { private final Scanner scan; // For user input - + public Orbit() { - + scan = new Scanner(System.in); - - } // End of constructor Orbit + + } // End of constructor Orbit public void play() { - + showIntro(); startGame(); - - } // End of method play - + + } // End of method play + private static void showIntro() { - + System.out.println(" ".repeat(32) + "ORBIT"); System.out.println(" ".repeat(14) + "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY"); System.out.println("\n\n"); @@ -57,13 +57,13 @@ private static void showIntro() { System.out.println("ANGLE (BETWEEN 0 AND 360) AND A DISTANCE IN UNITS OF"); System.out.println("100 MILES (BETWEEN 100 AND 300), AFTER WHICH YOUR BOMB'S"); System.out.println("DISTANCE FROM THE ENEMY SHIP WILL BE GIVEN."); - System.out.println(""); + System.out.println(""); System.out.println("AN EXPLOSION WITHIN 5,000 MILES OF THE ROMULAN SHIP"); System.out.println("WILL DESTROY IT."); System.out.println(""); System.out.println("BELOW IS A DIAGRAM TO HELP YOU VISUALIZE YOUR PLIGHT."); System.out.println(""); - System.out.println(""); + System.out.println(""); System.out.println(" 90"); System.out.println(" 0000000000000"); System.out.println(" 0000000000000000000"); @@ -94,58 +94,58 @@ private static void showIntro() { System.out.println("WITHOUT SUFFICIENT POWER THE ROMULAN SHIP'S ALTITUDE"); System.out.println("AND ORBITAL RATE WILL REMAIN CONSTANT."); System.out.println(""); - System.out.println("GOOD LUCK. THE FEDERATION IS COUNTING ON YOU."); - - } // End of method showIntro - + System.out.println("GOOD LUCK. THE FEDERATION IS COUNTING ON YOU."); + + } // End of method showIntro + private void startGame() { - double bombDistance = 0; + double bombDistance = 0; int bombAltitude = 0; int bombAngle = 0; int deltaAngle = 0; int hour = 0; int shipAltitude = 0; int shipAngle = 0; - int shipRate = 0; - String userResponse = ""; + int shipRate = 0; + String userResponse = ""; // Begin outer while loop - while (true) { + while (true) { shipAngle = (int) (361 * Math.random()); shipAltitude = (int) (201 * Math.random() + 200); shipRate = (int) (21 * Math.random() + 10); hour = 0; - + // Begin time limit loop while (hour < 7) { System.out.println(""); System.out.println(""); System.out.println("THIS IS HOUR " + (hour + 1) + ", AT WHAT ANGLE DO YOU WISH TO SEND"); - System.out.print("YOUR PHOTON BOMB? "); + System.out.print("YOUR PHOTON BOMB? "); bombAngle = Integer.parseInt(scan.nextLine()); - + System.out.print("HOW FAR OUT DO YOU WISH TO DETONATE IT? "); bombAltitude = Integer.parseInt(scan.nextLine()); - + System.out.println(""); System.out.println(""); - + // Update ship position shipAngle += shipRate; // Handle full revolutions - if (shipAngle >= 360) { + if (shipAngle >= 360) { shipAngle -= 360; } - + deltaAngle = Math.abs(shipAngle - bombAngle); // Keep angle in upper quadrants - if (deltaAngle >= 180) { - deltaAngle = 360 - deltaAngle; + if (deltaAngle >= 180) { + deltaAngle = 360 - deltaAngle; } bombDistance = Math.sqrt(shipAltitude * shipAltitude + bombAltitude * bombAltitude - 2 * shipAltitude @@ -153,22 +153,22 @@ private void startGame() { System.out.format("YOUR PHOTON BOMB EXPLODED " + "%.5f" + "*10^2 MILES FROM THE\n", bombDistance); System.out.println("ROMULAN SHIP."); - + // Win condition - if (bombDistance <= 50) { + if (bombDistance <= 50) { System.out.println("YOU HAVE SUCCESSFULLY COMPLETED YOUR MISSION."); - break; - } - + break; + } + hour++; - + } // End time limit loop // Lose condition - if (hour == 7) { - System.out.println("YOU HAVE ALLOWED THE ROMULANS TO ESCAPE."); - } - + if (hour == 7) { + System.out.println("YOU HAVE ALLOWED THE ROMULANS TO ESCAPE."); + } + System.out.println("ANOTHER ROMULAN SHIP HAS GONE INTO ORBIT."); System.out.print("DO YOU WISH TO TRY TO DESTROY IT? "); userResponse = scan.nextLine(); @@ -176,17 +176,17 @@ private void startGame() { if (!userResponse.toUpperCase().equals("YES")) { System.out.println("GOOD BYE."); break; - } - - } // End outer while loop - - } // End of method startGame + } + + } // End outer while loop + + } // End of method startGame public static void main(String[] args) { - + Orbit game = new Orbit(); game.play(); - + } // End of method main - + } // End of class Orbit diff --git a/68_Orbit/javascript/orbit.js b/68_Orbit/javascript/orbit.js index fc505bdf6..ed20fe0f1 100644 --- a/68_Orbit/javascript/orbit.js +++ b/68_Orbit/javascript/orbit.js @@ -12,10 +12,10 @@ function input() { var input_element; var input_str; - + return new Promise(function (resolve) { input_element = document.createElement("INPUT"); - + print("? "); input_element.setAttribute("type", "text"); input_element.setAttribute("length", "50"); diff --git a/68_Orbit/orbit.bas b/68_Orbit/orbit.bas index 123028871..f290eee47 100644 --- a/68_Orbit/orbit.bas +++ b/68_Orbit/orbit.bas @@ -57,7 +57,7 @@ 199 PRINT "COUNTERCLOCKWISE AROUND YOUR PLANET. DON'T FORGET THAT" 200 PRINT "WITHOUT SUFFICIENT POWER THE ROMULAN SHIP'S ALTITUDE" 210 PRINT "AND ORBITAL RATE WILL REMAIN CONSTANT." -220 PRINT +220 PRINT 230 PRINT "GOOD LUCK. THE FEDERATION IS COUNTING ON YOU." 270 A=INT(360*RND(1)) 280 D=INT(200*RND(1)+200) diff --git a/68_Orbit/python/orbit.py b/68_Orbit/python/orbit.py index 66fb6c560..252be2a66 100644 --- a/68_Orbit/python/orbit.py +++ b/68_Orbit/python/orbit.py @@ -124,8 +124,8 @@ def play_game(): rom_angle = (rom_angle + rom_angular_velocity) % 360 angular_difference = rom_angle - bomb_angle c = math.sqrt( - rom_distance ** 2 - + bomb_distance ** 2 + rom_distance**2 + + bomb_distance**2 - 2 * rom_distance * bomb_distance diff --git a/69_Pizza/csharp/CustomerMap.cs b/69_Pizza/csharp/CustomerMap.cs index ee991de31..d2214c269 100644 --- a/69_Pizza/csharp/CustomerMap.cs +++ b/69_Pizza/csharp/CustomerMap.cs @@ -25,7 +25,7 @@ public string GetCustomerOnPosition(int x, int y) { return string.Empty; } - + return _customerMap[y, x]; } @@ -74,8 +74,8 @@ public override string ToString() /// True if position is out of range otherwise false. private bool IsPositionOutOfRange(int x, int y) { - return - x < 0 || x > _mapSize - 1 || + return + x < 0 || x > _mapSize - 1 || y < 0 || y > _mapSize - 1; } @@ -128,4 +128,4 @@ private void AppendXLine(StringBuilder mapToDisplay, int horizontalSpace) mapToDisplay.Append(Environment.NewLine); } } -} \ No newline at end of file +} diff --git a/69_Pizza/csharp/PizzaGame.cs b/69_Pizza/csharp/PizzaGame.cs index 22c78e05a..b4157047c 100644 --- a/69_Pizza/csharp/PizzaGame.cs +++ b/69_Pizza/csharp/PizzaGame.cs @@ -293,4 +293,4 @@ private void WriteEmptyLine(int numberOfEmptyLines = 1) } } } -} \ No newline at end of file +} diff --git a/69_Pizza/csharp/Program.cs b/69_Pizza/csharp/Program.cs index 6c21fad0a..48cc4e275 100644 --- a/69_Pizza/csharp/Program.cs +++ b/69_Pizza/csharp/Program.cs @@ -8,4 +8,4 @@ static void Main(string[] args) pizzaGame.Play(); } } -} \ No newline at end of file +} diff --git a/69_Pizza/csharp/StringBuilderExtensions.cs b/69_Pizza/csharp/StringBuilderExtensions.cs index f7cb828d9..d3d769d3c 100644 --- a/69_Pizza/csharp/StringBuilderExtensions.cs +++ b/69_Pizza/csharp/StringBuilderExtensions.cs @@ -18,4 +18,4 @@ public static void AppendLine(this StringBuilder stringBuilder, string value, in } } } -} \ No newline at end of file +} diff --git a/69_Pizza/java/src/Pizza.java b/69_Pizza/java/src/Pizza.java index c3986c810..051bffce3 100644 --- a/69_Pizza/java/src/Pizza.java +++ b/69_Pizza/java/src/Pizza.java @@ -315,4 +315,4 @@ private String displayTextAndGetInput(String text) { return kbScanner.next(); } -} \ No newline at end of file +} diff --git a/69_Pizza/javascript/pizza.js b/69_Pizza/javascript/pizza.js index ba7fe5780..11547b213 100644 --- a/69_Pizza/javascript/pizza.js +++ b/69_Pizza/javascript/pizza.js @@ -12,10 +12,10 @@ function input() { var input_element; var input_str; - + return new Promise(function (resolve) { input_element = document.createElement("INPUT"); - + print("? "); input_element.setAttribute("type", "text"); input_element.setAttribute("length", "50"); diff --git a/69_Pizza/perl/pizza.pl b/69_Pizza/perl/pizza.pl index 7147ad494..8d3e707fb 100755 --- a/69_Pizza/perl/pizza.pl +++ b/69_Pizza/perl/pizza.pl @@ -108,6 +108,3 @@ 2 3 4 - - - diff --git a/69_Pizza/python/pizza.py b/69_Pizza/python/pizza.py index e3804e754..0f59262d1 100644 --- a/69_Pizza/python/pizza.py +++ b/69_Pizza/python/pizza.py @@ -121,7 +121,7 @@ def deliver_to(customer_index, customer_name, player_name): print(f" DRIVER TO {player_name}: WHERE DOES {customer_name} LIVE?") coords = input() - xc, yc = [int(c) for c in coords.split(",")] + xc, yc = (int(c) for c in coords.split(",")) delivery_index = calculate_customer_index(xc, yc) if delivery_index == customer_index: print(f"HELLO {player_name}. THIS IS {customer_name}, THANKS FOR THE PIZZA.") diff --git a/70_Poetry/java/Poetry.java b/70_Poetry/java/Poetry.java index 80be8f216..3b63dc1ea 100644 --- a/70_Poetry/java/Poetry.java +++ b/70_Poetry/java/Poetry.java @@ -6,261 +6,261 @@ *

* Note: The idea was to create a version of the 1970's BASIC game in Java, without introducing * new features - no additional text, error checking, etc has been added. - * + * * Converted from BASIC to Java by Darren Cardenas. */ - + public class Poetry { - + private final static double COMMA_RATE = 0.19; - private final static double SPACE_RATE = 0.65; + private final static double SPACE_RATE = 0.65; private final static int PARAGRAPH_RATE = 20; - + private enum Step { - WORD_GROUP1, WORD_GROUP2, WORD_GROUP3, WORD_GROUP4, RANDOMIZE_COMMA, + WORD_GROUP1, WORD_GROUP2, WORD_GROUP3, WORD_GROUP4, RANDOMIZE_COMMA, RANDOMIZE_WHITESPACE, RANDOMIZE_COUNTERS - } + } public void play() { showIntro(); startGame(); - } // End of method play - - private void showIntro() { - + } // End of method play + + private void showIntro() { + System.out.println(" ".repeat(29) + "POETRY"); System.out.println(" ".repeat(14) + "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY"); System.out.println("\n\n"); - - } // End of method showIntro - private void startGame() { - + } // End of method showIntro + + private void startGame() { + int groupIndex = 0; int paragraphIndex = 0; int punctuationIndex = 0; int wordIndex = 1; - + Step nextStep = Step.WORD_GROUP1; - // Begin outer while loop + // Begin outer while loop while (true) { - + switch (nextStep) { case WORD_GROUP1: - + if (wordIndex == 1) { - + System.out.print("MIDNIGHT DREARY"); nextStep = Step.RANDOMIZE_COMMA; - + } else if (wordIndex == 2) { - + System.out.print("FIERY EYES"); nextStep = Step.RANDOMIZE_COMMA; - + } else if (wordIndex == 3) { - + System.out.print("BIRD OR FIEND"); - nextStep = Step.RANDOMIZE_COMMA; - + nextStep = Step.RANDOMIZE_COMMA; + } else if (wordIndex == 4) { - + System.out.print("THING OF EVIL"); - nextStep = Step.RANDOMIZE_COMMA; - + nextStep = Step.RANDOMIZE_COMMA; + } else if (wordIndex == 5) { - + System.out.print("PROPHET"); - nextStep = Step.RANDOMIZE_COMMA; - } + nextStep = Step.RANDOMIZE_COMMA; + } break; - + case WORD_GROUP2: - + if (wordIndex == 1) { - + System.out.print("BEGUILING ME"); nextStep = Step.RANDOMIZE_COMMA; - + } else if (wordIndex == 2) { - + System.out.print("THRILLED ME"); nextStep = Step.RANDOMIZE_COMMA; - + } else if (wordIndex == 3) { - + System.out.print("STILL SITTING...."); - nextStep = Step.RANDOMIZE_WHITESPACE; - + nextStep = Step.RANDOMIZE_WHITESPACE; + } else if (wordIndex == 4) { - + System.out.print("NEVER FLITTING"); - nextStep = Step.RANDOMIZE_COMMA; - + nextStep = Step.RANDOMIZE_COMMA; + } else if (wordIndex == 5) { - + System.out.print("BURNED"); - nextStep = Step.RANDOMIZE_COMMA; - } + nextStep = Step.RANDOMIZE_COMMA; + } break; case WORD_GROUP3: - + if (wordIndex == 1) { - + System.out.print("AND MY SOUL"); nextStep = Step.RANDOMIZE_COMMA; - + } else if (wordIndex == 2) { - + System.out.print("DARKNESS THERE"); nextStep = Step.RANDOMIZE_COMMA; - + } else if (wordIndex == 3) { - + System.out.print("SHALL BE LIFTED"); - nextStep = Step.RANDOMIZE_COMMA; - + nextStep = Step.RANDOMIZE_COMMA; + } else if (wordIndex == 4) { - + System.out.print("QUOTH THE RAVEN"); - nextStep = Step.RANDOMIZE_COMMA; - + nextStep = Step.RANDOMIZE_COMMA; + } else if (wordIndex == 5) { - + if (punctuationIndex != 0) { - - System.out.print("SIGN OF PARTING"); - } - - nextStep = Step.RANDOMIZE_COMMA; - } - break; - + + System.out.print("SIGN OF PARTING"); + } + + nextStep = Step.RANDOMIZE_COMMA; + } + break; + case WORD_GROUP4: - + if (wordIndex == 1) { - + System.out.print("NOTHING MORE"); nextStep = Step.RANDOMIZE_COMMA; - + } else if (wordIndex == 2) { - + System.out.print("YET AGAIN"); nextStep = Step.RANDOMIZE_COMMA; - + } else if (wordIndex == 3) { - + System.out.print("SLOWLY CREEPING"); - nextStep = Step.RANDOMIZE_WHITESPACE; - + nextStep = Step.RANDOMIZE_WHITESPACE; + } else if (wordIndex == 4) { - + System.out.print("...EVERMORE"); - nextStep = Step.RANDOMIZE_COMMA; - + nextStep = Step.RANDOMIZE_COMMA; + } else if (wordIndex == 5) { - + System.out.print("NEVERMORE"); - nextStep = Step.RANDOMIZE_COMMA; - } - break; - + nextStep = Step.RANDOMIZE_COMMA; + } + break; + case RANDOMIZE_COMMA: - + // Insert commas if ((punctuationIndex != 0) && (Math.random() <= COMMA_RATE)) { - + System.out.print(","); - punctuationIndex = 2; - } + punctuationIndex = 2; + } nextStep = Step.RANDOMIZE_WHITESPACE; break; - - + + case RANDOMIZE_WHITESPACE: // Insert spaces if (Math.random() <= SPACE_RATE) { - - System.out.print(" "); - punctuationIndex++; - - } + + System.out.print(" "); + punctuationIndex++; + + } // Insert newlines - else { - + else { + System.out.println(""); - punctuationIndex = 0; - } + punctuationIndex = 0; + } nextStep = Step.RANDOMIZE_COUNTERS; break; - + case RANDOMIZE_COUNTERS: - + wordIndex = (int)((int)(10 * Math.random()) / 2) + 1; - + groupIndex++; paragraphIndex++; - + if ((punctuationIndex == 0) && (groupIndex % 2 == 0)) { - - System.out.print(" "); + + System.out.print(" "); } - + if (groupIndex == 1) { - - nextStep = Step.WORD_GROUP1; - + + nextStep = Step.WORD_GROUP1; + } else if (groupIndex == 2) { - + nextStep = Step.WORD_GROUP2; - + } else if (groupIndex == 3) { - + nextStep = Step.WORD_GROUP3; - + } else if (groupIndex == 4) { - + nextStep = Step.WORD_GROUP4; - + } else if (groupIndex == 5) { - + groupIndex = 0; System.out.println(""); - + if (paragraphIndex > PARAGRAPH_RATE) { - + System.out.println(""); punctuationIndex = 0; paragraphIndex = 0; - nextStep = Step.WORD_GROUP2; - + nextStep = Step.WORD_GROUP2; + } else { - - nextStep = Step.RANDOMIZE_COUNTERS; - } + + nextStep = Step.RANDOMIZE_COUNTERS; + } } - break; - + break; + default: System.out.println("INVALID STEP"); - break; - } - - } // End outer while loop - + break; + } + + } // End outer while loop + } // End of method startGame - + public static void main(String[] args) { - + Poetry poetry = new Poetry(); poetry.play(); - + } // End of method main } // End of class Poetry diff --git a/70_Poetry/javascript/poetry.js b/70_Poetry/javascript/poetry.js index 885f1921d..612e2eedc 100644 --- a/70_Poetry/javascript/poetry.js +++ b/70_Poetry/javascript/poetry.js @@ -12,10 +12,10 @@ function input() { var input_element; var input_str; - + return new Promise(function (resolve) { input_element = document.createElement("INPUT"); - + print("? "); input_element.setAttribute("type", "text"); input_element.setAttribute("length", "50"); @@ -50,9 +50,9 @@ async function main() print("\n"); print("\n"); print("\n"); - + times = 0; - + i = 1; j = 1; k = 0; diff --git a/70_Poetry/perl/poetry.pl b/70_Poetry/perl/poetry.pl index 610938b6c..585915c49 100755 --- a/70_Poetry/perl/poetry.pl +++ b/70_Poetry/perl/poetry.pl @@ -77,5 +77,3 @@ Line270: print "\n"; $U=0; $K=0; goto Line110; exit; - - diff --git a/70_Poetry/poetry.pl b/70_Poetry/poetry.pl index 610938b6c..585915c49 100755 --- a/70_Poetry/poetry.pl +++ b/70_Poetry/poetry.pl @@ -77,5 +77,3 @@ Line270: print "\n"; $U=0; $K=0; goto Line110; exit; - - diff --git a/71_Poker/javascript/poker.js b/71_Poker/javascript/poker.js index 105da0fa7..73f3c9f0d 100644 --- a/71_Poker/javascript/poker.js +++ b/71_Poker/javascript/poker.js @@ -12,10 +12,10 @@ function input() { var input_element; var input_str; - + return new Promise(function (resolve) { input_element = document.createElement("INPUT"); - + print("? "); input_element.setAttribute("type", "text"); input_element.setAttribute("length", "50"); @@ -254,7 +254,7 @@ function evaluate_hand() function get_prompt(question, def) { var str; - + str = window.prompt(question, def); print(question + "? " + str + "\n"); return str; @@ -339,7 +339,7 @@ function computer_low_in_money() function ask_for_bet() { var forced; - + if (t != Math.floor(t)) { if (k != 0 || g != 0 || t != 0.5) { print("NO SMALL CHANGE, PLEASE.\n"); diff --git a/72_Queen/javascript/queen.js b/72_Queen/javascript/queen.js index 0adee46c5..f07e1dd51 100644 --- a/72_Queen/javascript/queen.js +++ b/72_Queen/javascript/queen.js @@ -12,10 +12,10 @@ function input() { var input_element; var input_str; - + return new Promise(function (resolve) { input_element = document.createElement("INPUT"); - + print("? "); input_element.setAttribute("type", "text"); input_element.setAttribute("length", "50"); @@ -147,7 +147,7 @@ async function main() print("\n"); print("\n"); print("\n"); - + while (1) { print("DO YOU WANT INSTRUCTIONS"); str = await input(); diff --git a/72_Queen/queen.bas b/72_Queen/queen.bas index 9672338c6..e7b808105 100644 --- a/72_Queen/queen.bas +++ b/72_Queen/queen.bas @@ -104,7 +104,7 @@ 3290 REM PLAYER WINS 3300 PRINT 3310 PRINT "C O N G R A T U L A T I O N S . . ." -3320 PRINT +3320 PRINT 3330 PRINT "YOU HAVE WON--VERY WELL PLAYED." 3340 PRINT "IT LOOKS LIKE I HAVE MET MY MATCH." 3350 PRINT "THANKS FOR PLAYING---I CAN'T WIN ALL THE TIME." @@ -130,7 +130,7 @@ 4000 PRINT "ANYONE ELSE CARE TO TRY"; 4010 INPUT Q$ 4020 PRINT -4030 IF Q$="YES" THEN 30 +4030 IF Q$="YES" THEN 30 4040 IF Q$="NO" THEN 4050 4042 PRINT "PLEASE ANSWER 'YES' OR 'NO'." 4045 GOTO 4000 diff --git a/73_Reverse/java/Reverse.java b/73_Reverse/java/Reverse.java index 22c1d0731..603ef7639 100644 --- a/73_Reverse/java/Reverse.java +++ b/73_Reverse/java/Reverse.java @@ -9,43 +9,43 @@ *

* Note: The idea was to create a version of the 1970's BASIC game in Java, without introducing * new features - no additional text, error checking, etc has been added. - * + * * Converted from BASIC to Java by Darren Cardenas. */ - -public class Reverse { - + +public class Reverse { + private final int NUMBER_COUNT = 9; - + private final Scanner scan; // For user input - + private enum Step { INITIALIZE, PERFORM_REVERSE, TRY_AGAIN, END_GAME - } - + } + public Reverse() { - + scan = new Scanner(System.in); - - } // End of constructor Reverse + + } // End of constructor Reverse public void play() { - + showIntro(); startGame(); - - } // End of method play - + + } // End of method play + private static void showIntro() { - + System.out.println(" ".repeat(31) + "REVERSE"); System.out.println(" ".repeat(14) + "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY"); System.out.println("\n\n"); System.out.println("REVERSE -- A GAME OF SKILL"); System.out.println(""); - } // End of method showIntro - + } // End of method showIntro + private void startGame() { int index = 0; @@ -53,162 +53,162 @@ private void startGame() { int numReverse = 0; int tempVal = 0; int[] numList = new int[NUMBER_COUNT + 1]; - + Step nextStep = Step.INITIALIZE; - + String userResponse = ""; - + System.out.print("DO YOU WANT THE RULES? "); userResponse = scan.nextLine(); - + if (!userResponse.toUpperCase().equals("NO")) { - - this.printRules(); + + this.printRules(); } - + // Begin outer while loop while (true) { - + // Begin outer switch switch (nextStep) { - + case INITIALIZE: - - // Make a random list of numbers + + // Make a random list of numbers numList[1] = (int)((NUMBER_COUNT - 1) * Math.random() + 2); - + for (index = 2; index <= NUMBER_COUNT; index++) { - + // Keep generating lists if there are duplicates while (true) { - + numList[index] = (int)(NUMBER_COUNT * Math.random() + 1); // Search for duplicates - if (!this.findDuplicates(numList, index)) { + if (!this.findDuplicates(numList, index)) { break; - } + } } } - + System.out.println(""); System.out.println("HERE WE GO ... THE LIST IS:"); - + numMoves = 0; - + this.printBoard(numList); - + nextStep = Step.PERFORM_REVERSE; break; - + case PERFORM_REVERSE: - + System.out.print("HOW MANY SHALL I REVERSE? "); numReverse = Integer.parseInt(scan.nextLine()); - - if (numReverse == 0) { - - nextStep = Step.TRY_AGAIN; - + + if (numReverse == 0) { + + nextStep = Step.TRY_AGAIN; + } else if (numReverse > NUMBER_COUNT) { - - System.out.println("OOPS! TOO MANY! I CAN REVERSE AT MOST " + NUMBER_COUNT); - nextStep = Step.PERFORM_REVERSE; - + + System.out.println("OOPS! TOO MANY! I CAN REVERSE AT MOST " + NUMBER_COUNT); + nextStep = Step.PERFORM_REVERSE; + } else { - + numMoves++; - + for (index = 1; index <= (int)(numReverse / 2.0); index++) { - + tempVal = numList[index]; numList[index] = numList[numReverse - index + 1]; numList[numReverse - index + 1] = tempVal; } this.printBoard(numList); - + nextStep = Step.TRY_AGAIN; - - // Check for a win + + // Check for a win for (index = 1; index <= NUMBER_COUNT; index++) { - - if (numList[index] != index) { - nextStep = Step.PERFORM_REVERSE; - } + + if (numList[index] != index) { + nextStep = Step.PERFORM_REVERSE; + } } - + if (nextStep == Step.TRY_AGAIN) { - System.out.println("YOU WON IT IN " + numMoves + " MOVES!!!"); + System.out.println("YOU WON IT IN " + numMoves + " MOVES!!!"); System.out.println(""); - } - } + } + } break; - + case TRY_AGAIN: - + System.out.println(""); System.out.print("TRY AGAIN (YES OR NO)? "); userResponse = scan.nextLine(); - + if (userResponse.toUpperCase().equals("YES")) { nextStep = Step.INITIALIZE; } else { nextStep = Step.END_GAME; } break; - + case END_GAME: - + System.out.println(""); System.out.println("O.K. HOPE YOU HAD FUN!!"); - return; - + return; + default: - - System.out.println("INVALID STEP"); + + System.out.println("INVALID STEP"); break; - } // End outer switch - - } // End outer while loop - - } // End of method startGame - + } // End outer switch + + } // End outer while loop + + } // End of method startGame + public boolean findDuplicates(int[] board, int length) { - + int index = 0; - + for (index = 1; index <= length - 1; index++) { - + // Identify duplicates if (board[length] == board[index]) { - + return true; // Found a duplicate - } + } } - + return false; // No duplicates found - + } // End of method findDuplicates - + public void printBoard(int[] board) { - + int index = 0; - + System.out.println(""); - + for (index = 1; index <= NUMBER_COUNT; index++) { - - System.out.format("%2d", board[index]); + + System.out.format("%2d", board[index]); } - - System.out.println("\n"); - + + System.out.println("\n"); + } // End of method printBoard - + public void printRules() { - + System.out.println(""); System.out.println("THIS IS THE GAME OF 'REVERSE'. TO WIN, ALL YOU HAVE"); System.out.println("TO DO IS ARRANGE A LIST OF NUMBERS (1 THROUGH " + NUMBER_COUNT + ")"); @@ -229,14 +229,14 @@ public void printRules() { System.out.println("NO DOUBT YOU WILL LIKE THIS GAME, BUT"); System.out.println("IF YOU WANT TO QUIT, REVERSE 0 (ZERO)."); System.out.println(""); - + } // End of method printRules - + public static void main(String[] args) { - + Reverse game = new Reverse(); game.play(); - + } // End of method main - + } // End of class Reverse diff --git a/73_Reverse/javascript/reverse.js b/73_Reverse/javascript/reverse.js index 44937b518..9e55583bc 100644 --- a/73_Reverse/javascript/reverse.js +++ b/73_Reverse/javascript/reverse.js @@ -12,10 +12,10 @@ function input() { var input_element; var input_str; - + return new Promise(function (resolve) { input_element = document.createElement("INPUT"); - + print("? "); input_element.setAttribute("type", "text"); input_element.setAttribute("length", "50"); diff --git a/73_Reverse/python/reverse.py b/73_Reverse/python/reverse.py index b73c779da..924fe2441 100755 --- a/73_Reverse/python/reverse.py +++ b/73_Reverse/python/reverse.py @@ -2,25 +2,24 @@ import random import textwrap - NUMCNT = 9 # How many numbers are we playing with? def play(): - print('REVERSE'.center(72)) - print('CREATIVE COMPUTING MORRISTOWN, NEW JERSEY'.center(72)) + print("REVERSE".center(72)) + print("CREATIVE COMPUTING MORRISTOWN, NEW JERSEY".center(72)) print() print() - print('REVERSE -- A GAME OF SKILL') + print("REVERSE -- A GAME OF SKILL") print() - if not input('DO YOU WANT THE RULES? (yes/no) ').lower().startswith('n'): + if not input("DO YOU WANT THE RULES? (yes/no) ").lower().startswith("n"): rules() while True: game_loop() - if not input('TRY AGAIN? (yes/no) ').lower().startswith('y'): + if not input("TRY AGAIN? (yes/no) ").lower().startswith("y"): return @@ -32,13 +31,13 @@ def game_loop(): # Print original list and start the game print() - print('HERE WE GO ... THE LIST IS:') + print("HERE WE GO ... THE LIST IS:") print_list(numbers) turns = 0 while True: try: - howmany = int(input('HOW MANY SHALL I REVERSE? ')) + howmany = int(input("HOW MANY SHALL I REVERSE? ")) assert howmany >= 0 except (ValueError, AssertionError): continue @@ -47,7 +46,7 @@ def game_loop(): return if howmany > NUMCNT: - print('OOPS! WRONG! I CAN REVERSE AT MOST', NUMCNT) + print("OOPS! WRONG! I CAN REVERSE AT MOST", NUMCNT) continue turns += 1 @@ -62,19 +61,20 @@ def game_loop(): # Check for a win if all(numbers[i] == i + 1 for i in range(NUMCNT)): - print('YOU WON IT IN {} MOVES!'.format(turns)) + print(f"YOU WON IT IN {turns} MOVES!") print() return def print_list(numbers): """Print out the list""" - print(' '.join(map(str, numbers))) + print(" ".join(map(str, numbers))) def rules(): """Print out the rules""" - help = textwrap.dedent(""" + help = textwrap.dedent( + """ THIS IS THE GAME OF "REVERSE". TO WIN, ALL YOU HAVE TO DO IS ARRANGE A LIST OF NUMBERS (1 THROUGH {}) IN NUMERICAL ORDER FROM LEFT TO RIGHT. TO MOVE, YOU @@ -93,12 +93,15 @@ def rules(): NO DOUBT YOU WILL LIKE THIS GAME, BUT IF YOU WANT TO QUIT, REVERSE 0 (ZERO). - """.format(NUMCNT)) + """.format( + NUMCNT + ) + ) print(help) print() -if __name__ == '__main__': +if __name__ == "__main__": try: play() except KeyboardInterrupt: diff --git a/73_Reverse/ruby/reverse.rb b/73_Reverse/ruby/reverse.rb index 0e2f79346..021eed182 100644 --- a/73_Reverse/ruby/reverse.rb +++ b/73_Reverse/ruby/reverse.rb @@ -55,7 +55,7 @@ def reverseIt (howManyToReverse, triesSoFar) # extract and reverse the first howManyToReverse elements of the array subArray = $digitArray.take(howManyToReverse) subArray.reverse! - + # get the remaining elements of the original array endArray = $digitArray.slice(howManyToReverse, ARRAYSIZE) # append those elements to the reversed elements @@ -108,4 +108,3 @@ def askHowManyToReverse end r = askHowManyToReverse end - diff --git a/74_Rock_Scissors_Paper/java/src/RockScissors.java b/74_Rock_Scissors_Paper/java/src/RockScissors.java index 952cd80ed..2720028a5 100644 --- a/74_Rock_Scissors_Paper/java/src/RockScissors.java +++ b/74_Rock_Scissors_Paper/java/src/RockScissors.java @@ -209,4 +209,4 @@ public static void main(String[] args) { RockScissors rockScissors = new RockScissors(); rockScissors.play(); } -} \ No newline at end of file +} diff --git a/74_Rock_Scissors_Paper/javascript/rockscissors.js b/74_Rock_Scissors_Paper/javascript/rockscissors.js index a5d868621..707712fb4 100644 --- a/74_Rock_Scissors_Paper/javascript/rockscissors.js +++ b/74_Rock_Scissors_Paper/javascript/rockscissors.js @@ -12,10 +12,10 @@ function input() { var input_element; var input_str; - + return new Promise(function (resolve) { input_element = document.createElement("INPUT"); - + print("? "); input_element.setAttribute("type", "text"); input_element.setAttribute("length", "50"); diff --git a/74_Rock_Scissors_Paper/perl/rockscissors.pl b/74_Rock_Scissors_Paper/perl/rockscissors.pl index ac83f5cf2..2f2316519 100755 --- a/74_Rock_Scissors_Paper/perl/rockscissors.pl +++ b/74_Rock_Scissors_Paper/perl/rockscissors.pl @@ -24,7 +24,7 @@ do { print "3=ROCK...2=SCISSORS...1=PAPER\n"; print "1...2...3...WHAT'S YOUR CHOICE? "; chomp($K = ); - if (($K-1)*($K-2)*($K-3)!=0) { print "INVALID.\n"; $K=0; } + if (($K-1)*($K-2)*($K-3)!=0) { print "INVALID.\n"; $K=0; } } until ($K!=0); @@ -52,5 +52,3 @@ print "AND ".($Q-($C+$H))." GAME(S) ENDED IN A TIE.\n"; print "\n"; print "THANKS FOR PLAYING!!\n"; exit; - - diff --git a/74_Rock_Scissors_Paper/python/rockscissors.py b/74_Rock_Scissors_Paper/python/rockscissors.py index 688a894ba..cc56adf69 100644 --- a/74_Rock_Scissors_Paper/python/rockscissors.py +++ b/74_Rock_Scissors_Paper/python/rockscissors.py @@ -76,8 +76,7 @@ def main(): play_game() - keep_playing = input( - "Play again? (yes or no) ").lower().startswith("y") + keep_playing = input("Play again? (yes or no) ").lower().startswith("y") if __name__ == "__main__": diff --git a/74_Rock_Scissors_Paper/ruby/rockscissors.rb b/74_Rock_Scissors_Paper/ruby/rockscissors.rb index 9b24ac9a9..deae2a3fa 100644 --- a/74_Rock_Scissors_Paper/ruby/rockscissors.rb +++ b/74_Rock_Scissors_Paper/ruby/rockscissors.rb @@ -18,7 +18,7 @@ def center_text(text) def ask_for_number_of_games loop do - puts "HOW MANY GAMES" + puts "HOW MANY GAMES" response = STDIN.gets.to_i return response if response > 0 and response < 11 puts "SORRY, BUT WE AREN'T ALLOWED TO PLAY THAT MANY." @@ -58,7 +58,7 @@ def calculate_result(human_move, computer_move) human_move = ask_for_human_move puts "THIS IS MY CHOICE..." puts "...#{MOVE_WORDS[computer_move]}" - + case calculate_result(human_move, computer_move) when 'WIN' puts "YOU WIN!!!" @@ -77,4 +77,3 @@ def calculate_result(human_move, computer_move) puts "YOU HAVE WON #{games_won} GAME(S)." puts "AND #{number_of_games - (games_lost + games_won)} GAME(S) ENDED IN A TIE." puts "THANKS FOR PLAYING!!" - diff --git a/74_Rock_Scissors_Paper/rust/Cargo.toml b/74_Rock_Scissors_Paper/rust/Cargo.toml index cfdc7abed..b5162ec43 100644 --- a/74_Rock_Scissors_Paper/rust/Cargo.toml +++ b/74_Rock_Scissors_Paper/rust/Cargo.toml @@ -7,4 +7,4 @@ edition = "2021" text_io = "0.1.10" strum = "0.24" strum_macros = "0.24" -nanorand = "0.6.1" \ No newline at end of file +nanorand = "0.6.1" diff --git a/74_Rock_Scissors_Paper/rust/README.md b/74_Rock_Scissors_Paper/rust/README.md index 50e88090b..cd7631d46 100644 --- a/74_Rock_Scissors_Paper/rust/README.md +++ b/74_Rock_Scissors_Paper/rust/README.md @@ -1,4 +1,3 @@ Original source downloaded [from Vintage Basic](http://www.vintage-basic.net/games.html) Conversion to [Rust](https://www.rust-lang.org) - diff --git a/75_Roulette/java/README.md b/75_Roulette/java/README.md index bc05d92c5..ffa8a3ef2 100644 --- a/75_Roulette/java/README.md +++ b/75_Roulette/java/README.md @@ -6,5 +6,5 @@ Two versions of Roulette has been contributed. They are indicated within given s - [oop](./oop) - Conversion by Andrew McGuinness (andrew@arobeia.co.uk) - [iterative](./iterative) - Conversion by Thomas Kwashnak ([Github](https://github.com/LittleTealeaf)). - - Implements features from JDK 17. - - Does make use of some object oriented programming, but acts as a more iterative solution. \ No newline at end of file + - Implements features from JDK 17. + - Does make use of some object oriented programming, but acts as a more iterative solution. diff --git a/75_Roulette/java/oop/Bet.java b/75_Roulette/java/oop/Bet.java index 6d9ea48a3..8742ca6b0 100644 --- a/75_Roulette/java/oop/Bet.java +++ b/75_Roulette/java/oop/Bet.java @@ -16,7 +16,7 @@ public boolean isValid() { return ((target > 0) && (target <= 50) && (amount >= 5) && (amount <= 500)); } - + /* utility to return either the odds amount in the case of a win, or zero for a loss */ private int m(boolean isWon, int odds) { return isWon? odds: 0; diff --git a/75_Roulette/java/oop/Roulette.java b/75_Roulette/java/oop/Roulette.java index 77ae3463f..e7f9c4445 100644 --- a/75_Roulette/java/oop/Roulette.java +++ b/75_Roulette/java/oop/Roulette.java @@ -17,7 +17,7 @@ public static void main(String args[]) throws Exception { private BufferedReader reader; private PrintStream writer; - + private int house; // how much money does the house have private int player; // how much money does the player have private Wheel wheel = new Wheel(); @@ -156,7 +156,7 @@ private boolean betAndSpin() throws IOException { HashSet betsMade = new HashSet<>(); // Bet targets already made, so we can spot repeats ArrayList bets = new ArrayList<>(); // All the bets for this round - while (bets.size() < betCount) { + while (bets.size() < betCount) { Bet bet = new Bet(0, 0); // an invalid bet to hold the place while (!bet.isValid()) { // keep asking until it is valid try { diff --git a/75_Roulette/java/oop/Wheel.java b/75_Roulette/java/oop/Wheel.java index 497c8b53d..a454b22c7 100644 --- a/75_Roulette/java/oop/Wheel.java +++ b/75_Roulette/java/oop/Wheel.java @@ -36,7 +36,7 @@ public void spin() { pocket = random.nextInt(38) + 1; } while (random.nextInt(4) > 0); // keep spinning until it stops } - + // The string representation of the number; 1-36, 0, or 00 public String value() { if (pocket == 37) return "0"; diff --git a/75_Roulette/javascript/roulette.js b/75_Roulette/javascript/roulette.js index 7c3399bd4..db153017e 100644 --- a/75_Roulette/javascript/roulette.js +++ b/75_Roulette/javascript/roulette.js @@ -12,10 +12,10 @@ function input() { var input_element; var input_str; - + return new Promise(function (resolve) { input_element = document.createElement("INPUT"); - + print("? "); input_element.setAttribute("type", "text"); input_element.setAttribute("length", "50"); diff --git a/75_Roulette/perl/roulette.pl b/75_Roulette/perl/roulette.pl index ad3ce9652..7cd5de70d 100755 --- a/75_Roulette/perl/roulette.pl +++ b/75_Roulette/perl/roulette.pl @@ -38,21 +38,21 @@ sub main { (*=red) 1* 2 3* - 4 5* 6 + 4 5* 6 7* 8 9* 10 11 12* --------------- -13 14* 15 +13 14* 15 16* 17 18* 19* 20 21* -22 23* 24 +22 23* 24 --------------- 25* 26 27* 28 29 30* -31 32* 33 +31 32* 33 34* 35 36* --------------- - 00 0 + 00 0 Types of bets: diff --git a/75_Roulette/python/roulette.py b/75_Roulette/python/roulette.py index c839adc72..3db638ffb 100644 --- a/75_Roulette/python/roulette.py +++ b/75_Roulette/python/roulette.py @@ -1,11 +1,13 @@ -from datetime import date import random +from datetime import date global RED_NUMBERS RED_NUMBERS = [1, 3, 5, 7, 9, 12, 14, 16, 18, 19, 21, 23, 25, 27, 30, 32, 34, 36] + def print_instructions(): - print(""" + print( + """ THIS IS THE BETTING LAYOUT (*=RED) @@ -53,7 +55,9 @@ def print_instructions(): THE MINIMUM BET IS $5, THE MAXIMUM IS $500. - """) + """ + ) + def query_bets(): """Queries the user to input their bets""" @@ -68,10 +72,10 @@ def query_bets(): bet_Values = [0] * betCount for i in range(betCount): - while(bet_IDs[i] == -1): + while bet_IDs[i] == -1: try: - inString = input("NUMBER " + str(i + 1) + "? ").split(',') - id,val = int(inString[0]),int(inString[1]) + inString = input("NUMBER " + str(i + 1) + "? ").split(",") + id, val = int(inString[0]), int(inString[1]) # check other bet_IDs for j in range(i): @@ -85,12 +89,14 @@ def query_bets(): bet_Values[i] = val except: ... - return bet_IDs,bet_Values + return bet_IDs, bet_Values + -def bet_results(bet_IDs,bet_Values,result): +def bet_results(bet_IDs, bet_Values, result): """Computes the results, prints them, and returns the total net winnings""" total_winnings = 0 - def get_modifier(id,num): + + def get_modifier(id, num): if id == 37 and num <= 12: return 2 elif id == 38 and num > 12 and num <= 24: @@ -121,7 +127,7 @@ def get_modifier(id,num): return -1 for i in range(len(bet_IDs)): - winnings = bet_Values[i] * get_modifier(bet_IDs[i],result) + winnings = bet_Values[i] * get_modifier(bet_IDs[i], result) total_winnings += winnings if winnings >= 0: @@ -131,13 +137,14 @@ def get_modifier(id,num): return winnings + def print_check(amount): """Prints a check of a given amount""" name = input("TO WHOM SHALL I MAKE THE CHECK? ") print("-" * 72) print() - print(" " * 40 + "CHECK NO. " + str(random.randint(0,100))) + print(" " * 40 + "CHECK NO. " + str(random.randint(0, 100))) print(" " * 40 + str(date.today())) print() print("PAY TO THE ORDER OF -----" + name + "----- $" + str(amount)) @@ -147,6 +154,7 @@ def print_check(amount): print(" " * 40 + "----------X-----") print("-" * 72) + def main(): player_balance = 1000 host_balance = 100000 @@ -161,13 +169,13 @@ def main(): print_instructions() while True: - bet_IDs,bet_Values = query_bets() + bet_IDs, bet_Values = query_bets() print("SPINNING") print() print() - val = random.randint(0,38) + val = random.randint(0, 38) if val == 38: print("0") elif val == 37: @@ -178,7 +186,7 @@ def main(): print(str(val) + " BLACK") print() - total_winnings = bet_results(bet_IDs,bet_Values,val) + total_winnings = bet_results(bet_IDs, bet_Values, val) player_balance += total_winnings host_balance -= total_winnings @@ -196,7 +204,6 @@ def main(): if not stringtobool(input("PLAY AGAIN? ")): break - if player_balance <= 0: print("THANKS FOR YOUR MONEY") print("I'LL USE IT TO BUY A SOLID GOLD ROULETTE WHEEL") @@ -207,7 +214,8 @@ def main(): def stringtobool(string): """Converts a string to a bool""" - return string.lower() in ("yes","y","true","t","yes") + return string.lower() in ("yes", "y", "true", "t", "yes") + -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/75_Roulette/roulette.bas b/75_Roulette/roulette.bas index 50b7134ff..461231c0b 100644 --- a/75_Roulette/roulette.bas +++ b/75_Roulette/roulette.bas @@ -6,14 +6,14 @@ 1000 REM-ROULETTE 1010 REM-DAVID JOSLIN 1020 PRINT "WELCOME TO THE ROULETTE TABLE" -1030 PRINT +1030 PRINT 1040 PRINT "DO YOU WANT INSTRUCTIONS"; 1050 INPUT Y$ 1060 IF LEFT$(Y$,1)="N" THEN 1550 1070 PRINT 1080 PRINT "THIS IS THE BETTING LAYOUT" 1090 PRINT " (*=RED)" -1100 PRINT +1100 PRINT 1110 PRINT " 1* 2 3*" 1120 PRINT " 4 5* 6 " 1130 PRINT " 7* 8 9*" @@ -32,21 +32,21 @@ 1260 PRINT " 00 0 " 1270 PRINT 1280 PRINT "TYPES OF BETS" -1290 PRINT +1290 PRINT 1300 PRINT "THE NUMBERS 1 TO 36 SIGNIFY A STRAIGHT BET" 1310 PRINT "ON THAT NUMBER." 1320 PRINT "THESE PAY OFF 35:1" -1330 PRINT +1330 PRINT 1340 PRINT "THE 2:1 BETS ARE:" 1350 PRINT " 37) 1-12 40) FIRST COLUMN" 1360 PRINT " 38) 13-24 41) SECOND COLUMN" 1370 PRINT " 39) 25-36 42) THIRD COLUMN" -1380 PRINT +1380 PRINT 1390 PRINT "THE EVEN MONEY BETS ARE:" 1400 PRINT " 43) 1-18 46) ODD" 1410 PRINT " 44) 19-36 47) RED" 1420 PRINT " 45) EVEN 48) BLACK" -1430 PRINT +1430 PRINT 1440 PRINT " 49)0 AND 50)00 PAY OFF 35:1" 1450 PRINT " NOTE: 0 AND 00 DO NOT COUNT UNDER ANY" 1460 PRINT " BETS EXCEPT THEIR OWN." @@ -55,9 +55,9 @@ 1490 PRINT "AND THE AMOUNT, SEPARATED BY A COMMA." 1500 PRINT "FOR EXAMPLE: TO BET $500 ON BLACK, TYPE 48,500" 1510 PRINT "WHEN I ASK FOR A BET." -1520 PRINT +1520 PRINT 1530 PRINT "THE MINIMUM BET IS $5, THE MAXIMUM IS $500." -1540 PRINT +1540 PRINT 1550 REM-PROGRAM BEGINS HERE 1560 REM-TYPE OF BET(NUMBER) ODDS 1570 REM DON'T NEED TO DIMENSION STRINGS @@ -84,8 +84,8 @@ 1780 A(X)=1 1790 NEXT C 1800 PRINT "SPINNING" -1810 PRINT -1820 PRINT +1810 PRINT +1820 PRINT 1830 S=INT(RND(1)*100) 1840 IF S=0 OR S>38 THEN 1830 1850 X(S)=X(S)+1 @@ -95,7 +95,7 @@ 1890 GOTO 2020 1900 PRINT "0" 1910 GOTO 2020 -1920 RESTORE +1920 RESTORE 1930 FOR I1=1 TO 18 1940 READ R 1950 IF R=S THEN 2000 @@ -160,14 +160,14 @@ 2540 IF S/2<>INT(S/2) AND S<37 THEN 2430 2550 GOTO 2110 2560 REM RED(47) 1:1 -2570 RESTORE +2570 RESTORE 2580 FOR I=1 TO 18 2590 READ R 2600 IF S=R THEN 2430 2610 NEXT I 2620 GOTO 2110 2630 REM BLACK(48) 1:1 -2640 RESTORE +2640 RESTORE 2650 FOR I=1 TO 18 2660 READ R 2670 IF S=R THEN 2110 @@ -185,7 +185,7 @@ 2790 D=D-B(C)*35 2800 P=P+B(C)*35 2810 NEXT C -2820 PRINT +2820 PRINT 2830 PRINT "TOTALS:","ME","YOU" 2840 PRINT " ",D,P 2850 IF P>0 THEN 2880 @@ -202,29 +202,29 @@ 2960 IF P<1 THEN 3190 2970 PRINT "TO WHOM SHALL I MAKE THE CHECK"; 2980 INPUT B$ -2990 PRINT +2990 PRINT 3000 FOR I=1 TO 72: PRINT "-";: NEXT I: REM PRINT 72 DASHES 3010 PRINT TAB(50);"CHECK NO. ";INT(RND(1)*100) -3020 PRINT +3020 PRINT 3030 GOSUB 3230 3040 PRINT TAB(40);M$ -3050 PRINT -3060 PRINT +3050 PRINT +3060 PRINT 3070 PRINT "PAY TO THE ORDER OF-----";B$;"-----$ "; 3080 PRINT P -3090 PRINT -3100 PRINT +3090 PRINT +3100 PRINT 3110 PRINT TAB(10),"THE MEMORY BANK OF NEW YORK" -3120 PRINT +3120 PRINT 3130 PRINT TAB(40),"THE COMPUTER" 3140 PRINT TAB(40)"----------X-----" -3150 PRINT +3150 PRINT 3160 FOR I=1 TO 62: PRINT "-";: NEXT I 3170 PRINT "COME BACK SOON!" 3180 GOTO 3210 3190 PRINT "THANKS FOR YOUR MONEY." 3200 PRINT "I'LL USE IT TO BUY A SOLID GOLD ROULETTE WHEEL" -3210 PRINT +3210 PRINT 3220 GOTO 3420 3230 REM 3240 REM THIS ROUTINE RETURNS THE CURRENT DATE IN M$ diff --git a/76_Russian_Roulette/java/src/RussianRoulette.java b/76_Russian_Roulette/java/src/RussianRoulette.java index 1bbf37bc2..dd799a06a 100644 --- a/76_Russian_Roulette/java/src/RussianRoulette.java +++ b/76_Russian_Roulette/java/src/RussianRoulette.java @@ -140,4 +140,4 @@ public static void main(String[] args) { RussianRoulette russianRoulette = new RussianRoulette(); russianRoulette.play(); } -} \ No newline at end of file +} diff --git a/76_Russian_Roulette/javascript/russianroulette.js b/76_Russian_Roulette/javascript/russianroulette.js index d528cfff7..cb50c6ca8 100644 --- a/76_Russian_Roulette/javascript/russianroulette.js +++ b/76_Russian_Roulette/javascript/russianroulette.js @@ -12,10 +12,10 @@ function input() { var input_element; var input_str; - + return new Promise(function (resolve) { input_element = document.createElement("INPUT"); - + print("? "); input_element.setAttribute("type", "text"); input_element.setAttribute("length", "50"); diff --git a/76_Russian_Roulette/perl/russianroulette.pl b/76_Russian_Roulette/perl/russianroulette.pl index 0fa0cff7b..dbb5ac98a 100755 --- a/76_Russian_Roulette/perl/russianroulette.pl +++ b/76_Russian_Roulette/perl/russianroulette.pl @@ -35,5 +35,3 @@ print "LET SOMEONE ELSE BLOW HIS BRAINS OUT.\n"; goto Line10; exit; - - diff --git a/76_Russian_Roulette/python/russianroulette.py b/76_Russian_Roulette/python/russianroulette.py index bac04dc67..2ace69cd8 100644 --- a/76_Russian_Roulette/python/russianroulette.py +++ b/76_Russian_Roulette/python/russianroulette.py @@ -32,10 +32,10 @@ def parse_input(): correct_input = False while not correct_input: try: - i = int(input('? ')) + i = int(input("? ")) correct_input = True except ValueError: - print('Number expected...') + print("Number expected...") return i @@ -43,8 +43,8 @@ def parse_input(): while True: dead = False n = 0 - print("Type \'1\' to Spin chamber and pull trigger") - print("Type \'2\' to Give up") + print("Type '1' to Spin chamber and pull trigger") + print("Type '2' to Give up") print("Go") while not dead: i = parse_input() diff --git a/77_Salvo/javascript/salvo.js b/77_Salvo/javascript/salvo.js index b75f50880..7fb9d6dfc 100644 --- a/77_Salvo/javascript/salvo.js +++ b/77_Salvo/javascript/salvo.js @@ -12,10 +12,10 @@ function input() { var input_element; var input_str; - + return new Promise(function (resolve) { input_element = document.createElement("INPUT"); - + print("? "); input_element.setAttribute("type", "text"); input_element.setAttribute("length", "50"); diff --git a/77_Salvo/python/salvo.ipynb b/77_Salvo/python/salvo.ipynb index 7b98691b5..f488decd8 100644 --- a/77_Salvo/python/salvo.ipynb +++ b/77_Salvo/python/salvo.ipynb @@ -334,4 +334,4 @@ "source": [] } ] -} \ No newline at end of file +} diff --git a/77_Salvo/python/salvo.py b/77_Salvo/python/salvo.py index 0dd19816a..4de418cae 100644 --- a/77_Salvo/python/salvo.py +++ b/77_Salvo/python/salvo.py @@ -1,5 +1,5 @@ -import re import random +import re ################### # @@ -20,21 +20,25 @@ # length - number of "parts" on the ship that # can be shot # shots - number of shots the ship counts for -SHIPS = [("BATTLESHIP", 5, 3), - ("CRUISER", 3, 2), - ("DESTROYER", 2, 1), - ("DESTROYER", 2, 1)] - -VALID_MOVES = [[-1, 0], # North - [-1, 1], # North East - [0, 1], # East - [1, 1], # South East - [1, 0], # South - [1, -1], # South West - [0, -1], # West - [-1, -1]] # North West - -COORD_REGEX = '[ \t]{0,}(-?[0-9]{1,3})[ \t]{0,},[ \t]{0,}(-?[0-9]{1,2})' +SHIPS = [ + ("BATTLESHIP", 5, 3), + ("CRUISER", 3, 2), + ("DESTROYER", 2, 1), + ("DESTROYER", 2, 1), +] + +VALID_MOVES = [ + [-1, 0], # North + [-1, 1], # North East + [0, 1], # East + [1, 1], # South East + [1, 0], # South + [1, -1], # South West + [0, -1], # West + [-1, -1], +] # North West + +COORD_REGEX = "[ \t]{0,}(-?[0-9]{1,3})[ \t]{0,},[ \t]{0,}(-?[0-9]{1,2})" #################### # @@ -112,8 +116,8 @@ # x: integer between 1 and BOARD_HEIGHT # y: integer between 1 and BOARD WIDTH def random_x_y(): - x = random.randrange(1, BOARD_WIDTH+1) - y = random.randrange(1, BOARD_HEIGHT+1) + x = random.randrange(1, BOARD_WIDTH + 1) + y = random.randrange(1, BOARD_HEIGHT + 1) return (x, y) @@ -217,8 +221,7 @@ def generate_ship_coordinates(ship): # helper function to create a game board # that is blank def create_blank_board(): - return [[None for y in range(BOARD_WIDTH)] - for x in range(BOARD_HEIGHT)] + return [[None for y in range(BOARD_WIDTH)] for x in range(BOARD_HEIGHT)] # print_board @@ -228,19 +231,19 @@ def create_blank_board(): def print_board(board): # print board header (column numbers) - print(' ', end='') + print(" ", end="") for z in range(BOARD_WIDTH): - print(f'{z+1:3}', end='') - print('') + print(f"{z+1:3}", end="") + print("") for x in range(len(board)): - print(f'{x+1:2}', end='') + print(f"{x+1:2}", end="") for y in range(len(board[x])): - if(board[x][y] is None): - print(f"{' ':3}", end='') + if board[x][y] is None: + print(f"{' ':3}", end="") else: - print(f"{board[x][y]:3}", end='') - print('') + print(f"{board[x][y]:3}", end="") + print("") # place_ship @@ -256,7 +259,7 @@ def print_board(board): # ship - integer repreesnting the type of ship (given in SHIPS) def place_ship(board, coords, ship): for coord in coords: - board[coord[0]-1][coord[1]-1] = ship + board[coord[0] - 1][coord[1] - 1] = ship # NOTE: A little quirk that exists here and in the orginal @@ -274,7 +277,7 @@ def generate_board(): coords = generate_ship_coordinates(ship) clear = True for coord in coords: - if board[coord[0]-1][coord[1]-1] is not None: + if board[coord[0] - 1][coord[1] - 1] is not None: clear = False break if clear: @@ -292,12 +295,12 @@ def generate_board(): def execute_shot(turn, board, x, y): global current_turn - square = board[x-1][y-1] + square = board[x - 1][y - 1] ship_hit = -1 if square is not None: if square >= 0 and square < len(SHIPS): ship_hit = square - board[x-1][y-1] = 10 + current_turn + board[x - 1][y - 1] = 10 + current_turn return ship_hit @@ -310,7 +313,7 @@ def calculate_shots(board): ships_found = [0 for x in range(len(SHIPS))] for x in range(BOARD_HEIGHT): for y in range(BOARD_WIDTH): - square = board[x-1][y-1] + square = board[x - 1][y - 1] if square is not None: if square >= 0 and square < len(SHIPS): ships_found[square] = 1 @@ -340,12 +343,12 @@ def initialize_game(): computer_board, computer_ship_coords = generate_board() # print out the title 'screen' - print('{0:>38}'.format("SALVO")) - print('{0:>57s}'.format("CREATIVE COMPUTING MORRISTOWN, NEW JERSEY")) - print('') - print('{0:>52s}'.format("ORIGINAL BY LAWRENCE SIEGEL, 1973")) - print('{0:>56s}'.format("PYTHON 3 PORT BY TODD KAISER, MARCH 2021")) - print('\n') + print("{:>38}".format("SALVO")) + print("{:>57s}".format("CREATIVE COMPUTING MORRISTOWN, NEW JERSEY")) + print("") + print("{:>52s}".format("ORIGINAL BY LAWRENCE SIEGEL, 1973")) + print("{:>56s}".format("PYTHON 3 PORT BY TODD KAISER, MARCH 2021")) + print("\n") # ask the player for ship coordinates print("ENTER COORDINATES FOR...") @@ -376,7 +379,7 @@ def initialize_game(): for coord in coords: x = coord[0] y = coord[1] - print('{0:2}'.format(x), '{0:2}'.format(y)) + print(f"{x:2}", f"{y:2}") else: input_loop = False @@ -453,7 +456,7 @@ def execute_turn(turn): x, y = random_x_y() else: x, y = input_coord() - square = board[x-1][y-1] + square = board[x - 1][y - 1] if square is not None: if square > 10: if turn == PLAYER: @@ -477,7 +480,6 @@ def execute_turn(turn): else: print("YOU HIT MY", SHIPS[hit][0]) - if turn == COMPUTER: num_player_shots = calculate_shots(board) return num_player_shots diff --git a/78_Sine_Wave/csharp/Program.cs b/78_Sine_Wave/csharp/Program.cs index 6f44f8d52..69b2dee6e 100644 --- a/78_Sine_Wave/csharp/Program.cs +++ b/78_Sine_Wave/csharp/Program.cs @@ -12,4 +12,4 @@ isCreative = !isCreative; } -static string Tab(int n) => new string(' ', n); \ No newline at end of file +static string Tab(int n) => new string(' ', n); diff --git a/78_Sine_Wave/python/sinewave.py b/78_Sine_Wave/python/sinewave.py index d1d0024d8..edb1e03b0 100644 --- a/78_Sine_Wave/python/sinewave.py +++ b/78_Sine_Wave/python/sinewave.py @@ -21,16 +21,17 @@ # ######################################################## -import math, time +import math +import time # Constants -STRINGS = ('Creative', 'Computing') # Text to display +STRINGS = ("Creative", "Computing") # Text to display MAX_LINES = 160 -STEP_SIZE = 0.25 # Number of radians to increase at each - # line. Controls speed of horizontal - # printing movement. -CENTER = 26 # Controls left edge of "middle" string -DELAY = 0.05 # Amount of seconds to wait between lines +STEP_SIZE = 0.25 # Number of radians to increase at each +# line. Controls speed of horizontal +# printing movement. +CENTER = 26 # Controls left edge of "middle" string +DELAY = 0.05 # Amount of seconds to wait between lines # Display "intro" text @@ -46,10 +47,10 @@ # "Start long loop" for line_num in range(MAX_LINES): - + # Get string to display on this line curr_string = STRINGS[string_index] - + # Calculate how far over to print the text sine = math.sin(radians) padding = int(CENTER + width * sine) @@ -65,7 +66,6 @@ time.sleep(DELAY) - ######################################################## # # Porting Notes @@ -106,10 +106,3 @@ # What happens? Why? How would you fix it? # ######################################################## - - - - - - - diff --git a/78_Sine_Wave/ruby/sinewave.rb b/78_Sine_Wave/ruby/sinewave.rb index 001e2cd8a..6cb19cd9f 100644 --- a/78_Sine_Wave/ruby/sinewave.rb +++ b/78_Sine_Wave/ruby/sinewave.rb @@ -12,4 +12,4 @@ def main end end -main \ No newline at end of file +main diff --git a/79_Slalom/README.md b/79_Slalom/README.md index e76ead943..9a9d2605c 100644 --- a/79_Slalom/README.md +++ b/79_Slalom/README.md @@ -17,8 +17,7 @@ http://www.vintage-basic.net/games.html ### Bugs -- In the original version, the data pointer doesn't reset after a race is completed. This causes subsequent races to +- In the original version, the data pointer doesn't reset after a race is completed. This causes subsequent races to error at some future point at line 540, 540 READ Q - diff --git a/79_Slalom/csharp/program.cs b/79_Slalom/csharp/program.cs index 2d3b07d94..df70ba426 100644 --- a/79_Slalom/csharp/program.cs +++ b/79_Slalom/csharp/program.cs @@ -114,7 +114,7 @@ private int PromptForRate() { Success = true; } - else + else { Console.WriteLine("The bounds are 1-3"); } @@ -157,7 +157,7 @@ private int PromptForOption() return Option; } - + private string PromptForCommand() { bool Success = false; @@ -204,7 +204,7 @@ private bool ExceedGateSpeed(double MaxGateSpeed, double MPH, double Time) } else { - if (rand.NextDouble() < 0.5) + if (rand.NextDouble() < 0.5) { Console.WriteLine("snagged a flag!"); } @@ -217,11 +217,11 @@ private bool ExceedGateSpeed(double MaxGateSpeed, double MPH, double Time) return false; } - } + } else if (MPH > (MaxGateSpeed - 1)) { Console.WriteLine("Close one!"); - } + } return true; } @@ -234,7 +234,7 @@ private void DoARun(int NumberOfGates, int Rating) double MaxGateSpeed = 0; // Q double PreviousMPH = 0; double Medals = 0; - + Console.WriteLine("The starter counts down...5...4...3...2...1...GO!"); MPH = rand.NextDouble() * (18-9)+9; @@ -253,7 +253,7 @@ private void DoARun(int NumberOfGates, int Rating) PreviousMPH = MPH; Option = PromptForOption(); - while (Option == 0) + while (Option == 0) { Console.WriteLine("You've taken {0:N2} seconds.", Time); Option = PromptForOption(); @@ -430,4 +430,4 @@ static void Main(string[] args) } } -} \ No newline at end of file +} diff --git a/79_Slalom/java/Slalom.java b/79_Slalom/java/Slalom.java index 4b0c947d2..aaff59a40 100644 --- a/79_Slalom/java/Slalom.java +++ b/79_Slalom/java/Slalom.java @@ -370,4 +370,4 @@ public int getBronze() { } -} \ No newline at end of file +} diff --git a/79_Slalom/javascript/slalom.js b/79_Slalom/javascript/slalom.js index 7944e62e0..196ddb5dd 100644 --- a/79_Slalom/javascript/slalom.js +++ b/79_Slalom/javascript/slalom.js @@ -12,10 +12,10 @@ function input() { var input_element; var input_str; - + return new Promise(function (resolve) { input_element = document.createElement("INPUT"); - + print("? "); input_element.setAttribute("type", "text"); input_element.setAttribute("length", "50"); @@ -88,7 +88,7 @@ async function main() var gold = 0; var silver = 0; var bronze = 0; - + print(tab(33) + "SLALOM\n"); print(tab(15) + "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY\n"); print("\n"); diff --git a/80_Slots/csharp/README.md b/80_Slots/csharp/README.md index 4983614ce..32f406f89 100644 --- a/80_Slots/csharp/README.md +++ b/80_Slots/csharp/README.md @@ -2,7 +2,7 @@ Original source downloaded [from Vintage Basic](http://www.vintage-basic.net/gam Conversion to [Microsoft C#](https://docs.microsoft.com/en-us/dotnet/csharp/) -This C# implementation of slots was done using a [C# script](https://github.com/filipw/dotnet-script). +This C# implementation of slots was done using a [C# script](https://github.com/filipw/dotnet-script). # Required [.NET Core SDK (i.e., .NET 6.0)](https://dotnet.microsoft.com/en-us/download) @@ -15,4 +15,4 @@ dotnet tool install -g dotnet-script # Run ``` dotnet script .\slots.csx -``` \ No newline at end of file +``` diff --git a/80_Slots/csharp/slots.csx b/80_Slots/csharp/slots.csx index b812d9425..5c2ff5ccd 100644 --- a/80_Slots/csharp/slots.csx +++ b/80_Slots/csharp/slots.csx @@ -49,7 +49,7 @@ public void Play() } } else if(x == y) - { + { if(y == Slot.BAR) { DoubleBar(bet); @@ -57,7 +57,7 @@ public void Play() else { Double(bet); - } + } } else if(x == z) { diff --git a/80_Slots/javascript/slots.js b/80_Slots/javascript/slots.js index 2bafd26ed..93c860b4f 100644 --- a/80_Slots/javascript/slots.js +++ b/80_Slots/javascript/slots.js @@ -12,10 +12,10 @@ function input() { var input_element; var input_str; - + return new Promise(function (resolve) { input_element = document.createElement("INPUT"); - + print("? "); input_element.setAttribute("type", "text"); input_element.setAttribute("length", "50"); diff --git a/80_Slots/python/slots.py b/80_Slots/python/slots.py index fbae665b3..6af1bcbd0 100644 --- a/80_Slots/python/slots.py +++ b/80_Slots/python/slots.py @@ -31,15 +31,15 @@ # ######################################################## -from random import choices -from collections import Counter import sys +from collections import Counter +from random import choices def initial_message(): - print(" "*30 + "Slots") - print(" "*15 + "Creative Computing Morrison, New Jersey") - print("\n"*3) + print(" " * 30 + "Slots") + print(" " * 15 + "Creative Computing Morrison, New Jersey") + print("\n" * 3) print("You are in the H&M Casino, in front of one of our") print("one-arm Bandits. Bet from $1 to $100.") print("To pull the arm, punch the return key after making your bet.") @@ -65,7 +65,7 @@ def beeping(): # Function to produce a beep sound. # In the original program is the subroutine at line 1270 for _ in range(5): - sys.stdout.write('\a') + sys.stdout.write("\a") sys.stdout.flush() @@ -89,10 +89,10 @@ def adjust_profits(wheel, m, profits): if fruit == "Bar": print("\n***Jackpot***") - profits = (((100*m)+m)+profits) + profits = ((100 * m) + m) + profits else: print("\n**Top Dollar**") - profits = (((10*m)+m)+profits) + profits = ((10 * m) + m) + profits print("You Won!") elif len(s) == 2: @@ -103,10 +103,10 @@ def adjust_profits(wheel, m, profits): if fruit == "Bar": print("\n*Double Bar*") - profits = (((5*m)+m)+profits) + profits = ((5 * m) + m) + profits else: print("\nDouble!!") - profits = (((2*m)+m)+profits) + profits = ((2 * m) + m) + profits print("You Won!") else: @@ -135,7 +135,7 @@ def final_message(profits): w = spin_wheels() profits = adjust_profits(w, m, profits) - print("Your standings are ${}".format(profits)) + print(f"Your standings are ${profits}") answer = input("Again?") try: diff --git a/80_Slots/ruby/slots.rb b/80_Slots/ruby/slots.rb index a4c3e7ef0..1e6fc22d3 100644 --- a/80_Slots/ruby/slots.rb +++ b/80_Slots/ruby/slots.rb @@ -91,7 +91,7 @@ def win winType, bet else # valid bet, continue tenBells # ding - + # assign a random value from the array to each of the three reels reel1 = reelArray[rand(5)] reel2 = reelArray[rand(5)] diff --git a/80_Slots/slots.bas b/80_Slots/slots.bas index 2d1b84d4a..ef7ed841d 100644 --- a/80_Slots/slots.bas +++ b/80_Slots/slots.bas @@ -12,7 +12,7 @@ 180 IF M>100 THEN 860 190 IF M<1 THEN 880 200 M=INT(M) -210 GOSUB 1270 +210 GOSUB 1270 220 PRINT 230 LET X=INT(6*RND(1)+1) 240 LET Y=INT(6*RND(1)+1) @@ -118,7 +118,7 @@ 1240 GOTO 450 1250 PRINT" CHERRY" 1260 GOTO 450 -1270 FOR Q4=1 TO 10 +1270 FOR Q4=1 TO 10 1280 PRINT CHR$(7); 1290 NEXT Q4 1300 RETURN diff --git a/81_Splat/csharp/Program.cs b/81_Splat/csharp/Program.cs index a128ef0f5..6ca973a41 100644 --- a/81_Splat/csharp/Program.cs +++ b/81_Splat/csharp/Program.cs @@ -112,7 +112,7 @@ private void WriteSuccessfulResults(double Distance) else { int JumpPosition = DistanceLog.IndexOf(Distance); - + if (ArrayLength - JumpPosition <= .1 * ArrayLength) { @@ -155,13 +155,13 @@ private void PlayOneRound() { bool InputSuccess = false; Random rand = new Random(); - double Velocity = 0; - double TerminalVelocity = 0; - double Acceleration = 0; - double AccelerationInput = 0; - double Altitude = ((9001 * rand.NextDouble()) + 1000); - double SecondsTimer = 0; - double Distance = 0; + double Velocity = 0; + double TerminalVelocity = 0; + double Acceleration = 0; + double AccelerationInput = 0; + double Altitude = ((9001 * rand.NextDouble()) + 1000); + double SecondsTimer = 0; + double Distance = 0; bool TerminalVelocityReached = false; Console.WriteLine(""); @@ -177,7 +177,7 @@ private void PlayOneRound() InputSuccess = double.TryParse(Input, out TerminalVelocity); if (!InputSuccess) Console.WriteLine("*** Please enter a valid number ***"); - } + } } else { @@ -203,7 +203,7 @@ private void PlayOneRound() InputSuccess = double.TryParse(Input, out AccelerationInput); if (!InputSuccess) Console.WriteLine("*** Please enter a valid number ***"); - } + } } else { @@ -232,7 +232,7 @@ private void PlayOneRound() InputSuccess = double.TryParse(Input, out SecondsTimer); if (!InputSuccess) Console.WriteLine("*** Please enter a valid number ***"); - } + } // Begin the drop! Console.WriteLine("Here we go."); @@ -240,9 +240,9 @@ private void PlayOneRound() WriteColumnOutput("Time (sec)", "Dist to Fall (ft)"); WriteColumnOutput("==========", "================="); - + // Loop through the number of seconds stepping by 8 intervals - for (double i = 0; i < SecondsTimer; i+=(SecondsTimer/8)) + for (double i = 0; i < SecondsTimer; i+=(SecondsTimer/8)) { if (i > (Velocity / Acceleration)) { @@ -294,17 +294,17 @@ private void PlayOneRound() // Store succesful jump and write out a fun message WriteSuccessfulResults(Distance); - } + } } public void PlayTheGame() { bool ContinuePlay = false; - + DisplayIntro(); - do + do { PlayOneRound(); @@ -327,4 +327,4 @@ static void Main(string[] args) } } -} \ No newline at end of file +} diff --git a/81_Splat/java/src/Splat.java b/81_Splat/java/src/Splat.java index e042c326c..e28a2bb8d 100644 --- a/81_Splat/java/src/Splat.java +++ b/81_Splat/java/src/Splat.java @@ -354,4 +354,4 @@ float getTimeOfTerminalAccelerationReached() { return terminalVelocity / acceleration; } } -} \ No newline at end of file +} diff --git a/81_Splat/javascript/splat.js b/81_Splat/javascript/splat.js index e037d1907..8b51786bc 100644 --- a/81_Splat/javascript/splat.js +++ b/81_Splat/javascript/splat.js @@ -12,10 +12,10 @@ function input() { var input_element; var input_str; - + return new Promise(function (resolve) { input_element = document.createElement("INPUT"); - + print("? "); input_element.setAttribute("type", "text"); input_element.setAttribute("length", "50"); diff --git a/81_Splat/perl/splat.pl b/81_Splat/perl/splat.pl index eebfcb6b1..6114e7fc7 100755 --- a/81_Splat/perl/splat.pl +++ b/81_Splat/perl/splat.pl @@ -21,7 +21,7 @@ Welcome to 'Splat' -- the game that simulates a parachute -jump. Try to open your chute at the last possible +jump. Try to open your chute at the last possible moment without going splat. EOD @@ -115,8 +115,8 @@ if ( $fractile <= 0.1 ) { print <<"EOD"; Wow! That's some jumping. Of the $jumps successful jumps -before yours, only $better opened their chutes lower than -you did. +before yours, only $better opened their chutes lower than +you did. EOD } elsif ( $fractile <= 0.25 ) { print <<"EOD"; @@ -126,7 +126,7 @@ EOD } elsif ( $fractile <= 0.5 ) { print <<"EOD"; -Not bad. There have been $jumps successful jumps before yours. +Not bad. There have been $jumps successful jumps before yours. You were beaten out by $better of them. EOD } elsif ( $fractile <= 0.75 ) { @@ -136,7 +136,7 @@ EOD } elsif ( $fractile <= 0.9 ) { print <<"EOD"; -Humph! Don't you have any sporting blood? There were +Humph! Don't you have any sporting blood? There were $jumps successful jumps before yours and you came in $worse jumps better than the worst. Shape up!!! EOD diff --git a/81_Splat/python/splat.py b/81_Splat/python/splat.py index 6e08083bc..909151e25 100644 --- a/81_Splat/python/splat.py +++ b/81_Splat/python/splat.py @@ -137,7 +137,7 @@ def jump(): # here, the displacement is just a function of the terminal # velocity and the time passed after having reached terminal # velocity: d2 = v * (t - t_reached_term_vel) - d1 = (v ** 2) / (2 * a) + d1 = (v**2) / (2 * a) d2 = v * (t - (v / a)) altitude = initial_altitude - (d1 + d2) if altitude <= 0: @@ -160,7 +160,7 @@ def jump(): # From the second equation of motion, # d = v_0 * t + 0.5 * a * t^2, with v_0 = 0, we can get # the displacement using d1 = a / 2 * t^2 - d1 = (a / 2) * (t ** 2) + d1 = (a / 2) * (t**2) altitude = initial_altitude - d1 if altitude <= 0: # Time taken for an object to fall to the ground given that @@ -206,7 +206,7 @@ def jump_stats(previous_jumps, chute_altitude): the current jump is better. """ n_previous_jumps = len(previous_jumps) - n_better = sum([1 for pj in previous_jumps if chute_altitude < pj]) + n_better = sum(1 for pj in previous_jumps if chute_altitude < pj) return n_previous_jumps, n_better diff --git a/81_Splat/splat.bas b/81_Splat/splat.bas index a3aba0362..8561f6345 100644 --- a/81_Splat/splat.bas +++ b/81_Splat/splat.bas @@ -3,122 +3,122 @@ 40 PRINT:PRINT:PRINT 50 DIM A(42) 95 PRINT "WELCOME TO 'SPLAT' -- THE GAME THAT SIMULATES A PARACHUTE" -96 PRINT "JUMP. TRY TO OPEN YOUR CHUTE AT THE LAST POSSIBLE" +96 PRINT "JUMP. TRY TO OPEN YOUR CHUTE AT THE LAST POSSIBLE" 97 PRINT "MOMENT WITHOUT GOING SPLAT." 118 PRINT:PRINT:D1=0:V=0:A=0:N=0:M=0:D1=INT(9001*RND(1)+1000) -119 PRINT "SELECT YOUR OWN TERMINAL VELOCITY (YES OR NO)";:INPUT A1$ +119 PRINT "SELECT YOUR OWN TERMINAL VELOCITY (YES OR NO)";:INPUT A1$ 120 IF A1$="NO" THEN 128 121 IF A1$<>"YES" THEN PRINT "YES OR NO";:INPUT A1$:GOTO 120 -123 PRINT "WHAT TERMINAL VELOCITY (MI/HR)";:INPUT V1 +123 PRINT "WHAT TERMINAL VELOCITY (MI/HR)";:INPUT V1 125 V1=V1*(5280/3600):V=V1+((V1*RND(1))/20)-((V1*RND(1))/20):GOTO 135 128 V1=INT(1000*RND(1)) 130 PRINT "OK. TERMINAL VELOCITY ="V1"MI/HR" -131 V1=V1*(5280/3600):V=V1+((V1*RND(1))/20)-((V1*RND(1))/20) -135 PRINT "WANT TO SELECT ACCELERATION DUE TO GRAVITY (YES OR NO)"; +131 V1=V1*(5280/3600):V=V1+((V1*RND(1))/20)-((V1*RND(1))/20) +135 PRINT "WANT TO SELECT ACCELERATION DUE TO GRAVITY (YES OR NO)"; 136 INPUT B1$ 140 IF B1$="NO" THEN 150 141 IF B1$<>"YES" THEN PRINT "YES OR NO";:INPUT B1$:GOTO 140 -143 PRINT "WHAT ACCELERATION (FT/SEC/SEC)";:INPUT A2 +143 PRINT "WHAT ACCELERATION (FT/SEC/SEC)";:INPUT A2 145 A=A2+((A2*RND(1))/20)-((A2*RND(1))/20):GOTO 205 -150 ON INT(1+(10*RND(1)))GOTO 151,152,153,154,155,156,157,158,159,160 +150 ON INT(1+(10*RND(1)))GOTO 151,152,153,154,155,156,157,158,159,160 151 PRINT"FINE. YOU'RE ON MERCURY. ACCELERATION=12.2 FT/SEC/SEC.":GOTO 161 152 PRINT"ALL RIGHT. YOU'RE ON VENUS. ACCELERATION=28.3 FT/SEC/SEC.":GOTO 162 -153 PRINT "THEN YOU'RE ON EARTH. ACCELERATION=32.16 FT/SEC/SEC.":GOTO 163 +153 PRINT "THEN YOU'RE ON EARTH. ACCELERATION=32.16 FT/SEC/SEC.":GOTO 163 154 PRINT"FINE. YOU'RE ON THE MOON. ACCELERATION=5.15 FT/SEC/SEC.":GOTO 164 -155 PRINT"ALL RIGHT. YOU'RE ON MARS. ACCELERATION=12.5 FT/SEC/SEC.":GOTO 165 +155 PRINT"ALL RIGHT. YOU'RE ON MARS. ACCELERATION=12.5 FT/SEC/SEC.":GOTO 165 156 PRINT"THEN YOU'RE ON JUPITER. ACCELERATION=85.2 FT/SEC/SEC.":GOTO 166 157 PRINT"FINE. YOU'RE ON SATURN. ACCELERATION=37.6 FT/SEC/SEC.":GOTO 167 -158 PRINT"ALL RIGHT. YOU'RE ON URANUS. ACCELERATION=33.8 FT/SEC/SEC.":GOTO 168 +158 PRINT"ALL RIGHT. YOU'RE ON URANUS. ACCELERATION=33.8 FT/SEC/SEC.":GOTO 168 159 PRINT"THEN YOU'RE ON NEPTUNE. ACCELERATION=39.6 FT/SEC/SEC.":GOTO 169 160 PRINT"FINE. YOU'RE ON THE SUN. ACCELERATION=896 FT/SEC/SEC.":GOTO 170 -161 A2=12.2:GOTO 145 -162 A2=28.3:GOTO 145 +161 A2=12.2:GOTO 145 +162 A2=28.3:GOTO 145 163 A2=32.16:GOTO 145 -164 A2=5.15:GOTO 145 -165 A2=12.5:GOTO 145 -166 A2=85.2:GOTO 145 -167 A2=37.6:GOTO 145 +164 A2=5.15:GOTO 145 +165 A2=12.5:GOTO 145 +166 A2=85.2:GOTO 145 +167 A2=37.6:GOTO 145 168 A2=33.8 :GOTO 145 -169 A2=39.6:GOTO 145 +169 A2=39.6:GOTO 145 170 A2=896:GOTO 145 205 PRINT -206 PRINT " ALTITUDE ="D1"FT" +206 PRINT " ALTITUDE ="D1"FT" 207 PRINT " TERM. VELOCITY ="V1"FT/SEC +/-5%" 208 PRINT " ACCELERATION ="A2"FT/SEC/SEC +/-5%" 210 PRINT "SET THE TIMER FOR YOUR FREEFALL." 211 PRINT "HOW MANY SECONDS";:INPUT T 215 PRINT "HERE WE GO." 217 PRINT -218 PRINT "TIME (SEC)","DIST TO FALL (FT)" -219 PRINT "==========","=================" +218 PRINT "TIME (SEC)","DIST TO FALL (FT)" +219 PRINT "==========","=================" 300 FOR I=0 TO T STEP (T/8) 310 IF I>V/A THEN 400 -320 D=D1-((A/2)*I^2) +320 D=D1-((A/2)*I^2) 330 IF D<=0 THEN 1000 340 PRINT I,D -350 NEXT I -360 GOTO 500 +350 NEXT I +360 GOTO 500 400 PRINT "TERMINAL VELOCITY REACHED AT T PLUS"V/A"SECONDS." 405 FOR I=I TO T STEP (T/8) -410 D=D1-((V^2/(2*A))+(V*(I-(V/A)))) +410 D=D1-((V^2/(2*A))+(V*(I-(V/A)))) 420 IF D<=0 THEN 1010 430 PRINT I,D -440 NEXT I +440 NEXT I 500 PRINT "CHUTE OPEN" -510 K=0:K1=0 +510 K=0:K1=0 550 FOR J=0 TO 42 -555 IF A(J)=0 THEN 620 +555 IF A(J)=0 THEN 620 560 K=K+1 570 IF D>=A(J) THEN 600 580 K1=K1+1 -600 NEXT J -610 GOTO 540 -620 A(J)=D +600 NEXT J +610 GOTO 540 +620 A(J)=D 630 IF J>2 THEN 650 635 PRINT "AMAZING!!! NOT BAD FOR YOUR "; 636 IF J=0 THEN PRINT "1ST "; 637 IF J=1 THEN PRINT "2ND "; 638 IF J=2 THEN PRINT "3RD "; 639 PRINT "SUCCESSFUL JUMP!!!":GOTO 2000 -650 IF K-K1<=.1*K THEN 700 +650 IF K-K1<=.1*K THEN 700 660 IF K-K1<=.25*K THEN 710 -670 IF K-K1<=.5*K THEN 720 +670 IF K-K1<=.5*K THEN 720 680 IF K-K1<=.75*K THEN 730 -690 IF K-K1<=.9*K THEN 740 -695 GOTO 750 +690 IF K-K1<=.9*K THEN 740 +695 GOTO 750 700 PRINT "WOW! THAT'S SOME JUMPING. OF THE"K"SUCCESSFUL JUMPS" -701 PRINT "BEFORE YOURS, ONLY"K-K1"OPENED THEIR CHUTES LOWER THAN" -702 PRINT "YOU DID." +701 PRINT "BEFORE YOURS, ONLY"K-K1"OPENED THEIR CHUTES LOWER THAN" +702 PRINT "YOU DID." 703 GOTO 2000 710 PRINT "PRETTY GOOD! " K"SUCCESSFUL JUMPS PRECEDED YOURS AND ONLY" 711 PRINT K-K1" OF THEM GOT LOWER THAN YOU DID BEFORE THEIR CHUTES" -712 PRINT "OPENED." :GOTO 2000 -720 PRINT "NOT BAD. THERE HAVE BEEN"K"SUCCESSFUL JUMPS BEFORE YOURS." -721 PRINT"YOU WERE BEATEN OUT BY"K-K1"OF THEM.":GOTO 2000 +712 PRINT "OPENED." :GOTO 2000 +720 PRINT "NOT BAD. THERE HAVE BEEN"K"SUCCESSFUL JUMPS BEFORE YOURS." +721 PRINT"YOU WERE BEATEN OUT BY"K-K1"OF THEM.":GOTO 2000 730 PRINT "CONSERVATIVE, AREN'T YOU? YOU RANKED ONLY"K-K1"IN THE" 731 PRINT K"SUCCESSFUL JUMPS BEFORE YOURS.":GOTO 2000 -740 PRINT "HUMPH! DON'T YOU HAVE ANY SPORTING BLOOD? THERE WERE" +740 PRINT "HUMPH! DON'T YOU HAVE ANY SPORTING BLOOD? THERE WERE" 741 PRINT K"SUCCESSFUL JUMPS BEFORE YOURS AND YOU CAME IN"K1"JUMPS" 742 PRINT "BETTER THAN THE WORST. SHAPE UP!!!":GOTO 2000 750 PRINT "HEY! YOU PULLED THE RIP CORD MUCH TOO SOON. "K"SUCCESSFUL" -751 PRINT "JUMPS BEFORE YOURS AND YOU CAME IN NUMBER"K-K1"! GET WITH IT!" +751 PRINT "JUMPS BEFORE YOURS AND YOU CAME IN NUMBER"K-K1"! GET WITH IT!" 752 GOTO 2000 800 PRINT "REQUIESCAT IN PACE.":GOTO 1950 -801 PRINT "MAY THE ANGEL OF HEAVEN LEAD YOU INTO PARADISE.":GOTO 1950 +801 PRINT "MAY THE ANGEL OF HEAVEN LEAD YOU INTO PARADISE.":GOTO 1950 802 PRINT "REST IN PEACE.":GOTO 1950 -803 PRINT "SON-OF-A-GUN.":GOTO 1950 -804 PRINT "#$%&&%!$":GOTO 1950 +803 PRINT "SON-OF-A-GUN.":GOTO 1950 +804 PRINT "#$%&&%!$":GOTO 1950 805 PRINT "A KICK IN THE PANTS IS A BOOST IF YOU'RE HEADED RIGHT.":GOTO 1950 -806 PRINT "HMMM. SHOULD HAVE PICKED A SHORTER TIME.":GOTO 1950 +806 PRINT "HMMM. SHOULD HAVE PICKED A SHORTER TIME.":GOTO 1950 807 PRINT "MUTTER. MUTTER. MUTTER.":GOTO 1950 -808 PRINT "PUSHING UP DAISIES.":GOTO 1950 -809 PRINT "EASY COME, EASY GO.":GOTO 1950 +808 PRINT "PUSHING UP DAISIES.":GOTO 1950 +809 PRINT "EASY COME, EASY GO.":GOTO 1950 1000 PRINT SQR(2*D1/A),"SPLAT" 1005 ON INT(1+(10*RND(1)))GOTO 800,801,802,803,804,805,806,807,808,809 1010 PRINT (V/A)+((D1-(V^2/(2*A)))/V),"SPLAT" 1020 GOTO 1005 1950 PRINT "I'LL GIVE YOU ANOTHER CHANCE.":GOTO 2000 -2000 PRINT "DO YOU WANT TO PLAY AGAIN";:INPUT Z$ +2000 PRINT "DO YOU WANT TO PLAY AGAIN";:INPUT Z$ 2001 IF Z$="YES" THEN 118 2002 IF Z$="NO" THEN 2005 2003 PRINT "YES OR NO":GOTO 2000 diff --git a/82_Stars/csharp/Game.cs b/82_Stars/csharp/Game.cs index 7045fe4bf..9711dd828 100644 --- a/82_Stars/csharp/Game.cs +++ b/82_Stars/csharp/Game.cs @@ -91,4 +91,4 @@ private void DisplayLoss(int target) Console.WriteLine($"Sorry, that's {_maxGuessCount} guesses. The number was {target}."); } } -} \ No newline at end of file +} diff --git a/82_Stars/java/src/Stars.java b/82_Stars/java/src/Stars.java index 75e7cdd6a..b9cf641a1 100644 --- a/82_Stars/java/src/Stars.java +++ b/82_Stars/java/src/Stars.java @@ -239,4 +239,4 @@ private int randomNumber() { return (int) (Math.random() * (HIGH_NUMBER_RANGE) + 1); } -} \ No newline at end of file +} diff --git a/82_Stars/javascript/stars.js b/82_Stars/javascript/stars.js index 5ffdd761d..15a92ca14 100644 --- a/82_Stars/javascript/stars.js +++ b/82_Stars/javascript/stars.js @@ -12,10 +12,10 @@ function input() { var input_element; var input_str; - + return new Promise(function (resolve) { input_element = document.createElement("INPUT"); - + print("? "); input_element.setAttribute("type", "text"); input_element.setAttribute("length", "50"); @@ -71,7 +71,7 @@ async function main() var loss = true; print("\nOK, I AM THINKING OF A NUMBER, START GUESSING.\n\n"); - + for(var guessNum=1; guessNum <= guesses; guessNum++) { // Input guess @@ -105,4 +105,4 @@ async function main() } } -main(); \ No newline at end of file +main(); diff --git a/82_Stars/python/stars.py b/82_Stars/python/stars.py index 7b4cbfa14..d35538efc 100644 --- a/82_Stars/python/stars.py +++ b/82_Stars/python/stars.py @@ -56,8 +56,7 @@ def get_guess(): if guess.isdigit(): valid_response = True guess = int(guess) - return(guess) - + return guess # Display intro text @@ -69,7 +68,7 @@ def get_guess(): response = input("Do you want instructions? ") if response.upper()[0] == "Y": print_instructions() - + still_playing = True while still_playing: @@ -82,33 +81,32 @@ def get_guess(): player_has_won = False while (guess_number < MAX_GUESSES) and not player_has_won: - print("") - guess = get_guess() - guess_number += 1 + print("") + guess = get_guess() + guess_number += 1 - if guess == secret_number: - # "*** We have a winner" - player_has_won = True - print("*************************" + - "*************************!!!") - print("You got it in %d guesses!!!" % guess_number) + if guess == secret_number: + # "*** We have a winner" + player_has_won = True + print("*************************" + "*************************!!!") + print("You got it in %d guesses!!!" % guess_number) - else: - print_stars(secret_number, guess) + else: + print_stars(secret_number, guess) - # End of guess loop + # End of guess loop # "*** Did not guess in [MAX_GUESS] guesses" if not player_has_won: - print("\nSorry, that's %d guesses, number was %d" % - (guess_number, secret_number)) + print( + "\nSorry, that's %d guesses, number was %d" % (guess_number, secret_number) + ) # Keep playing? response = input("\nPlay again? ") if response.upper()[0] != "Y": still_playing = False - ###################################################################### # @@ -132,10 +130,3 @@ def get_guess(): # Hard = 6 guesses, 1 to 200 # ###################################################################### - - - - - - - diff --git a/82_Stars/stars.bas b/82_Stars/stars.bas index 3290cbbd4..0536ed3a7 100644 --- a/82_Stars/stars.bas +++ b/82_Stars/stars.bas @@ -41,7 +41,7 @@ 520 PRINT 530 NEXT K 540 REM *** DID NOT GUESS IN M GUESSES -550 PRINT +550 PRINT 560 PRINT "SORRY, THAT'S";M;"GUESSES. THE NUMBER WAS";X 580 GOTO 650 590 REM *** WE HAVE A WINNER diff --git a/83_Stock_Market/java/StockMarket.java b/83_Stock_Market/java/StockMarket.java index 142f6fb68..3eb883e91 100644 --- a/83_Stock_Market/java/StockMarket.java +++ b/83_Stock_Market/java/StockMarket.java @@ -423,4 +423,4 @@ public String toString() { } } -} \ No newline at end of file +} diff --git a/83_Stock_Market/javascript/stockmarket.js b/83_Stock_Market/javascript/stockmarket.js index fbcbd8a5b..69af32f92 100644 --- a/83_Stock_Market/javascript/stockmarket.js +++ b/83_Stock_Market/javascript/stockmarket.js @@ -12,10 +12,10 @@ function input() { var input_element; var input_str; - + return new Promise(function (resolve) { input_element = document.createElement("INPUT"); - + print("? "); input_element.setAttribute("type", "text"); input_element.setAttribute("length", "50"); diff --git a/83_Stock_Market/python/Stock_Market.py b/83_Stock_Market/python/Stock_Market.py index 98386cc1a..3c53e3573 100644 --- a/83_Stock_Market/python/Stock_Market.py +++ b/83_Stock_Market/python/Stock_Market.py @@ -1,153 +1,171 @@ import random -#Stock_Market -class Stock_Market(): - - def __init__(self): - - #Hard Coded Names - short_names = ['IBM', 'RCA', 'LBJ', 'ABC', 'CBS'] - full_names = ['INT. BALLISTIC MISSLES', 'RED CROSS OF AMERICA', - 'LICHTENSTEIN, BUMRAP & JOKE', 'AMERICAN BANKRUPT CO.', - 'CENSURED BOOKS STORE'] - - #Initializing Dictionary to hold all the information systematically - self.data = {} - for sn, fn in zip(short_names, full_names): - #A dictionary for each stock - temp = {'Name' : fn, 'Price' : None, 'Holdings' : 0} - #Nested outer dictionary for all stocks - self.data[sn] = temp - - #Initializing Randomly generated initial prices - for stock in self.data.values(): - stock['Price'] = round(random.uniform(80,120),2) #Price b/w 60 and 120 - - #Initialize Assets - self.cash_assets = 10000 - self.stock_assets = 0 - - def total_assets(self): - - return self.cash_assets + self.stock_assets - - def _generate_day_change(self): - - self.changes = [] - for _ in range(len(self.data)): - self.changes.append(round(random.uniform(-5,5),2)) #Random % Change b/w -5 and 5 - - def update_prices(self): - - self._generate_day_change() - for stock, change in zip(self.data.values(), self.changes): - stock['Price'] = round(stock['Price'] + (change/100)*stock['Price'], 2) - - def print_exchange_average(self): - - sum = 0 - for stock in self.data.values(): - sum += stock['Price'] - - print('\nNEW YORK STOCK EXCHANGE AVERAGE: ${:.2f}'.format(sum/5)) - - def get_average_change(self): - - sum = 0 - for change in self.changes: - sum += change - - return round(sum/5,2) - - def print_first_day(self): - - print('\nSTOCK\t\t\t\t\tINITIALS\tPRICE/SHARE($)') - for stock, data in self.data.items(): - if stock != 'LBJ': - print('{}\t\t\t{}\t\t{}'.format(data['Name'], stock, data['Price'])) - else: - print('{}\t\t{}\t\t{}'.format(data['Name'], stock, data['Price'])) - - self.print_exchange_average() - self.print_assets() - - def take_inputs(self): - - print('\nWHAT IS YOUR TRANSACTION IN') - flag = False - while flag != True: - new_holdings = [] - for stock in self.data.keys(): - try: - new_holdings.append(int(input('{}? '.format(stock)))) - except: - print('\nINVALID ENTRY, TRY AGAIN\n') - break - if len(new_holdings) == 5: - flag = self._check_transaction(new_holdings) - - return new_holdings - - def print_trading_day(self): - - print("STOCK\tPRICE/SHARE\tHOLDINGS\tNET. Value\tPRICE CHANGE") - for stock, data, change in zip(self.data.keys(), self.data.values(),self.changes): - value = data['Price'] * data['Holdings'] - print('{}\t{}\t\t{}\t\t{:.2f}\t\t{}'.format(stock, data['Price'], data['Holdings'], value, change)) - - def update_cash_assets(self, new_holdings): - - sell=0 - buy=0 - for stock, holding in zip(self.data.values(), new_holdings): - if holding > 0: - buy += stock['Price']*holding - - elif holding < 0: - sell += stock['Price']*abs(holding) - - self.cash_assets = self.cash_assets + sell - buy - - def update_stock_assets(self): - - sum=0 - for data in self.data.values(): - sum += data['Price']*data['Holdings'] - - self.stock_assets = round(sum,2) - def print_assets(self): +# Stock_Market +class Stock_Market: + def __init__(self): + + # Hard Coded Names + short_names = ["IBM", "RCA", "LBJ", "ABC", "CBS"] + full_names = [ + "INT. BALLISTIC MISSLES", + "RED CROSS OF AMERICA", + "LICHTENSTEIN, BUMRAP & JOKE", + "AMERICAN BANKRUPT CO.", + "CENSURED BOOKS STORE", + ] - print('\nTOTAL STOCK ASSETS ARE: ${:.2f}'.format(self.stock_assets)) - print('TOTAL CASH ASSETS ARE: ${:.2f}'.format(self.cash_assets)) - print('TOTAL ASSETS ARE: ${:.2f}'.format(self.total_assets())) + # Initializing Dictionary to hold all the information systematically + self.data = {} + for sn, fn in zip(short_names, full_names): + # A dictionary for each stock + temp = {"Name": fn, "Price": None, "Holdings": 0} + # Nested outer dictionary for all stocks + self.data[sn] = temp - def _check_transaction(self, new_holdings): + # Initializing Randomly generated initial prices + for stock in self.data.values(): + stock["Price"] = round(random.uniform(80, 120), 2) # Price b/w 60 and 120 - sum = 0 - for stock, holding in zip(self.data.values(), new_holdings): - if holding > 0: - sum += stock['Price']*holding - - elif holding < 0: - if abs(holding) > stock['Holdings']: - print('\nYOU HAVE OVERSOLD SOME STOCKS, TRY AGAIN\n') - return False + # Initialize Assets + self.cash_assets = 10000 + self.stock_assets = 0 - if sum > self.cash_assets: - print('\nYOU HAVE USED ${:.2f} MORE THAN YOU HAVE, TRY AGAIN\n'.format(sum - self.cash_assets)) - return False + def total_assets(self): - return True + return self.cash_assets + self.stock_assets - def update_holdings(self, new_holdings): + def _generate_day_change(self): + + self.changes = [] + for _ in range(len(self.data)): + self.changes.append( + round(random.uniform(-5, 5), 2) + ) # Random % Change b/w -5 and 5 + + def update_prices(self): + + self._generate_day_change() + for stock, change in zip(self.data.values(), self.changes): + stock["Price"] = round(stock["Price"] + (change / 100) * stock["Price"], 2) + + def print_exchange_average(self): + + sum = 0 + for stock in self.data.values(): + sum += stock["Price"] + + print(f"\nNEW YORK STOCK EXCHANGE AVERAGE: ${sum / 5:.2f}") + + def get_average_change(self): + + sum = 0 + for change in self.changes: + sum += change + + return round(sum / 5, 2) + + def print_first_day(self): + + print("\nSTOCK\t\t\t\t\tINITIALS\tPRICE/SHARE($)") + for stock, data in self.data.items(): + if stock != "LBJ": + print("{}\t\t\t{}\t\t{}".format(data["Name"], stock, data["Price"])) + else: + print("{}\t\t{}\t\t{}".format(data["Name"], stock, data["Price"])) + + self.print_exchange_average() + self.print_assets() + + def take_inputs(self): + + print("\nWHAT IS YOUR TRANSACTION IN") + flag = False + while flag != True: + new_holdings = [] + for stock in self.data.keys(): + try: + new_holdings.append(int(input(f"{stock}? "))) + except: + print("\nINVALID ENTRY, TRY AGAIN\n") + break + if len(new_holdings) == 5: + flag = self._check_transaction(new_holdings) + + return new_holdings + + def print_trading_day(self): + + print("STOCK\tPRICE/SHARE\tHOLDINGS\tNET. Value\tPRICE CHANGE") + for stock, data, change in zip( + self.data.keys(), self.data.values(), self.changes + ): + value = data["Price"] * data["Holdings"] + print( + "{}\t{}\t\t{}\t\t{:.2f}\t\t{}".format( + stock, data["Price"], data["Holdings"], value, change + ) + ) + + def update_cash_assets(self, new_holdings): + + sell = 0 + buy = 0 + for stock, holding in zip(self.data.values(), new_holdings): + if holding > 0: + buy += stock["Price"] * holding + + elif holding < 0: + sell += stock["Price"] * abs(holding) + + self.cash_assets = self.cash_assets + sell - buy + + def update_stock_assets(self): + + sum = 0 + for data in self.data.values(): + sum += data["Price"] * data["Holdings"] + + self.stock_assets = round(sum, 2) + + def print_assets(self): + + print(f"\nTOTAL STOCK ASSETS ARE: ${self.stock_assets:.2f}") + print(f"TOTAL CASH ASSETS ARE: ${self.cash_assets:.2f}") + print(f"TOTAL ASSETS ARE: ${self.total_assets():.2f}") + + def _check_transaction(self, new_holdings): + + sum = 0 + for stock, holding in zip(self.data.values(), new_holdings): + if holding > 0: + sum += stock["Price"] * holding + + elif holding < 0: + if abs(holding) > stock["Holdings"]: + print("\nYOU HAVE OVERSOLD SOME STOCKS, TRY AGAIN\n") + return False + + if sum > self.cash_assets: + print( + "\nYOU HAVE USED ${:.2f} MORE THAN YOU HAVE, TRY AGAIN\n".format( + sum - self.cash_assets + ) + ) + return False + + return True + + def update_holdings(self, new_holdings): + + for stock, new_holding in zip(self.data.values(), new_holdings): + stock["Holdings"] += new_holding - for stock, new_holding in zip(self.data.values(), new_holdings): - stock['Holdings'] += new_holding def print_instruction(): - print(''' + print( + """ THIS PROGRAM PLAYS THE STOCK MARKET. YOU WILL BE GIVEN $10,000 AND MAY BUY OR SELL STOCKS. THE STOCK PRICES WILL BE GENERATED RANDOMLY AND THEREFORE THIS MODEL DOES NOT @@ -164,45 +182,47 @@ def print_instruction(): (NOTE: TO GET A 'FEEL' FOR THE MARKET RUN FOR AT LEAST 10 DAYS) ------------GOOD LUCK!------------\n - ''') - + """ + ) + + if __name__ == "__main__": - - print('\t\t STOCK MARKET') - help = input('\nDO YOU WANT INSTRUCTIONS(YES OR NO)? ') - - #Printing Instruction - if help == 'YES' or help == 'yes' or help == 'Yes': - print_instruction() - - #Initialize Game - Game = Stock_Market() - - #Do first day - Game.print_first_day() - new_holdings = Game.take_inputs() - Game.update_holdings(new_holdings) - Game.update_cash_assets(new_holdings) - print('\n------------END OF TRADING DAY--------------\n') - - response = 1 - while response == 1: - - #Simulate a DAY - Game.update_prices() - Game.print_trading_day() - Game.print_exchange_average() - Game.update_stock_assets() - Game.print_assets() - - response = int(input('\nDO YOU WISH TO CONTINUE (YES-TYPE 1, NO-TYPE 0)? ')) - if response == 0: - break - + + print("\t\t STOCK MARKET") + help = input("\nDO YOU WANT INSTRUCTIONS(YES OR NO)? ") + + # Printing Instruction + if help == "YES" or help == "yes" or help == "Yes": + print_instruction() + + # Initialize Game + Game = Stock_Market() + + # Do first day + Game.print_first_day() new_holdings = Game.take_inputs() Game.update_holdings(new_holdings) Game.update_cash_assets(new_holdings) - print('\n------------END OF TRADING DAY--------------\n') + print("\n------------END OF TRADING DAY--------------\n") + + response = 1 + while response == 1: + + # Simulate a DAY + Game.update_prices() + Game.print_trading_day() + Game.print_exchange_average() + Game.update_stock_assets() + Game.print_assets() + + response = int(input("\nDO YOU WISH TO CONTINUE (YES-TYPE 1, NO-TYPE 0)? ")) + if response == 0: + break + + new_holdings = Game.take_inputs() + Game.update_holdings(new_holdings) + Game.update_cash_assets(new_holdings) + print("\n------------END OF TRADING DAY--------------\n") - print('\nHOPE YOU HAD FUN!!!!') - input('') + print("\nHOPE YOU HAD FUN!!!!") + input("") diff --git a/83_Stock_Market/stockmarket.bas b/83_Stock_Market/stockmarket.bas index 5d81e62f7..402b6360b 100644 --- a/83_Stock_Market/stockmarket.bas +++ b/83_Stock_Market/stockmarket.bas @@ -2,107 +2,107 @@ 20 PRINT TAB(15);"CREATIVE COMPUTING MORRISTOWN, NEW JERSEY" 30 PRINT: PRINT: PRINT 100 REM STOCK MARKET SIMULATION -STOCK- -101 REM REVISED 8/18/70 (D. PESSEL, L. BRAUN, C. LOSIK) -102 REM IMP VRBLS: A-MRKT TRND SLP; B5-BRKRGE FEE; C-TTL CSH ASSTS; +101 REM REVISED 8/18/70 (D. PESSEL, L. BRAUN, C. LOSIK) +102 REM IMP VRBLS: A-MRKT TRND SLP; B5-BRKRGE FEE; C-TTL CSH ASSTS; 103 REM C5-TTL CSH ASSTS (TEMP); C(I)-CHNG IN STK VAL; D-TTL ASSTS; -104 REM E1,E2-LRG CHNG MISC; I-STCK #; I1,I2-STCKS W LRG CHNG; +104 REM E1,E2-LRG CHNG MISC; I-STCK #; I1,I2-STCKS W LRG CHNG; 105 REM N1,N2-LRG CHNG DAY CNTS; P5-TTL DAYS PRCHSS; P(I)-PRTFL CNTNTS; -106 REM Q9-NEW CYCL?; S4-SGN OF A; S5-TTL DYS SLS; S(I)-VALUE/SHR; +106 REM Q9-NEW CYCL?; S4-SGN OF A; S5-TTL DYS SLS; S(I)-VALUE/SHR; 107 REM T-TTL STCK ASSTS; T5-TTL VAL OF TRNSCTNS; 108 REM W3-LRG CHNG; X1-SMLL CHNG(<$1); Z4,Z5,Z6-NYSE AVE.; Z(I)-TRNSCT -110 DIM S(5),P(5),Z(5),C(5) -112 REM SLOPE OF MARKET TREND:A (SAME FOR ALL STOCKS) +110 DIM S(5),P(5),Z(5),C(5) +112 REM SLOPE OF MARKET TREND:A (SAME FOR ALL STOCKS) 113 LET X=1 -114 LET A=INT((RND(X)/10)*100+.5)/100 +114 LET A=INT((RND(X)/10)*100+.5)/100 115 LET T5=0 116 LET X9=0 117 LET N1=0 118 LET N2=0 119 LET E1=0 120 LET E2=0 -121 REM INTRODUCTION -122 PRINT "DO YOU WANT THE INSTRUCTIONS (YES-TYPE 1, NO-TYPE 0)"; +121 REM INTRODUCTION +122 PRINT "DO YOU WANT THE INSTRUCTIONS (YES-TYPE 1, NO-TYPE 0)"; 123 INPUT Z9 -124 PRINT -125 PRINT +124 PRINT +125 PRINT 126 IF Z9<1 THEN 200 -130 PRINT "THIS PROGRAM PLAYS THE STOCK MARKET. YOU WILL BE GIVEN" +130 PRINT "THIS PROGRAM PLAYS THE STOCK MARKET. YOU WILL BE GIVEN" 132 PRINT "$10,000 AND MAY BUY OR SELL STOCKS. THE STOCK PRICES WILL" -134 PRINT "BE GENERATED RANDOMLY AND THEREFORE THIS MODEL DOES NOT" +134 PRINT "BE GENERATED RANDOMLY AND THEREFORE THIS MODEL DOES NOT" 135 PRINT "REPRESENT EXACTLY WHAT HAPPENS ON THE EXCHANGE. A TABLE" 136 PRINT "OF AVAILABLE STOCKS, THEIR PRICES, AND THE NUMBER OF SHARES" -137 PRINT "IN YOUR PORTFOLIO WILL BE PRINTED. FOLLOWING THIS, THE" +137 PRINT "IN YOUR PORTFOLIO WILL BE PRINTED. FOLLOWING THIS, THE" 138 PRINT "INITIALS OF EACH STOCK WILL BE PRINTED WITH A QUESTION" -139 PRINT "MARK. HERE YOU INDICATE A TRANSACTION. TO BUY A STOCK" -140 PRINT "TYPE +NNN, TO SELL A STOCK TYPE -NNN, WHERE NNN IS THE" +139 PRINT "MARK. HERE YOU INDICATE A TRANSACTION. TO BUY A STOCK" +140 PRINT "TYPE +NNN, TO SELL A STOCK TYPE -NNN, WHERE NNN IS THE" 141 PRINT "NUMBER OF SHARES. A BROKERAGE FEE OF 1% WILL BE CHARGED" 142 PRINT "ON ALL TRANSACTIONS. NOTE THAT IF A STOCK'S VALUE DROPS" 143 PRINT "TO ZERO IT MAY REBOUND TO A POSITIVE VALUE AGAIN. YOU" 144 PRINT "HAVE $10,000 TO INVEST. USE INTEGERS FOR ALL YOUR INPUTS." -145 PRINT "(NOTE: TO GET A 'FEEL' FOR THE MARKET RUN FOR AT LEAST" +145 PRINT "(NOTE: TO GET A 'FEEL' FOR THE MARKET RUN FOR AT LEAST" 146 PRINT "10 DAYS)" 147 PRINT "-----GOOD LUCK!-----" -200 REM GENERATION OF STOCK TABLE; INPUT REQUESTS -210 REM INITIAL STOCK VALUES +200 REM GENERATION OF STOCK TABLE; INPUT REQUESTS +210 REM INITIAL STOCK VALUES 220 LET S(1)=100 -230 LET S(2)=85 +230 LET S(2)=85 240 LET S(3)=150 250 LET S(4)=140 260 LET S(5)=110 265 REM INITIAL T8 - # DAYS FOR FIRST TREND SLOPE (A) -266 LET T8=INT(4.99*RND(X)+1) +266 LET T8=INT(4.99*RND(X)+1) 267 REM RANDOMIZE SIGN OF FIRST TREND SLOPE (A) -268 IF RND(X)>.5 THEN 270 +268 IF RND(X)>.5 THEN 270 269 LET A=-A -270 REM RANDOMIZE INITIAL VALUES -280 GOSUB 830 -285 REM INITIAL PORTFOLIO CONTENTS +270 REM RANDOMIZE INITIAL VALUES +280 GOSUB 830 +285 REM INITIAL PORTFOLIO CONTENTS 290 FOR I=1 TO 5 300 LET P(I)=0 305 LET Z(I)=0 310 NEXT I -320 PRINT -330 PRINT -333 REM INITIALIZE CASH ASSETS:C -335 LET C=10000 +320 PRINT +330 PRINT +333 REM INITIALIZE CASH ASSETS:C +335 LET C=10000 338 REM PRINT INITIAL PORTFOLIO 340 PRINT "STOCK"," ","INITIALS","PRICE/SHARE" 350 PRINT "INT. BALLISTIC MISSILES"," IBM",S(1) -352 PRINT "RED CROSS OF AMERICA"," RCA",S(2) +352 PRINT "RED CROSS OF AMERICA"," RCA",S(2) 354 PRINT "LICHTENSTEIN, BUMRAP & JOKE"," LBJ",S(3) 356 PRINT "AMERICAN BANKRUPT CO."," ABC",S(4) -358 PRINT "CENSURED BOOKS STORE"," CBS",S(5) -360 PRINT -361 REM NYSE AVERAGE:Z5; TEMP. VALUE:Z4; NET CHANGE:Z6 -363 LET Z4=Z5 +358 PRINT "CENSURED BOOKS STORE"," CBS",S(5) +360 PRINT +361 REM NYSE AVERAGE:Z5; TEMP. VALUE:Z4; NET CHANGE:Z6 +363 LET Z4=Z5 364 LET Z5=0 -365 LET T=0 +365 LET T=0 370 FOR I=1 TO 5 375 LET Z5=Z5+S(I) -380 LET T=T+S(I)*P(I) +380 LET T=T+S(I)*P(I) 390 NEXT I -391 LET Z5=INT(100*(Z5/5)+.5)/100 +391 LET Z5=INT(100*(Z5/5)+.5)/100 392 LET Z6=INT((Z5-Z4)*100+.5)/100 -393 REM TOTAL ASSETS:D -394 LET D=T+C +393 REM TOTAL ASSETS:D +394 LET D=T+C 395 IF X9>0 THEN 398 -396 PRINT "NEW YORK STOCK EXCHANGE AVERAGE: "Z5 -397 GOTO 399 +396 PRINT "NEW YORK STOCK EXCHANGE AVERAGE: "Z5 +397 GOTO 399 398 PRINT "NEW YORK STOCK EXCHANGE AVERAGE: "Z5"NET CHANGE"Z6 -399 PRINT -400 LET T=INT(100*T+.5)/100 +399 PRINT +400 LET T=INT(100*T+.5)/100 401 PRINT "TOTAL STOCK ASSETS ARE $";T -403 LET C=INT(100*C+.5)/100 +403 LET C=INT(100*C+.5)/100 405 PRINT "TOTAL CASH ASSETS ARE $";C -407 LET D=INT(100*D+.5)/100 +407 LET D=INT(100*D+.5)/100 408 PRINT "TOTAL ASSETS ARE $";D -410 PRINT +410 PRINT 411 IF X9=0 THEN 416 412 PRINT "DO YOU WISH TO CONTINUE (YES-TYPE 1, NO-TYPE 0)"; 413 INPUT Q9 414 IF Q9<1 THEN 998 -416 REM INPUT TRANSACTIONS -420 PRINT "WHAT IS YOUR TRANSACTION IN" +416 REM INPUT TRANSACTIONS +420 PRINT "WHAT IS YOUR TRANSACTION IN" 430 PRINT "IBM"; 440 INPUT Z(1) 450 PRINT "RCA"; @@ -113,44 +113,44 @@ 500 INPUT Z(4) 510 PRINT "CBS"; 520 INPUT Z(5) -525 PRINT +525 PRINT 530 REM TOTAL DAY'S PURCHASES IN $:P5 540 LET P5=0 550 REM TOTAL DAY'S SALES IN $:S5 560 LET S5=0 570 FOR I=1 TO 5 -575 LET Z(I)=INT(Z(I)+.5) -580 IF Z(I)<=0 THEN 610 -590 LET P5=P5+Z(I)*S(I) -600 GOTO 620 -610 LET S5=S5-Z(I)*S(I) -612 IF -Z(I)<=P(I) THEN 620 -614 PRINT "YOU HAVE OVERSOLD A STOCK; TRY AGAIN." -616 GOTO 420 +575 LET Z(I)=INT(Z(I)+.5) +580 IF Z(I)<=0 THEN 610 +590 LET P5=P5+Z(I)*S(I) +600 GOTO 620 +610 LET S5=S5-Z(I)*S(I) +612 IF -Z(I)<=P(I) THEN 620 +614 PRINT "YOU HAVE OVERSOLD A STOCK; TRY AGAIN." +616 GOTO 420 620 NEXT I -622 REM TOTAL VALUE OF TRANSACTIONS:T5 +622 REM TOTAL VALUE OF TRANSACTIONS:T5 625 LET T5=P5+S5 -630 REM BROKERAGE FEE:B5 -640 LET B5=INT(.01*T5*100+.5)/100 +630 REM BROKERAGE FEE:B5 +640 LET B5=INT(.01*T5*100+.5)/100 650 REM CASH ASSETS=OLD CASH ASSETS-TOTAL PURCHASES -652 REM -BROKERAGE FEES+TOTAL SALES:C5 -654 LET C5=C-P5-B5+S5 -656 IF C5>=0 THEN 674 -658 PRINT "YOU HAVE USED $"-C5" MORE THAN YOU HAVE." +652 REM -BROKERAGE FEES+TOTAL SALES:C5 +654 LET C5=C-P5-B5+S5 +656 IF C5>=0 THEN 674 +658 PRINT "YOU HAVE USED $"-C5" MORE THAN YOU HAVE." 660 GOTO 420 674 LET C=C5 -675 REM CALCULATE NEW PORTFOLIO +675 REM CALCULATE NEW PORTFOLIO 680 FOR I=1 TO 5 690 LET P(I)=P(I)+Z(I) 700 NEXT I -710 REM CALCULATE NEW STOCK VALUES -720 GOSUB 830 +710 REM CALCULATE NEW STOCK VALUES +720 GOSUB 830 750 REM PRINT PORTFOLIO -751 REM BELL RINGING-DIFFERENT ON MANY COMPUTERS -755 PRINT +751 REM BELL RINGING-DIFFERENT ON MANY COMPUTERS +755 PRINT 756 PRINT "********** END OF DAY'S TRADING **********" -757 PRINT -758 PRINT +757 PRINT +758 PRINT 759 IF X9<1 THEN 769 769 PRINT "STOCK","PRICE/SHARE","HOLDINGS", "VALUE", "NET PRICE CHANGE" 770 PRINT "IBM", S(1), P(1), S(1)*P(1), C(1) @@ -159,72 +159,72 @@ 773 PRINT "ABC", S(4), P(4), S(4)*P(4), C(4) 774 PRINT "CBS", S(5), P(5), S(5)*P(5), C(5) 775 LET X9=1 -780 PRINT -790 PRINT -810 GOTO 360 +780 PRINT +790 PRINT +810 GOTO 360 829 REM NEW STOCK VALUES - SUBROUTINE 830 REM RANDOMLY PRODUCE NEW STOCK VALUES BASED ON PREVIOUS -831 REM DAY'S VALUES +831 REM DAY'S VALUES 832 REM N1,N2 ARE RANDOM NUMBERS OF DAYS WHICH RESPECTIVELY 833 REM DETERMINE WHEN STOCK I1 WILL INCREASE 10 PTS. AND STOCK -834 REM I2 WILL DECREASE 10 PTS. -840 REM IF N1 DAYS HAVE PASSED, PICK AN I1, SET E1, DETERMINE NEW N1 +834 REM I2 WILL DECREASE 10 PTS. +840 REM IF N1 DAYS HAVE PASSED, PICK AN I1, SET E1, DETERMINE NEW N1 841 IF N1>0 THEN 850 -845 LET I1=INT(4.99*RND(X)+1) -846 LET N1=INT(4.99*RND(X)+1) +845 LET I1=INT(4.99*RND(X)+1) +846 LET N1=INT(4.99*RND(X)+1) 847 LET E1=1 -850 REM IF N2 DAYS HAVE PASSED, PICK AN I2, SET E2, DETERMINE NEW N2 +850 REM IF N2 DAYS HAVE PASSED, PICK AN I2, SET E2, DETERMINE NEW N2 851 IF N2>0 THEN 860 -855 LET I2=INT(4.99*RND(X)+1) -856 LET N2=INT(4.99*RND(X)+1) +855 LET I2=INT(4.99*RND(X)+1) +856 LET N2=INT(4.99*RND(X)+1) 857 LET E2=1 860 REM DEDUCT ONE DAY FROM N1 AND N2 -861 LET N1=N1-1 -862 LET N2=N2-1 +861 LET N1=N1-1 +862 LET N2=N2-1 890 REM LOOP THROUGH ALL STOCKS 900 FOR I=1 TO 5 -910 LET X1=RND(X) +910 LET X1=RND(X) 915 IF X1>.25 THEN 920 916 LET X1=.25 -917 GOTO 935 +917 GOTO 935 920 IF X1>.5 THEN 925 921 LET X1=.5 -922 GOTO 935 +922 GOTO 935 925 IF X1>.75 THEN 930 -926 LET X1=.75 -927 GOTO 935 +926 LET X1=.75 +927 GOTO 935 930 LET X1=0.0 931 REM BIG CHANGE CONSTANT:W3 (SET TO ZERO INITIALLY) 935 LET W3=0 936 IF E1<1 THEN 945 -937 IF INT(I1+.5)<>INT(I+.5) THEN 945 -938 REM ADD 10 PTS. TO THIS STOCK; RESET E1 -939 LET W3=10 +937 IF INT(I1+.5)<>INT(I+.5) THEN 945 +938 REM ADD 10 PTS. TO THIS STOCK; RESET E1 +939 LET W3=10 943 LET E1=0 945 IF E2<1 THEN 955 -947 IF INT(I2+.5)<>INT(I+.5) THEN 955 +947 IF INT(I2+.5)<>INT(I+.5) THEN 955 948 REM SUBTRACT 10 PTS. FROM THIS STOCK; RESET E2 949 LET W3=W3-10 953 LET E2=0 954 REM C(I) IS CHANGE IN STOCK VALUE -955 LET C(I)=INT(A*S(I))+X1+INT(3-6*RND(X)+.5)+W3 -956 LET C(I)=INT(100*C(I)+.5)/100 +955 LET C(I)=INT(A*S(I))+X1+INT(3-6*RND(X)+.5)+W3 +956 LET C(I)=INT(100*C(I)+.5)/100 957 LET S(I)=S(I)+C(I) 960 IF S(I)>0 THEN 967 964 LET C(I)=0 965 LET S(I)=0 -966 GOTO 970 -967 LET S(I)=INT(100*S(I)+.5)/100 +966 GOTO 970 +967 LET S(I)=INT(100*S(I)+.5)/100 970 NEXT I -972 REM AFTER T8 DAYS RANDOMLY CHANGE TREND SIGN AND SLOPE -973 LET T8=T8-1 +972 REM AFTER T8 DAYS RANDOMLY CHANGE TREND SIGN AND SLOPE +973 LET T8=T8-1 974 IF T8<1 THEN 985 980 RETURN -985 REM RANDOMLY CHANGE TREND SIGN AND SLOPE (A), AND DURATION +985 REM RANDOMLY CHANGE TREND SIGN AND SLOPE (A), AND DURATION 986 REM OF TREND (T8) -990 LET T8=INT(4.99*RND(X)+1) -992 LET A=INT((RND(X)/10)*100+.5)/100 -993 LET S4=RND(X) +990 LET T8=INT(4.99*RND(X)+1) +992 LET A=INT((RND(X)/10)*100+.5)/100 +993 LET S4=RND(X) 994 IF S4<=.5 THEN 997 995 LET A=-A 997 RETURN diff --git a/84_Super_Star_Trek/README.md b/84_Super_Star_Trek/README.md index e47c90b78..1ad375fdd 100644 --- a/84_Super_Star_Trek/README.md +++ b/84_Super_Star_Trek/README.md @@ -91,7 +91,7 @@ The relation between the Historical and Standard nomenclatures is shown in the s --- #### Bugs -Many of the programs in this book and this collection have bugs in the original code. +Many of the programs in this book and this collection have bugs in the original code. @jkboyce has done a great job of discovering and fixing a number of bugs in the [original code](superstartrek.bas), as part of his [python implementation](python/superstartrek.py), which should be noted by other implementers: diff --git a/84_Super_Star_Trek/csharp/Resources/CourtMartial.txt b/84_Super_Star_Trek/csharp/Resources/CourtMartial.txt index 7d05a5b83..a6c5285e7 100644 --- a/84_Super_Star_Trek/csharp/Resources/CourtMartial.txt +++ b/84_Super_Star_Trek/csharp/Resources/CourtMartial.txt @@ -1,3 +1,3 @@ Starfleet Command reviewing your record to consider -court martial! \ No newline at end of file +court martial! diff --git a/84_Super_Star_Trek/csharp/Resources/Enterprise.txt b/84_Super_Star_Trek/csharp/Resources/Enterprise.txt index 4310ca91b..a47156a53 100644 --- a/84_Super_Star_Trek/csharp/Resources/Enterprise.txt +++ b/84_Super_Star_Trek/csharp/Resources/Enterprise.txt @@ -16,9 +16,3 @@ '----------------' THE USS ENTERPRISE --- NCC-1701 - - - - - - diff --git a/84_Super_Star_Trek/csharp/Resources/Instructions.txt b/84_Super_Star_Trek/csharp/Resources/Instructions.txt index 34b4169c3..72ded5ce2 100644 --- a/84_Super_Star_Trek/csharp/Resources/Instructions.txt +++ b/84_Super_Star_Trek/csharp/Resources/Instructions.txt @@ -104,4 +104,3 @@ COM command = Library-Computer Option 5 = Galactic Region Name Map This option prints the names of the sixteen major galactic regions referred to in the game. - diff --git a/84_Super_Star_Trek/csharp/Resources/NoEnemyShips.txt b/84_Super_Star_Trek/csharp/Resources/NoEnemyShips.txt index 394f10575..d4b2efb2f 100644 --- a/84_Super_Star_Trek/csharp/Resources/NoEnemyShips.txt +++ b/84_Super_Star_Trek/csharp/Resources/NoEnemyShips.txt @@ -1,2 +1,2 @@ Science Officer Spock reports, 'Sensors show no enemy ships - in this quadrant' \ No newline at end of file + in this quadrant' diff --git a/84_Super_Star_Trek/csharp/Resources/NoStarbase.txt b/84_Super_Star_Trek/csharp/Resources/NoStarbase.txt index 5bb4e5fbc..59c991eca 100644 --- a/84_Super_Star_Trek/csharp/Resources/NoStarbase.txt +++ b/84_Super_Star_Trek/csharp/Resources/NoStarbase.txt @@ -1 +1 @@ -Mr. Spock reports, 'Sensors show no starbases in this quadrant.' \ No newline at end of file +Mr. Spock reports, 'Sensors show no starbases in this quadrant.' diff --git a/84_Super_Star_Trek/csharp/Resources/NowEntering.txt b/84_Super_Star_Trek/csharp/Resources/NowEntering.txt index 6545f9c4e..6e770a714 100644 --- a/84_Super_Star_Trek/csharp/Resources/NowEntering.txt +++ b/84_Super_Star_Trek/csharp/Resources/NowEntering.txt @@ -1,3 +1,2 @@ Now entering {0} quadrant . . . - diff --git a/84_Super_Star_Trek/csharp/Resources/Orders.txt b/84_Super_Star_Trek/csharp/Resources/Orders.txt index 7dc14b24e..7dd142e54 100644 --- a/84_Super_Star_Trek/csharp/Resources/Orders.txt +++ b/84_Super_Star_Trek/csharp/Resources/Orders.txt @@ -3,4 +3,3 @@ Your orders are as follows: the galaxy before they can attack federation headquarters on stardate {1}. This gives you {2} days. There {3} {4} starbase{5} in the galaxy for resupplying your ship. - diff --git a/84_Super_Star_Trek/csharp/Resources/Protected.txt b/84_Super_Star_Trek/csharp/Resources/Protected.txt index 27c4a5f88..fe23b63b6 100644 --- a/84_Super_Star_Trek/csharp/Resources/Protected.txt +++ b/84_Super_Star_Trek/csharp/Resources/Protected.txt @@ -1 +1 @@ -Starbase shields protect the Enterprise \ No newline at end of file +Starbase shields protect the Enterprise diff --git a/84_Super_Star_Trek/csharp/Resources/RegionNames.txt b/84_Super_Star_Trek/csharp/Resources/RegionNames.txt index f84fe43bf..7556a9f87 100644 --- a/84_Super_Star_Trek/csharp/Resources/RegionNames.txt +++ b/84_Super_Star_Trek/csharp/Resources/RegionNames.txt @@ -5,4 +5,4 @@ Canopus Aldebaran Altair Regulus Sagittarius Arcturus - Pollux Spica \ No newline at end of file + Pollux Spica diff --git a/84_Super_Star_Trek/csharp/Resources/RelievedOfCommand.txt b/84_Super_Star_Trek/csharp/Resources/RelievedOfCommand.txt index 8086e3ca9..31f398ba5 100644 --- a/84_Super_Star_Trek/csharp/Resources/RelievedOfCommand.txt +++ b/84_Super_Star_Trek/csharp/Resources/RelievedOfCommand.txt @@ -1,3 +1,3 @@ That does it, Captain!! You are hereby relieved of command -and sentenced to 99 stardates at hard labor on Cygnus 12!! \ No newline at end of file +and sentenced to 99 stardates at hard labor on Cygnus 12!! diff --git a/84_Super_Star_Trek/csharp/Resources/RepairPrompt.txt b/84_Super_Star_Trek/csharp/Resources/RepairPrompt.txt index feffdb27f..36428e308 100644 --- a/84_Super_Star_Trek/csharp/Resources/RepairPrompt.txt +++ b/84_Super_Star_Trek/csharp/Resources/RepairPrompt.txt @@ -1 +1 @@ -Will you authorize the repair order (Y/N) \ No newline at end of file +Will you authorize the repair order (Y/N) diff --git a/84_Super_Star_Trek/csharp/Resources/ReplayPrompt.txt b/84_Super_Star_Trek/csharp/Resources/ReplayPrompt.txt index 3ca3a1021..8f9c2d547 100644 --- a/84_Super_Star_Trek/csharp/Resources/ReplayPrompt.txt +++ b/84_Super_Star_Trek/csharp/Resources/ReplayPrompt.txt @@ -2,4 +2,4 @@ The Federation is in need of a new starship commander for a similar mission -- if there is a volunteer -let him step forward and enter 'Aye' \ No newline at end of file +let him step forward and enter 'Aye' diff --git a/84_Super_Star_Trek/csharp/Resources/ShieldsDropped.txt b/84_Super_Star_Trek/csharp/Resources/ShieldsDropped.txt index 9135e8b46..acc87f590 100644 --- a/84_Super_Star_Trek/csharp/Resources/ShieldsDropped.txt +++ b/84_Super_Star_Trek/csharp/Resources/ShieldsDropped.txt @@ -1 +1 @@ -Shields dropped for docking purposes \ No newline at end of file +Shields dropped for docking purposes diff --git a/84_Super_Star_Trek/csharp/Resources/StartText.txt b/84_Super_Star_Trek/csharp/Resources/StartText.txt index 3c6028a5e..c599a2e23 100644 --- a/84_Super_Star_Trek/csharp/Resources/StartText.txt +++ b/84_Super_Star_Trek/csharp/Resources/StartText.txt @@ -2,4 +2,3 @@ Your mission begins with your starship located in the galactic quadrant, '{0}'. - diff --git a/84_Super_Star_Trek/csharp/Resources/Title.txt b/84_Super_Star_Trek/csharp/Resources/Title.txt index ccd867744..edee35782 100644 --- a/84_Super_Star_Trek/csharp/Resources/Title.txt +++ b/84_Super_Star_Trek/csharp/Resources/Title.txt @@ -17,11 +17,3 @@ * * * * ************************************* - - - - - - - - diff --git a/84_Super_Star_Trek/csharp/Space/Coordinates.cs b/84_Super_Star_Trek/csharp/Space/Coordinates.cs index 7aec927f2..4768d2c22 100644 --- a/84_Super_Star_Trek/csharp/Space/Coordinates.cs +++ b/84_Super_Star_Trek/csharp/Space/Coordinates.cs @@ -17,11 +17,11 @@ internal Coordinates(int x, int y) } internal int X { get; } - + internal int Y { get; } - + internal int RegionIndex { get; } - + internal int SubRegionIndex { get; } private static int Validated(int value, string argumentName) diff --git a/84_Super_Star_Trek/csharp/Space/Course.cs b/84_Super_Star_Trek/csharp/Space/Course.cs index b316e4b38..6b9dfc31c 100644 --- a/84_Super_Star_Trek/csharp/Space/Course.cs +++ b/84_Super_Star_Trek/csharp/Space/Course.cs @@ -46,7 +46,7 @@ internal Course(float direction) } internal float DeltaX { get; } - + internal float DeltaY { get; } internal IEnumerable GetSectorsFrom(Coordinates start) diff --git a/84_Super_Star_Trek/csharp/StringExtensions.cs b/84_Super_Star_Trek/csharp/StringExtensions.cs index 02e9794fe..4e77291af 100644 --- a/84_Super_Star_Trek/csharp/StringExtensions.cs +++ b/84_Super_Star_Trek/csharp/StringExtensions.cs @@ -4,4 +4,4 @@ internal static class StringExtensions { internal static string Pluralize(this string singular, int quantity) => singular + (quantity > 1 ? "s" : ""); } -} \ No newline at end of file +} diff --git a/84_Super_Star_Trek/csharp/Systems/ComputerFunctions/ComputerFunction.cs b/84_Super_Star_Trek/csharp/Systems/ComputerFunctions/ComputerFunction.cs index 36d9127b4..43553bd79 100644 --- a/84_Super_Star_Trek/csharp/Systems/ComputerFunctions/ComputerFunction.cs +++ b/84_Super_Star_Trek/csharp/Systems/ComputerFunctions/ComputerFunction.cs @@ -16,4 +16,4 @@ protected ComputerFunction(string description, Output output) internal abstract void Execute(Quadrant quadrant); } -} \ No newline at end of file +} diff --git a/84_Super_Star_Trek/csharp/Systems/ComputerFunctions/CumulativeGalacticRecord.cs b/84_Super_Star_Trek/csharp/Systems/ComputerFunctions/CumulativeGalacticRecord.cs index f02677ca2..920fbccaf 100644 --- a/84_Super_Star_Trek/csharp/Systems/ComputerFunctions/CumulativeGalacticRecord.cs +++ b/84_Super_Star_Trek/csharp/Systems/ComputerFunctions/CumulativeGalacticRecord.cs @@ -18,4 +18,4 @@ protected override void WriteHeader(Quadrant quadrant) => protected override IEnumerable GetRowData() => Galaxy.Quadrants.Select(row => " " + string.Join(" ", row)); } -} \ No newline at end of file +} diff --git a/84_Super_Star_Trek/csharp/Systems/ComputerFunctions/DirectionDistanceCalculator.cs b/84_Super_Star_Trek/csharp/Systems/ComputerFunctions/DirectionDistanceCalculator.cs index a3679ada9..3e9965db5 100644 --- a/84_Super_Star_Trek/csharp/Systems/ComputerFunctions/DirectionDistanceCalculator.cs +++ b/84_Super_Star_Trek/csharp/Systems/ComputerFunctions/DirectionDistanceCalculator.cs @@ -27,4 +27,4 @@ internal override void Execute(Quadrant quadrant) _input.GetCoordinates(" Final coordinates")); } } -} \ No newline at end of file +} diff --git a/84_Super_Star_Trek/csharp/Systems/ComputerFunctions/GalacticReport.cs b/84_Super_Star_Trek/csharp/Systems/ComputerFunctions/GalacticReport.cs index 8be29baf5..1e8d5f23a 100644 --- a/84_Super_Star_Trek/csharp/Systems/ComputerFunctions/GalacticReport.cs +++ b/84_Super_Star_Trek/csharp/Systems/ComputerFunctions/GalacticReport.cs @@ -31,4 +31,4 @@ internal sealed override void Execute(Quadrant quadrant) } } } -} \ No newline at end of file +} diff --git a/84_Super_Star_Trek/csharp/Systems/ComputerFunctions/GalaxyRegionMap.cs b/84_Super_Star_Trek/csharp/Systems/ComputerFunctions/GalaxyRegionMap.cs index f6fe0305a..12ff204b0 100644 --- a/84_Super_Star_Trek/csharp/Systems/ComputerFunctions/GalaxyRegionMap.cs +++ b/84_Super_Star_Trek/csharp/Systems/ComputerFunctions/GalaxyRegionMap.cs @@ -18,4 +18,4 @@ protected override void WriteHeader(Quadrant quadrant) => protected override IEnumerable GetRowData() => Strings.RegionNames.Split('\n').Select(n => n.TrimEnd('\r')); } -} \ No newline at end of file +} diff --git a/84_Super_Star_Trek/csharp/Systems/ComputerFunctions/NavigationCalculator.cs b/84_Super_Star_Trek/csharp/Systems/ComputerFunctions/NavigationCalculator.cs index 680f3d18e..ef35f8c3e 100644 --- a/84_Super_Star_Trek/csharp/Systems/ComputerFunctions/NavigationCalculator.cs +++ b/84_Super_Star_Trek/csharp/Systems/ComputerFunctions/NavigationCalculator.cs @@ -26,4 +26,4 @@ private void Write(float direction, float distance) => Output.WriteLine($"Direction = {direction}") .WriteLine($"Distance = {distance}"); } -} \ No newline at end of file +} diff --git a/84_Super_Star_Trek/csharp/Systems/ComputerFunctions/StarbaseDataCalculator.cs b/84_Super_Star_Trek/csharp/Systems/ComputerFunctions/StarbaseDataCalculator.cs index 7a87f9708..07f2119b2 100644 --- a/84_Super_Star_Trek/csharp/Systems/ComputerFunctions/StarbaseDataCalculator.cs +++ b/84_Super_Star_Trek/csharp/Systems/ComputerFunctions/StarbaseDataCalculator.cs @@ -27,4 +27,4 @@ internal override void Execute(Quadrant quadrant) WriteDirectionAndDistance(_enterprise.SectorCoordinates, quadrant.Starbase.Sector); } } -} \ No newline at end of file +} diff --git a/84_Super_Star_Trek/csharp/Systems/ComputerFunctions/StatusReport.cs b/84_Super_Star_Trek/csharp/Systems/ComputerFunctions/StatusReport.cs index 26a299a81..6e6bf6f14 100644 --- a/84_Super_Star_Trek/csharp/Systems/ComputerFunctions/StatusReport.cs +++ b/84_Super_Star_Trek/csharp/Systems/ComputerFunctions/StatusReport.cs @@ -38,4 +38,4 @@ internal override void Execute(Quadrant quadrant) _enterprise.Execute(Command.DAM); } } -} \ No newline at end of file +} diff --git a/84_Super_Star_Trek/csharp/Systems/ComputerFunctions/TorpedoDataCalculator.cs b/84_Super_Star_Trek/csharp/Systems/ComputerFunctions/TorpedoDataCalculator.cs index ec837fc42..94f8ae9ab 100644 --- a/84_Super_Star_Trek/csharp/Systems/ComputerFunctions/TorpedoDataCalculator.cs +++ b/84_Super_Star_Trek/csharp/Systems/ComputerFunctions/TorpedoDataCalculator.cs @@ -30,4 +30,4 @@ internal override void Execute(Quadrant quadrant) } } } -} \ No newline at end of file +} diff --git a/84_Super_Star_Trek/csharp/Utils/DirectionAndDistance.cs b/84_Super_Star_Trek/csharp/Utils/DirectionAndDistance.cs index e4b1a2faa..a2d3f09bc 100644 --- a/84_Super_Star_Trek/csharp/Utils/DirectionAndDistance.cs +++ b/84_Super_Star_Trek/csharp/Utils/DirectionAndDistance.cs @@ -62,4 +62,4 @@ private static float GetDirection(float deltaX, float deltaY) private static float GetDistance(float deltaX, float deltaY) => (float)Math.Sqrt(Math.Pow(deltaX, 2) + Math.Pow(deltaY, 2)); } -} \ No newline at end of file +} diff --git a/84_Super_Star_Trek/instructions.txt b/84_Super_Star_Trek/instructions.txt index 91f26b42b..59124d9d6 100644 --- a/84_Super_Star_Trek/instructions.txt +++ b/84_Super_Star_Trek/instructions.txt @@ -54,9 +54,9 @@ OF THE STARSHIP ENTERPRISE: WAY BETWEEN 1 AND 2 ... . . . VALUES MAY APPROACH 9.0, WHICH 6 7 8 - ITSELF IS EQUIVALENT TO 1.0" + ITSELF IS EQUIVALENT TO 1.0" COURSE - ONE WARP FACTOR IS THE SIZE OF + ONE WARP FACTOR IS THE SIZE OF ONE QUADTANT. THEREFORE, TO GET FROM QUADRANT 6,5 TO 5,5, YOU WOULD USE COURSE 3, WARP FACTOR 1. @@ -83,7 +83,7 @@ OF THE STARSHIP ENTERPRISE: EXAMPLE - 207 = 2 KLINGONS, NO STARBASES, & 7 STARS. \PHA\ COMMAND = PHASER CONTROL. - ALLOWS YOU TO DESTROY THE KLINGON BATTLE CRUISERS BY + ALLOWS YOU TO DESTROY THE KLINGON BATTLE CRUISERS BY ZAPPING THEM WITH SUITABLY LARGE UNITS OF ENERGY TO DEPLETE THEIR SHIELD POWER. (REMEMBER, KLINGONS HAVE PHASERS TOO!) @@ -92,10 +92,10 @@ OF THE STARSHIP ENTERPRISE: TORPEDO COURSE IS THE SAME AS USED IN WARP ENGINE CONTROL IF YOU HIT THE KLINGON VESSEL, HE IS DESTROYED AND CANNOT FIRE BACK AT YOU. IF YOU MISS, YOU ARE SUBJECT TO - HIS PHASER FIRE. IN EITHER CASE, YOU ARE ALSO SUBJECT TO + HIS PHASER FIRE. IN EITHER CASE, YOU ARE ALSO SUBJECT TO THE PHASER FIRE OF ALL OTHER KLINGONS IN THE QUADRANT. - THE LIBRARY-COMPUTER (\COM\ COMMAND) HAS AN OPTION TO + THE LIBRARY-COMPUTER (\COM\ COMMAND) HAS AN OPTION TO COMPUTE TORPEDO TRAJECTORY FOR YOU (OPTION 2) \SHE\ COMMAND = SHIELD CONTROL @@ -120,12 +120,11 @@ OF THE STARSHIP ENTERPRISE: WHICH GIVES DIRECTIONS AND DISTANCE FROM THE ENTERPRISE TO ALL KLINGONS IN YOUR QUADRANT OPTION 3 = STARBASE NAV DATA - THIS OPTION GIVES DIRECTION AND DISTANCE TO ANY + THIS OPTION GIVES DIRECTION AND DISTANCE TO ANY STARBASE WITHIN YOUR QUADRANT OPTION 4 = DIRECTION/DISTANCE CALCULATOR THIS OPTION ALLOWS YOU TO ENTER COORDINATES FOR DIRECTION/DISTANCE CALCULATIONS OPTION 5 = GALACTIC /REGION NAME/ MAP - THIS OPTION PRINTS THE NAMES OF THE SIXTEEN MAJOR + THIS OPTION PRINTS THE NAMES OF THE SIXTEEN MAJOR GALACTIC REGIONS REFERRED TO IN THE GAME. - diff --git a/84_Super_Star_Trek/java/SuperStarTrekGame.java b/84_Super_Star_Trek/java/SuperStarTrekGame.java index 213b2a0b8..b8ecb9343 100644 --- a/84_Super_Star_Trek/java/SuperStarTrekGame.java +++ b/84_Super_Star_Trek/java/SuperStarTrekGame.java @@ -120,9 +120,9 @@ static void printBanner() { // 220 '-------- --' / / ,---' '-------/ /--, '----------------' - + THE USS ENTERPRISE --- NCC-1701" - + """ ); } diff --git a/84_Super_Star_Trek/javascript/index.html b/84_Super_Star_Trek/javascript/index.html index fd3a7e091..d2e31b8f3 100644 --- a/84_Super_Star_Trek/javascript/index.html +++ b/84_Super_Star_Trek/javascript/index.html @@ -96,9 +96,9 @@

Super Star Trek

WAY BETWEEN 1 AND 2 ... . . . VALUES MAY APPROACH 9.0, WHICH 6 7 8 - ITSELF IS EQUIVALENT TO 1.0" + ITSELF IS EQUIVALENT TO 1.0" COURSE - ONE WARP FACTOR IS THE SIZE OF + ONE WARP FACTOR IS THE SIZE OF ONE QUADTANT. THEREFORE, TO GET FROM QUADRANT 6,5 TO 5,5, YOU WOULD USE COURSE 3, WARP FACTOR 1. @@ -122,7 +122,7 @@

Super Star Trek

EXAMPLE - 207 = 2 KLINGONS, NO STARBASES, & 7 STARS. \PHA\ COMMAND = PHASER CONTROL. - ALLOWS YOU TO DESTROY THE KLINGON BATTLE CRUISERS BY + ALLOWS YOU TO DESTROY THE KLINGON BATTLE CRUISERS BY ZAPPING THEM WITH SUITABLY LARGE UNITS OF ENERGY TO DEPLETE THEIR SHIELD POWER. (REMBER, KLINGONS HAVE PHASERS TOO!) @@ -150,7 +150,7 @@

Super Star Trek

THE LIBRARY-COMPUTER CONTAINS SIX OPTIONS: OPTION 0 = CUMULATIVE GALACTIC RECORD THIS OPTION SHOWES COMPUTER MEMORY OF THE RESULTS OF ALL - PREVIOUS SHORT AND LONG RANGE SENSOR SCANS + PREVIOUS SHORT AND LONG RANGE SENSOR SCANS OPTION 1 = STATUS REPORT THIS OPTION SHOWS THE NUMBER OF KLINGONS, STARDATES, AND STARBASES REMAINING IN THE GAME. diff --git a/84_Super_Star_Trek/python/superstartrek.py b/84_Super_Star_Trek/python/superstartrek.py index f6898c0d2..bd3a2e89c 100644 --- a/84_Super_Star_Trek/python/superstartrek.py +++ b/84_Super_Star_Trek/python/superstartrek.py @@ -1,4 +1,3 @@ - # **** **** STAR TREK **** **** # **** SIMULATION OF A MISSION OF THE STARSHIP ENTERPRISE, # **** AS SEEN ON THE STAR TREK TV SHOW. @@ -16,7 +15,6 @@ import random from math import sqrt - # ------------------------------------------------------------------------- # Utility functions # ------------------------------------------------------------------------- @@ -29,16 +27,32 @@ def fnr(): def quadrant_name(row, col, region_only=False): # Return quadrant name visible on scans, etc. - region1 = ['ANTARES', 'RIGEL', 'PROCYON', 'VEGA', 'CANOPUS', 'ALTAIR', - 'SAGITTARIUS', 'POLLUX'] - region2 = ['SIRIUS', 'DENEB', 'CAPELLA', 'BETELGEUSE', 'ALDEBARAN', - 'REGULUS', 'ARCTURUS', 'SPICA'] - modifier = ['I', 'II', 'III', 'IV'] + region1 = [ + "ANTARES", + "RIGEL", + "PROCYON", + "VEGA", + "CANOPUS", + "ALTAIR", + "SAGITTARIUS", + "POLLUX", + ] + region2 = [ + "SIRIUS", + "DENEB", + "CAPELLA", + "BETELGEUSE", + "ALDEBARAN", + "REGULUS", + "ARCTURUS", + "SPICA", + ] + modifier = ["I", "II", "III", "IV"] quadrant = region1[row] if col < 4 else region2[row] if not region_only: - quadrant += ' ' + modifier[col % 4] + quadrant += " " + modifier[col % 4] return quadrant @@ -49,25 +63,25 @@ def insert_marker(row, col, marker): global qs if len(marker) != 3: - print('ERROR') + print("ERROR") exit() pos = round(col) * 3 + round(row) * 24 - qs = qs[0:pos] + marker + qs[(pos + 3):192] + qs = qs[0:pos] + marker + qs[(pos + 3) : 192] def compare_marker(row, col, test_marker): # Check whether the position in the current quadrant is occupied with a # given marker. pos = round(col) * 3 + round(row) * 24 - return qs[pos:(pos + 3)] == test_marker + return qs[pos : (pos + 3)] == test_marker def find_empty_place(): # Find an empty location in the current quadrant. while True: row, col = fnr(), fnr() - if compare_marker(row, col, ' '): + if compare_marker(row, col, " "): return row, col @@ -102,8 +116,9 @@ def navigation(): if warp == 0: return if warp < 0 or warp > 8: - print(" CHIEF ENGINEER SCOTT REPORTS 'THE ENGINES WON'T TAKE " - f"WARP {warp}!'") + print( + " CHIEF ENGINEER SCOTT REPORTS 'THE ENGINES WON'T TAKE " f"WARP {warp}!'" + ) return n = round(warp * 8) @@ -118,14 +133,14 @@ def navigation(): # klingons move and fire for i in range(3): if k[i][2] != 0: - insert_marker(k[i][0], k[i][1], ' ') + insert_marker(k[i][0], k[i][1], " ") k[i][0], k[i][1] = find_empty_place() - insert_marker(k[i][0], k[i][1], '+K+') + insert_marker(k[i][0], k[i][1], "+K+") klingons_fire() # repair damaged devices and print damage report - line = '' + line = "" for i in range(8): if d[i] < 0: d[i] += min(warp, 1) @@ -134,7 +149,7 @@ def navigation(): elif d[i] >= 0: if len(line) == 0: line = "DAMAGE CONTROL REPORT:" - line += ' ' + devices[i] + ' REPAIR COMPLETED\n' + line += " " + devices[i] + " REPAIR COMPLETED\n" if len(line) > 0: print(line) if random.random() <= 0.2: @@ -144,11 +159,12 @@ def navigation(): print(f"DAMAGE CONTROL REPORT: {devices[r1]} DAMAGED\n") else: d[r1] += random.random() * 3 + 1 - print(f"DAMAGE CONTROL REPORT: {devices[r1]} STATE OF " - "REPAIR IMPROVED\n") + print( + f"DAMAGE CONTROL REPORT: {devices[r1]} STATE OF " "REPAIR IMPROVED\n" + ) # begin moving starship - insert_marker(int(s1), int(s2), ' ') + insert_marker(int(s1), int(s2), " ") ic1 = int(c1) x1 = c[ic1 - 1][0] + (c[ic1][0] - c[ic1 - 1][0]) * (c1 - ic1) x2 = c[ic1 - 1][1] + (c[ic1][1] - c[ic1 - 1][1]) * (c1 - ic1) @@ -187,12 +203,13 @@ def navigation(): q2 = s2 = 7 if hit_edge: print("LT. UHURA REPORTS MESSAGE FROM STARFLEET COMMAND:") - print(" 'PERMISSION TO ATTEMPT CROSSING OF GALACTIC " - "PERIMETER") + print(" 'PERMISSION TO ATTEMPT CROSSING OF GALACTIC " "PERIMETER") print(" IS HEREBY *DENIED*. SHUT DOWN YOUR ENGINES.'") print("CHIEF ENGINEER SCOTT REPORTS 'WARP ENGINES SHUT DOWN") - print(f" AT SECTOR {s1 + 1} , {s2 + 1} OF QUADRANT " - f"{q1 + 1} , {q2 + 1}.'") + print( + f" AT SECTOR {s1 + 1} , {s2 + 1} OF QUADRANT " + f"{q1 + 1} , {q2 + 1}.'" + ) if t > t0 + t9: end_game(won=False, quit=False) return @@ -205,15 +222,17 @@ def navigation(): return else: pos = int(s1) * 24 + int(s2) * 3 - if qs[pos:(pos + 2)] != ' ': + if qs[pos : (pos + 2)] != " ": s1, s2 = int(s1 - x1), int(s2 - x2) - print("WARP ENGINES SHUT DOWN AT SECTOR " - f"{s1 + 1} , {s2 + 1} DUE TO BAD NAVAGATION") + print( + "WARP ENGINES SHUT DOWN AT SECTOR " + f"{s1 + 1} , {s2 + 1} DUE TO BAD NAVAGATION" + ) break else: s1, s2 = int(s1), int(s2) - insert_marker(int(s1), int(s2), '<*>') + insert_marker(int(s1), int(s2), "<*>") maneuver_energy(n) t += 0.1 * int(10 * warp) if warp < 1 else 1 @@ -245,9 +264,9 @@ def short_range_scan(): for i in (s1 - 1, s1, s1 + 1): for j in (s2 - 1, s2, s2 + 1): if 0 <= i <= 7 and 0 <= j <= 7: - if compare_marker(i, j, '>!<'): + if compare_marker(i, j, ">!<"): docked = True - cs = 'DOCKED' + cs = "DOCKED" e, p = e0, p0 print("SHIELDS DROPPED FOR DOCKING PURPOSES") s = 0 @@ -257,40 +276,40 @@ def short_range_scan(): break else: if k3 > 0: - cs = '*RED*' + cs = "*RED*" elif e < e0 * 0.1: - cs = 'YELLOW' + cs = "YELLOW" else: - cs = 'GREEN' + cs = "GREEN" if d[1] < 0: print("\n*** SHORT RANGE SENSORS ARE OUT ***\n") return - sep = '---------------------------------' + sep = "---------------------------------" print(sep) for i in range(8): - line = '' + line = "" for j in range(8): pos = i * 24 + j * 3 - line = line + ' ' + qs[pos:(pos + 3)] + line = line + " " + qs[pos : (pos + 3)] if i == 0: - line += f' STARDATE {round(int(t * 10) * 0.1, 1)}' + line += f" STARDATE {round(int(t * 10) * 0.1, 1)}" elif i == 1: - line += f' CONDITION {cs}' + line += f" CONDITION {cs}" elif i == 2: - line += f' QUADRANT {q1 + 1} , {q2 + 1}' + line += f" QUADRANT {q1 + 1} , {q2 + 1}" elif i == 3: - line += f' SECTOR {s1 + 1} , {s2 + 1}' + line += f" SECTOR {s1 + 1} , {s2 + 1}" elif i == 4: - line += f' PHOTON TORPEDOES {int(p)}' + line += f" PHOTON TORPEDOES {int(p)}" elif i == 5: - line += f' TOTAL ENERGY {int(e + s)}' + line += f" TOTAL ENERGY {int(e + s)}" elif i == 6: - line += f' SHIELDS {int(s)}' + line += f" SHIELDS {int(s)}" else: - line += f' KLINGONS REMAINING {k9}' + line += f" KLINGONS REMAINING {k9}" print(line) print(sep) @@ -305,7 +324,7 @@ def long_range_scan(): return print(f"LONG RANGE SCAN FOR QUADRANT {q1 + 1} , {q2 + 1}") - sep = '-------------------' + sep = "-------------------" print(sep) for i in (q1 - 1, q1, q1 + 1): n = [-1, -2, -3] @@ -315,12 +334,12 @@ def long_range_scan(): n[j - q2 + 1] = g[i][j] z[i][j] = g[i][j] - line = ': ' + line = ": " for l in range(3): if n[l] < 0: - line += '*** : ' + line += "*** : " else: - line += str(n[l] + 1000).rjust(4, ' ')[-3:] + ' : ' + line += str(n[l] + 1000).rjust(4, " ")[-3:] + " : " print(line) print(sep) @@ -366,17 +385,19 @@ def phaser_control(): h = int((h1 / fnd(i)) * (random.random() + 2)) if h <= 0.15 * k[i][2]: - print("SENSORS SHOW NO DAMAGE TO ENEMY AT " - f"{k[i][0] + 1} , {k[i][1] + 1}") + print( + "SENSORS SHOW NO DAMAGE TO ENEMY AT " f"{k[i][0] + 1} , {k[i][1] + 1}" + ) else: k[i][2] -= h - print(f" {h} UNIT HIT ON KLINGON AT SECTOR " - f"{k[i][0] + 1} , {k[i][1] + 1}") + print( + f" {h} UNIT HIT ON KLINGON AT SECTOR " f"{k[i][0] + 1} , {k[i][1] + 1}" + ) if k[i][2] <= 0: print("*** KLINGON DESTROYED ***") k3 -= 1 k9 -= 1 - insert_marker(k[i][0], k[i][1], ' ') + insert_marker(k[i][0], k[i][1], " ") k[i][2] = 0 g[q1][q2] -= 100 z[q1][q2] = g[q1][q2] @@ -428,10 +449,10 @@ def photon_torpedoes(): klingons_fire() return print(f" {x3 + 1} , {y3 + 1}") - if not compare_marker(x3, y3, ' '): + if not compare_marker(x3, y3, " "): break - if compare_marker(x3, y3, '+K+'): + if compare_marker(x3, y3, "+K+"): print("*** KLINGON DESTROYED ***") k3 -= 1 k9 -= 1 @@ -441,11 +462,11 @@ def photon_torpedoes(): for i in range(3): if x3 == k[i][0] and y3 == k[i][1]: k[i][2] = 0 - elif compare_marker(x3, y3, ' * '): + elif compare_marker(x3, y3, " * "): print(f"STAR AT {x3 + 1} , {y3 + 1} ABSORBED TORPEDO ENERGY.") klingons_fire() return - elif compare_marker(x3, y3, '>!<'): + elif compare_marker(x3, y3, ">!<"): print("*** STARBASE DESTROYED ***") b3 -= 1 b9 -= 1 @@ -459,7 +480,7 @@ def photon_torpedoes(): print("COURT MARTIAL!") docked = False - insert_marker(x3, y3, ' ') + insert_marker(x3, y3, " ") g[q1][q2] = k3 * 100 + b3 * 10 + s3 z[q1][q2] = g[q1][q2] klingons_fire() @@ -467,7 +488,7 @@ def photon_torpedoes(): def fnd(i): # Find distance between Enterprise and i'th Klingon warship. - return sqrt((k[i][0] - s1)**2 + (k[i][1] - s2)**2) + return sqrt((k[i][0] - s1) ** 2 + (k[i][1] - s2) ** 2) def klingons_fire(): @@ -486,9 +507,10 @@ def klingons_fire(): h = int((k[i][2] / fnd(i)) * (random.random() + 2)) s -= h - k[i][2] /= (random.random() + 3) - print(f" {h} UNIT HIT ON ENTERPRISE FROM SECTOR " - f"{k[i][0] + 1} , {k[i][1] + 1}") + k[i][2] /= random.random() + 3 + print( + f" {h} UNIT HIT ON ENTERPRISE FROM SECTOR " f"{k[i][0] + 1} , {k[i][1] + 1}" + ) if s <= 0: end_game(won=False, quit=False, enterprise_killed=True) return @@ -496,8 +518,7 @@ def klingons_fire(): if h >= 20 and random.random() < 0.60 and h / s > 0.02: r1 = fnr() d[r1] -= h / s + 0.5 * random.random() - print(f"DAMAGE CONTROL REPORTS '{devices[r1]} DAMAGED " - "BY THE HIT'") + print(f"DAMAGE CONTROL REPORTS '{devices[r1]} DAMAGED " "BY THE HIT'") def shield_control(): @@ -519,9 +540,11 @@ def shield_control(): return if x > e + s: - print("SHIELD CONTROL REPORTS 'THIS IS NOT THE FEDERATION " - "TREASURY.'\n" - "") + print( + "SHIELD CONTROL REPORTS 'THIS IS NOT THE FEDERATION " + "TREASURY.'\n" + "" + ) return e += s - x @@ -535,9 +558,9 @@ def damage_control(): global d, t if d[5] < 0: - print('DAMAGE CONTROL REPORT NOT AVAILABLE') + print("DAMAGE CONTROL REPORT NOT AVAILABLE") else: - print('\nDEVICE STATE OF REPAIR') + print("\nDEVICE STATE OF REPAIR") for r1 in range(8): print(f"{devices[r1].ljust(26, ' ')}{int(d[r1] * 100) * 0.01:g}") print() @@ -553,10 +576,8 @@ def damage_control(): if d3 >= 1: d3 = 0.9 print("\nTECHNICIANS STANDING BY TO EFFECT REPAIRS TO YOUR SHIP;") - print("ESTIMATED TIME TO REPAIR: " - f"{round(0.01 * int(100 * d3), 2)} STARDATES") - if input("WILL YOU AUTHORIZE THE " - "REPAIR ORDER (Y/N)? ").upper().strip() != 'Y': + print("ESTIMATED TIME TO REPAIR: " f"{round(0.01 * int(100 * d3), 2)} STARDATES") + if input("WILL YOU AUTHORIZE THE " "REPAIR ORDER (Y/N)? ").upper().strip() != "Y": return for i in range(8): @@ -588,26 +609,28 @@ def computer(): if com == 5: print(" THE GALAXY") else: - print("\n COMPUTER RECORD OF GALAXY FOR " - f"QUADRANT {q1 + 1} , {q2 + 1}\n") + print( + "\n COMPUTER RECORD OF GALAXY FOR " + f"QUADRANT {q1 + 1} , {q2 + 1}\n" + ) print(" 1 2 3 4 5 6 7 8") sep = " ----- ----- ----- ----- ----- ----- ----- -----" print(sep) for i in range(8): - line = ' ' + str(i + 1) + ' ' + line = " " + str(i + 1) + " " if com == 5: g2s = quadrant_name(i, 0, True) - line += (' ' * int(12 - 0.5 * len(g2s))) + g2s + line += (" " * int(12 - 0.5 * len(g2s))) + g2s g2s = quadrant_name(i, 4, True) - line += (' ' * int(39 - 0.5 * len(g2s) - len(line))) + g2s + line += (" " * int(39 - 0.5 * len(g2s) - len(line))) + g2s else: for j in range(8): - line += ' ' + line += " " if z[i][j] == 0: - line += '***' + line += "***" else: line += str(z[i][j] + 1000)[-3:] @@ -619,27 +642,34 @@ def computer(): elif com == 1: print(" STATUS REPORT:") print(f"KLINGON{'S' if k9 > 1 else ''} LEFT: {k9}") - print("MISSION MUST BE COMPLETED IN " - f"{round(0.1 * int((t0+t9-t) * 10), 1)} STARDATES") + print( + "MISSION MUST BE COMPLETED IN " + f"{round(0.1 * int((t0+t9-t) * 10), 1)} STARDATES" + ) if b9 == 0: print("YOUR STUPIDITY HAS LEFT YOU ON YOUR OWN IN") print(" THE GALAXY -- YOU HAVE NO STARBASES LEFT!") else: - print(f"THE FEDERATION IS MAINTAINING {b9} " - f"STARBASE{'S' if b9 > 1 else ''} IN THE GALAXY") + print( + f"THE FEDERATION IS MAINTAINING {b9} " + f"STARBASE{'S' if b9 > 1 else ''} IN THE GALAXY" + ) damage_control() return elif com == 2: if k3 <= 0: - print("SCIENCE OFFICER SPOCK REPORTS 'SENSORS SHOW NO ENEMY " - "SHIPS\n" - " IN THIS QUADRANT'") + print( + "SCIENCE OFFICER SPOCK REPORTS 'SENSORS SHOW NO ENEMY " + "SHIPS\n" + " IN THIS QUADRANT'" + ) return - print("FROM ENTERPRISE TO KLINGON BATTLE " - f"CRUISER{'S' if k3 > 1 else ''}") + print( + "FROM ENTERPRISE TO KLINGON BATTLE " f"CRUISER{'S' if k3 > 1 else ''}" + ) for i in range(3): if k[i][2] > 0: @@ -647,8 +677,10 @@ def computer(): return elif com == 3: if b3 == 0: - print("MR. SPOCK REPORTS, 'SENSORS SHOW NO STARBASES IN THIS " - "QUADRANT.'") + print( + "MR. SPOCK REPORTS, 'SENSORS SHOW NO STARBASES IN THIS " + "QUADRANT.'" + ) return print("FROM ENTERPRISE TO STARBASE:") @@ -656,17 +688,16 @@ def computer(): return elif com == 4: print("DIRECTION/DISTANCE CALCULATOR:") - print(f"YOU ARE AT QUADRANT {q1+1} , {q2+1} SECTOR " - f"{s1+1} , {s2+1}") + print(f"YOU ARE AT QUADRANT {q1+1} , {q2+1} SECTOR " f"{s1+1} , {s2+1}") print("PLEASE ENTER") while True: - ins = input(" INITIAL COORDINATES (X,Y)? ").split(',') + ins = input(" INITIAL COORDINATES (X,Y)? ").split(",") if len(ins) == 2: from1, from2 = int(ins[0]) - 1, int(ins[1]) - 1 if 0 <= from1 <= 7 and 0 <= from2 <= 7: break while True: - ins = input(" FINAL COORDINATES (X,Y)? ").split(',') + ins = input(" FINAL COORDINATES (X,Y)? ").split(",") if len(ins) == 2: to1, to2 = int(ins[0]) - 1, int(ins[1]) - 1 if 0 <= to1 <= 7 and 0 <= to2 <= 7: @@ -674,13 +705,15 @@ def computer(): print_direction(from1, from2, to1, to2) return else: - print("FUNCTIONS AVAILABLE FROM LIBRARY-COMPUTER:\n" - " 0 = CUMULATIVE GALACTIC RECORD\n" - " 1 = STATUS REPORT\n" - " 2 = PHOTON TORPEDO DATA\n" - " 3 = STARBASE NAV DATA\n" - " 4 = DIRECTION/DISTANCE CALCULATOR\n" - " 5 = GALAXY 'REGION NAME' MAP\n") + print( + "FUNCTIONS AVAILABLE FROM LIBRARY-COMPUTER:\n" + " 0 = CUMULATIVE GALACTIC RECORD\n" + " 1 = STATUS REPORT\n" + " 2 = PHOTON TORPEDO DATA\n" + " 3 = STARBASE NAV DATA\n" + " 4 = DIRECTION/DISTANCE CALCULATOR\n" + " 5 = GALAXY 'REGION NAME' MAP\n" + ) def print_direction(from1, from2, to1, to2): @@ -722,39 +755,57 @@ def startup(): global g, z, d, t, t0, t9, docked, e, e0, p, p0, s, k9, b9, s9, c global devices, q1, q2, s1, s2, k7 - print("\n\n\n\n\n\n\n\n\n\n\n" - " ,------*------,\n" - " ,------------- '--- ------'\n" - " '-------- --' / /\n" - " ,---' '-------/ /--,\n" - " '----------------'\n\n" - " THE USS ENTERPRISE --- NCC-1701\n" - "\n\n\n\n") + print( + "\n\n\n\n\n\n\n\n\n\n\n" + " ,------*------,\n" + " ,------------- '--- ------'\n" + " '-------- --' / /\n" + " ,---' '-------/ /--,\n" + " '----------------'\n\n" + " THE USS ENTERPRISE --- NCC-1701\n" + "\n\n\n\n" + ) # set up global game variables - g = [[0] * 8 for _ in range(8)] # galaxy map - z = [[0] * 8 for _ in range(8)] # charted galaxy map - d = [0] * 8 # damage stats for devices - t = t0 = 100 * random.randint(20, 39) # stardate (current, initial) - t9 = random.randint(25, 34) # mission duration (stardates) - docked = False # true when docked at starbase - e = e0 = 3000 # energy (current, initial) - p = p0 = 10 # torpedoes (current, initial) - s = 0 # shields - k9, b9 = 0, 0 # total Klingons, bases in galaxy + g = [[0] * 8 for _ in range(8)] # galaxy map + z = [[0] * 8 for _ in range(8)] # charted galaxy map + d = [0] * 8 # damage stats for devices + t = t0 = 100 * random.randint(20, 39) # stardate (current, initial) + t9 = random.randint(25, 34) # mission duration (stardates) + docked = False # true when docked at starbase + e = e0 = 3000 # energy (current, initial) + p = p0 = 10 # torpedoes (current, initial) + s = 0 # shields + k9, b9 = 0, 0 # total Klingons, bases in galaxy # ^ bug in original, was b9 = 2 - s9 = 200 # avg. Klingon shield strength - - c = [[0, 1], [-1, 1], [-1, 0], [-1, -1], [0, -1], [1, -1], - [1, 0], [1, 1], [0, 1]] # vectors in cardinal directions - - devices = ['WARP ENGINES', 'SHORT RANGE SENSORS', 'LONG RANGE SENSORS', - 'PHASER CONTROL', 'PHOTON TUBES', 'DAMAGE CONTROL', - 'SHIELD CONTROL', 'LIBRARY-COMPUTER'] + s9 = 200 # avg. Klingon shield strength + + c = [ + [0, 1], + [-1, 1], + [-1, 0], + [-1, -1], + [0, -1], + [1, -1], + [1, 0], + [1, 1], + [0, 1], + ] # vectors in cardinal directions + + devices = [ + "WARP ENGINES", + "SHORT RANGE SENSORS", + "LONG RANGE SENSORS", + "PHASER CONTROL", + "PHOTON TUBES", + "DAMAGE CONTROL", + "SHIELD CONTROL", + "LIBRARY-COMPUTER", + ] # initialize Enterprise's position - q1, q2 = fnr(), fnr() # Enterprise's quadrant - s1, s2 = fnr(), fnr() # ...and sector + q1, q2 = fnr(), fnr() # Enterprise's quadrant + s1, s2 = fnr(), fnr() # ...and sector # initialize contents of galaxy for i in range(8): @@ -784,23 +835,25 @@ def startup(): g[q1][q2] += 10 q1, q2 = fnr(), fnr() - k7 = k9 # Klingons at start of game + k7 = k9 # Klingons at start of game - print("YOUR ORDERS ARE AS FOLLOWS:\n" - f" DESTROY THE {k9} KLINGON WARSHIPS WHICH HAVE INVADED\n" - " THE GALAXY BEFORE THEY CAN ATTACK FEDERATION HEADQUARTERS\n" - f" ON STARDATE {t0+t9}. THIS GIVES YOU {t9} DAYS. THERE " - f"{'IS' if b9 == 1 else 'ARE'}\n" - f" {b9} STARBASE{'' if b9 == 1 else 'S'} IN THE GALAXY FOR " - "RESUPPLYING YOUR SHIP.\n") + print( + "YOUR ORDERS ARE AS FOLLOWS:\n" + f" DESTROY THE {k9} KLINGON WARSHIPS WHICH HAVE INVADED\n" + " THE GALAXY BEFORE THEY CAN ATTACK FEDERATION HEADQUARTERS\n" + f" ON STARDATE {t0+t9}. THIS GIVES YOU {t9} DAYS. THERE " + f"{'IS' if b9 == 1 else 'ARE'}\n" + f" {b9} STARBASE{'' if b9 == 1 else 'S'} IN THE GALAXY FOR " + "RESUPPLYING YOUR SHIP.\n" + ) def new_quadrant(): # Enter a new quadrant: populate map and print a short range scan. global z, k3, b3, s3, d4, k, qs, b4, b5 - k3 = b3 = s3 = 0 # Klingons, bases, stars in quad. - d4 = 0.5 * random.random() # extra delay in repairs at base + k3 = b3 = s3 = 0 # Klingons, bases, stars in quad. + d4 = 0.5 * random.random() # extra delay in repairs at base z[q1][q2] = g[q1][q2] if 0 <= q1 <= 7 and 0 <= q2 <= 7: @@ -820,21 +873,21 @@ def new_quadrant(): if s <= 200: print(" SHIELDS DANGEROUSLY LOW") - k = [[0, 0, 0], [0, 0, 0], [0, 0, 0]] # Klingons in current quadrant - qs = ' ' * 192 # quadrant string + k = [[0, 0, 0], [0, 0, 0], [0, 0, 0]] # Klingons in current quadrant + qs = " " * 192 # quadrant string # build quadrant string - insert_marker(s1, s2, '<*>') + insert_marker(s1, s2, "<*>") for i in range(k3): r1, r2 = find_empty_place() - insert_marker(r1, r2, '+K+') + insert_marker(r1, r2, "+K+") k[i] = [r1, r2, s9 * (0.5 + random.random())] if b3 > 0: - b4, b5 = find_empty_place() # position of starbase (sector) - insert_marker(b4, b5, '>!<') + b4, b5 = find_empty_place() # position of starbase (sector) + insert_marker(b4, b5, ">!<") for i in range(s3): r1, r2 = find_empty_place() - insert_marker(r1, r2, ' * ') + insert_marker(r1, r2, " * ") short_range_scan() @@ -846,13 +899,14 @@ def end_game(won=False, quit=True, enterprise_killed=False): if won: print("CONGRATULATIONS, CAPTAIN! THE LAST KLINGON BATTLE CRUISER") print("MENACING THE FEDERATION HAS BEEN DESTROYED.\n") - print("YOUR EFFICIENCY RATING IS " - f"{round(1000 * (k7 / (t - t0))**2, 4)}\n\n") + print("YOUR EFFICIENCY RATING IS " f"{round(1000 * (k7 / (t - t0))**2, 4)}\n\n") else: if not quit: if enterprise_killed: - print("\nTHE ENTERPRISE HAS BEEN DESTROYED. THE FEDERATION " - "WILL BE CONQUERED.") + print( + "\nTHE ENTERPRISE HAS BEEN DESTROYED. THE FEDERATION " + "WILL BE CONQUERED." + ) print(f"IT IS STARDATE {round(t, 1)}") print(f"THERE WERE {k9} KLINGON BATTLE CRUISERS LEFT AT") @@ -863,8 +917,7 @@ def end_game(won=False, quit=True, enterprise_killed=False): print("THE FEDERATION IS IN NEED OF A NEW STARSHIP COMMANDER") print("FOR A SIMILAR MISSION -- IF THERE IS A VOLUNTEER,") - if input("LET HIM STEP FORWARD AND " - "ENTER 'AYE'? ").upper().strip() != 'AYE': + if input("LET HIM STEP FORWARD AND " "ENTER 'AYE'? ").upper().strip() != "AYE": exit() restart = True @@ -877,9 +930,17 @@ def end_game(won=False, quit=True, enterprise_killed=False): def main(): global restart - f = {'NAV': navigation, 'SRS': short_range_scan, 'LRS': long_range_scan, - 'PHA': phaser_control, 'TOR': photon_torpedoes, 'SHE': shield_control, - 'DAM': damage_control, 'COM': computer, 'XXX': end_game} + f = { + "NAV": navigation, + "SRS": short_range_scan, + "LRS": long_range_scan, + "PHA": phaser_control, + "TOR": photon_torpedoes, + "SHE": shield_control, + "DAM": damage_control, + "COM": computer, + "XXX": end_game, + } while True: startup() @@ -888,26 +949,30 @@ def main(): while not restart: if s + e <= 10 or (e <= 10 and d[6] != 0): - print("\n** FATAL ERROR ** YOU'VE JUST STRANDED YOUR SHIP " - "IN SPACE.\nYOU HAVE INSUFFICIENT MANEUVERING ENERGY, " - "AND SHIELD CONTROL\nIS PRESENTLY INCAPABLE OF CROSS-" - "CIRCUITING TO ENGINE ROOM!!") + print( + "\n** FATAL ERROR ** YOU'VE JUST STRANDED YOUR SHIP " + "IN SPACE.\nYOU HAVE INSUFFICIENT MANEUVERING ENERGY, " + "AND SHIELD CONTROL\nIS PRESENTLY INCAPABLE OF CROSS-" + "CIRCUITING TO ENGINE ROOM!!" + ) - command = input('COMMAND? ').upper().strip() + command = input("COMMAND? ").upper().strip() if command in f: f[command]() else: - print("ENTER ONE OF THE FOLLOWING:\n" - " NAV (TO SET COURSE)\n" - " SRS (FOR SHORT RANGE SENSOR SCAN)\n" - " LRS (FOR LONG RANGE SENSOR SCAN)\n" - " PHA (TO FIRE PHASERS)\n" - " TOR (TO FIRE PHOTON TORPEDOES)\n" - " SHE (TO RAISE OR LOWER SHIELDS)\n" - " DAM (FOR DAMAGE CONTROL REPORTS)\n" - " COM (TO CALL ON LIBRARY-COMPUTER)\n" - " XXX (TO RESIGN YOUR COMMAND)\n") + print( + "ENTER ONE OF THE FOLLOWING:\n" + " NAV (TO SET COURSE)\n" + " SRS (FOR SHORT RANGE SENSOR SCAN)\n" + " LRS (FOR LONG RANGE SENSOR SCAN)\n" + " PHA (TO FIRE PHASERS)\n" + " TOR (TO FIRE PHOTON TORPEDOES)\n" + " SHE (TO RAISE OR LOWER SHIELDS)\n" + " DAM (FOR DAMAGE CONTROL REPORTS)\n" + " COM (TO CALL ON LIBRARY-COMPUTER)\n" + " XXX (TO RESIGN YOUR COMMAND)\n" + ) if __name__ == "__main__": diff --git a/84_Super_Star_Trek/python/superstartrekins.py b/84_Super_Star_Trek/python/superstartrekins.py index 2260c8072..63736e4c6 100644 --- a/84_Super_Star_Trek/python/superstartrekins.py +++ b/84_Super_Star_Trek/python/superstartrekins.py @@ -7,9 +7,11 @@ Ported by Dave LeCompte """ + def get_yes_no(prompt): response = input(prompt).upper() - return response[0] != 'N' + return response[0] != "N" + def print_header(): for i in range(12): @@ -25,6 +27,7 @@ def print_header(): for i in range(8): print() + def print_instructions(): # Back in the 70s, at this point, the user would be prompted to # turn on their (printing) TTY to capture the output to hard copy. @@ -60,7 +63,7 @@ def print_instructions(): print(" WAY BETWEEN 1 AND 2 ...") print(" . . .") print(" VALUES MAY APPROACH 9.0, WHICH 6 7 8") - print(" ITSELF IS EQUIVALENT TO 1.0" ) + print(" ITSELF IS EQUIVALENT TO 1.0") print(" COURSE") print(" ONE WARP FACTOR IS THE SIZE OF ") print(" ONE QUADTANT. THEREFORE, TO GET") @@ -134,8 +137,7 @@ def print_instructions(): print(" OPTION 5 = GALACTIC /REGION NAME/ MAP") print(" THIS OPTION PRINTS THE NAMES OF THE SIXTEEN MAJOR ") print(" GALACTIC REGIONS REFERRED TO IN THE GAME.") - - + def main(): print_header() @@ -143,5 +145,6 @@ def main(): return print_instructions() + if __name__ == "__main__": main() diff --git a/84_Super_Star_Trek/superstartrekins.bas b/84_Super_Star_Trek/superstartrekins.bas index 9f5f3a33b..b3aa1daa6 100644 --- a/84_Super_Star_Trek/superstartrekins.bas +++ b/84_Super_Star_Trek/superstartrekins.bas @@ -44,7 +44,7 @@ 440 PRINT" WAY BETWEEN 1 AND 2 ..." 450 PRINT" . . ." 460 PRINT" VALUES MAY APPROACH 9.0, WHICH 6 7 8" -470 PRINT" ITSELF IS EQUIVALENT TO 1.0" +470 PRINT" ITSELF IS EQUIVALENT TO 1.0" 480 PRINT" COURSE" 490 PRINT" ONE WARP FACTOR IS THE SIZE OF " 500 PRINT" ONE QUADTANT. THEREFORE, TO GET" diff --git a/85_Synonym/csharp/Synonym.cs b/85_Synonym/csharp/Synonym.cs index 9d58da718..1a90fd724 100644 --- a/85_Synonym/csharp/Synonym.cs +++ b/85_Synonym/csharp/Synonym.cs @@ -80,7 +80,7 @@ private bool CheckTheResponse(string WordName, int WordIndex, string LineInput, { // Randomly display one of the five correct answer exclamations Console.WriteLine(GetAnAffirmation()); - + return true; } else @@ -109,7 +109,7 @@ private void AskForSynonyms() foreach (string[] WordList in Words) { int WordIndex = rand.Next(WordList.Length); // random word position in the current list of words - string WordName = WordList[WordIndex]; // what is that actual word + string WordName = WordList[WordIndex]; // what is that actual word bool Success = false; while (!Success) @@ -117,7 +117,7 @@ private void AskForSynonyms() // Ask for the synonym of the current word string LineInput = PromptForSynonym(WordName); - // Check the response + // Check the response Success = CheckTheResponse(WordName, WordIndex, LineInput, WordList); // Add extra line space for formatting @@ -146,4 +146,4 @@ static void Main(string[] args) } } -} \ No newline at end of file +} diff --git a/85_Synonym/javascript/synonym.js b/85_Synonym/javascript/synonym.js index ad3175b7c..e48bf77f1 100644 --- a/85_Synonym/javascript/synonym.js +++ b/85_Synonym/javascript/synonym.js @@ -12,10 +12,10 @@ function input() { var input_element; var input_str; - + return new Promise(function (resolve) { input_element = document.createElement("INPUT"); - + print("? "); input_element.setAttribute("type", "text"); input_element.setAttribute("length", "50"); diff --git a/85_Synonym/kotlin/Synonym.kt b/85_Synonym/kotlin/Synonym.kt index 386a2525e..e85b142a5 100644 --- a/85_Synonym/kotlin/Synonym.kt +++ b/85_Synonym/kotlin/Synonym.kt @@ -70,4 +70,4 @@ private val synonyms = listOf( SynonymList("PAIN", listOf("SUFFERING", "HURT", "MISERY", "DISTRESS", "ACHE", "DISCOMFORT")) ) -class SynonymList(val word: String, val synonyms: List) \ No newline at end of file +class SynonymList(val word: String, val synonyms: List) diff --git a/85_Synonym/perl/README.md b/85_Synonym/perl/README.md index f947aea0e..977a834a7 100644 --- a/85_Synonym/perl/README.md +++ b/85_Synonym/perl/README.md @@ -3,5 +3,5 @@ Original source downloaded [from Vintage Basic](http://www.vintage-basic.net/gam Conversion to [Perl](https://www.perl.org/) I used List::Util to do all the heavy work to show that perl can handle all the various -array functions. It would be interesting to see a version that handled all of this +array functions. It would be interesting to see a version that handled all of this manually as there ended up being very little code left in this program. diff --git a/85_Synonym/perl/synonym.pl b/85_Synonym/perl/synonym.pl index 37f323660..7b9ef90cd 100755 --- a/85_Synonym/perl/synonym.pl +++ b/85_Synonym/perl/synonym.pl @@ -55,4 +55,3 @@ } say "\nSynonym drill completed."; - diff --git a/85_Synonym/python/synonym.py b/85_Synonym/python/synonym.py index 02ac24e6d..046758d6c 100644 --- a/85_Synonym/python/synonym.py +++ b/85_Synonym/python/synonym.py @@ -8,7 +8,6 @@ import random - PAGE_WIDTH = 64 diff --git a/85_Synonym/ruby/synonim.rb b/85_Synonym/ruby/synonim.rb index 92d2e8c7d..d155af5b1 100644 --- a/85_Synonym/ruby/synonim.rb +++ b/85_Synonym/ruby/synonim.rb @@ -49,13 +49,13 @@ ["PAIN", "SUFFERING", "HURT", "MISERY", "DISTRESS", "ACHE", "DISCOMFORT"], ] -synonym_words.shuffle.each {|words_ar| +synonym_words.shuffle.each {|words_ar| } -synonym_words.each {|words_ar| - answer = false +synonym_words.each {|words_ar| + answer = false keyword = words_ar.shift while not answer and words_ar.length != 0 diff --git a/86_Target/csharp/Strings/TitleAndInstructions.txt b/86_Target/csharp/Strings/TitleAndInstructions.txt index 0142e4204..f883ac7a4 100644 --- a/86_Target/csharp/Strings/TitleAndInstructions.txt +++ b/86_Target/csharp/Strings/TitleAndInstructions.txt @@ -14,5 +14,3 @@ You will then proceed to shoot at the target until it is destroyed! Good luck!! - - diff --git a/86_Target/java/Target.java b/86_Target/java/Target.java index 869c443ad..4a60005d1 100644 --- a/86_Target/java/Target.java +++ b/86_Target/java/Target.java @@ -142,5 +142,3 @@ private static class TargetAttempt { double distance; } } - - diff --git a/86_Target/javascript/target.js b/86_Target/javascript/target.js index e61fba8b4..f32fc6b99 100644 --- a/86_Target/javascript/target.js +++ b/86_Target/javascript/target.js @@ -12,10 +12,10 @@ function input() { var input_element; var input_str; - + return new Promise(function (resolve) { input_element = document.createElement("INPUT"); - + print("? "); input_element.setAttribute("type", "text"); input_element.setAttribute("length", "50"); diff --git a/87_3-D_Plot/java/Plot3D.java b/87_3-D_Plot/java/Plot3D.java index a12848d8d..ee9b02341 100644 --- a/87_3-D_Plot/java/Plot3D.java +++ b/87_3-D_Plot/java/Plot3D.java @@ -8,90 +8,90 @@ *

* Note: The idea was to create a version of the 1970's BASIC game in Java, without introducing * new features - no additional text, error checking, etc has been added. - * + * * Converted from BASIC to Java by Darren Cardenas. */ - + // Java class names cannot begin with a letter, so class name 3dplot cannot be used -public class Plot3D { +public class Plot3D { + - public void play() { showIntro(); startGame(); - } // End of method play - - - private void showIntro() { - + } // End of method play + + + private void showIntro() { + System.out.println(" ".repeat(31) + "3D PLOT"); System.out.println(" ".repeat(14) + "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY"); System.out.println("\n\n\n"); - - } // End of method showIntro + + } // End of method showIntro - private void startGame() { + private void startGame() { float row = 0; int column = 0; int limit = 0; int plotVal = 0; int root = 0; - + String lineContent = ""; - + // Begin loop through all rows for (row = -30; row <= 30; row += 1.5) { - - limit = 0; - + + limit = 0; + root = 5 * (int) Math.floor((Math.sqrt(900 - row * row) / 5)); - + // Begin loop through all columns for (column = root; column >= -root; column += -5) { - + plotVal = 25 + (int) Math.floor(func(Math.sqrt(row * row + column * column)) - 0.7 * column); - + if (plotVal > limit) { - + limit = plotVal; - + // Add whitespace while (lineContent.length() < (plotVal-1)) { lineContent += " "; - } + } + + lineContent += "*"; - lineContent += "*"; - } } // End loop through all columns - - System.out.println(lineContent); - + + System.out.println(lineContent); + lineContent = ""; } // End loop through all rows - + } // End of method startGame - + // Function to be plotted public double func(double inputVal) { - - return (30 * Math.exp(-inputVal * inputVal / 100)); - + + return (30 * Math.exp(-inputVal * inputVal / 100)); + } - + public static void main(String[] args) { - + Plot3D plot = new Plot3D(); plot.play(); - + } // End of method main } // End of class Plot3D diff --git a/87_3-D_Plot/python/3dplot.py b/87_3-D_Plot/python/3dplot.py index 2dda44ff7..71757b6fa 100644 --- a/87_3-D_Plot/python/3dplot.py +++ b/87_3-D_Plot/python/3dplot.py @@ -6,21 +6,23 @@ import math + def equation(input): - return 30 * math.exp(-input * input / 100) + return 30 * math.exp(-input * input / 100) + print(" " * 32 + "3D PLOT") print(" " * 15 + "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY\n\n\n\n") -for x in range (-300, 315, 15): - x1 = x / 10 - l = 0 - y1 = 5 * math.floor(math.sqrt(900 - x1 * x1) / 5) - yPlot = [" "] * 80 - - for y in range (y1, -(y1 + 5), -5): - z = math.floor(25 + equation(math.sqrt(x1 * x1 + y * y)) - .7 * y) - if z > l: - l = z - yPlot[z] = "*" - print("".join(yPlot)) \ No newline at end of file +for x in range(-300, 315, 15): + x1 = x / 10 + l = 0 + y1 = 5 * math.floor(math.sqrt(900 - x1 * x1) / 5) + yPlot = [" "] * 80 + + for y in range(y1, -(y1 + 5), -5): + z = math.floor(25 + equation(math.sqrt(x1 * x1 + y * y)) - 0.7 * y) + if z > l: + l = z + yPlot[z] = "*" + print("".join(yPlot)) diff --git a/87_3-D_Plot/ruby/3dplot.rb b/87_3-D_Plot/ruby/3dplot.rb index 9c4e8394b..ca673e9c6 100644 --- a/87_3-D_Plot/ruby/3dplot.rb +++ b/87_3-D_Plot/ruby/3dplot.rb @@ -25,4 +25,4 @@ def main render end -main \ No newline at end of file +main diff --git a/88_3-D_Tic-Tac-Toe/README.md b/88_3-D_Tic-Tac-Toe/README.md index 678bac6b3..3fa7c6c9d 100644 --- a/88_3-D_Tic-Tac-Toe/README.md +++ b/88_3-D_Tic-Tac-Toe/README.md @@ -8,7 +8,7 @@ This version of 3-D TIC-TAC-TOE is from Dartmouth College. ### Conversion notes -The AI code for TicTacToe2 depends quite heavily on the non-structured GOTO (I can almost hear Dijkstra now) and translation is quite challenging. This code relies very heavily on GOTOs that bind the code tightly together. Comments explain where that happens in the original. +The AI code for TicTacToe2 depends quite heavily on the non-structured GOTO (I can almost hear Dijkstra now) and translation is quite challenging. This code relies very heavily on GOTOs that bind the code tightly together. Comments explain where that happens in the original. There are at least two bugs from the original BASIC: diff --git a/88_3-D_Tic-Tac-Toe/csharp/Qubic.cs b/88_3-D_Tic-Tac-Toe/csharp/Qubic.cs index 513651d6a..a01944e19 100644 --- a/88_3-D_Tic-Tac-Toe/csharp/Qubic.cs +++ b/88_3-D_Tic-Tac-Toe/csharp/Qubic.cs @@ -35,7 +35,7 @@ internal class Qubic private const double MACHINE = 5.0; private const double POTENTIAL = 0.125; private const double EMPTY = 0.0; - + // The X variable in the original BASIC. This is the Qubic board, // flattened into a 1D array. private readonly double[] Board = new double[64]; @@ -51,7 +51,7 @@ public Qubic() { } ///

/// Run the Qubic game. - /// + /// /// Show the title, prompt for instructions, then begin the game loop. /// public void Run() @@ -68,7 +68,7 @@ public void Run() /// /// Display title and attribution. - /// + /// /// Original BASIC: 50-120 /// private static void Title() @@ -82,7 +82,7 @@ private static void Title() /// /// Prompt user for game instructions. - /// + /// /// Original BASIC: 210-313 /// private static void Instructions() @@ -113,7 +113,7 @@ private static void Instructions() /// /// Prompt player for whether they would like to move first, or allow /// the machine to make the first move. - /// + /// /// Original BASIC: 440-490 /// /// true if the player wants to move first @@ -191,7 +191,7 @@ private void Loop() /// /// Prompt the user to try another game. - /// + /// /// Original BASIC: 1490-1560 /// /// true if the user wants to play again @@ -252,7 +252,7 @@ private enum PlayerAction /// /// Make the player's move based on their input. - /// + /// /// Original BASIC: 500-620 /// /// Whether the player moved or quit the program. @@ -295,7 +295,7 @@ private PlayerAction PlayerMove() /// /// Read a player move from the terminal. Move can be any integer. - /// + /// /// Original BASIC: 510-520 /// /// the move inputted @@ -307,9 +307,9 @@ private static int ReadMove() /// /// Read an integer from the terminal. - /// + /// /// Original BASIC: 520 - /// + /// /// Unlike the basic, this code will not accept any string that starts /// with a number; only full number strings are allowed. /// @@ -335,7 +335,7 @@ private static int ReadInteger() /// /// Display the board to the player. Spaces taken by the player are /// marked with "Y", while machine spaces are marked with "M". - /// + /// /// Original BASIC: 2550-2740 /// private void ShowBoard() @@ -375,9 +375,9 @@ private void ShowBoard() /// /// Check all rows for a player win. - /// + /// /// A row indicates a player win if its sum = PLAYER * 4. - /// + /// /// Original BASIC: 720-780 /// /// whether the player won in any row @@ -401,10 +401,10 @@ private bool CheckPlayerWin() /// /// Check all rows for a row that the machine could move to to win /// immediately. - /// + /// /// A row indicates a player could win immediately if it has three /// machine moves already; that is, sum = MACHINE * 3. - /// + /// /// Original Basic: 790-920 /// /// @@ -471,9 +471,9 @@ private enum MachineAction /// /// Machine decides where to move on the board, and ends the game if /// appropriate. - /// + /// /// The machine's AI tries to take the following actions (in order): - /// + /// /// 1. If the player has a row that will get them the win on their /// next turn, block that row. /// 2. If the machine can trap the player (create two different rows @@ -486,10 +486,10 @@ private enum MachineAction /// moves, and take a space in the first such plane. /// 5. Find the first open corner or center and move there. /// 6. Find the first open space and move there. - /// + /// /// If none of these actions are possible, then the board is entirely /// full, and the game results in a draw. - /// + /// /// Original BASIC: start at 930 /// /// the action the machine took @@ -528,7 +528,7 @@ private MachineAction MachineMove() /// /// Block a row with three spaces already taken by the player. - /// + /// /// Original BASIC: 930-1010 /// /// @@ -565,13 +565,13 @@ private MachineAction BlockPlayer() /// three MACHINE spaces, with the remaining space not shared between /// the two rows. The player can only block one of these traps, so the /// machine will win. - /// + /// /// If a player trap is not possible, but a row is found that is /// particularly advantageous for the machine to move to, the machine /// will try and move to a plane edge in that row. - /// + /// /// Original BASIC: 1300-1480 - /// + /// /// Lines 1440/50 of the BASIC call 2360 (MovePlaneEdge). Because it /// goes to this code only after it has found an open space marked as /// potential, it cannot reach line 2440 of that code, as that is only @@ -640,13 +640,13 @@ private MachineAction MakePlayerTrap() /// /// Block a trap that the player could create for the machine on their /// next turn. - /// + /// /// If there are no player traps to block, but a row is found that is /// particularly advantageous for the player to move to, the machine /// will try and move to a plane edge in that row. - /// + /// /// Original BASIC: 1030-1190 - /// + /// /// Lines 1160/1170 of the BASIC call 2360 (MovePlaneEdge). As with /// MakePlayerTrap, because it goes to this code only after it has /// found an open space marked as potential, it cannot reach line 2440 @@ -713,10 +713,10 @@ private MachineAction BlockMachineTrap() /// /// Either make a trap for the player or block a trap the player could /// create on their next turn. - /// + /// /// Unclear how this method could possibly end with a concession; it /// seems it can only be called if the row contains a potential move. - /// + /// /// Original BASIC: 2230-2350 /// /// the row containing the space to move to @@ -757,15 +757,15 @@ private MachineAction MakeOrBlockTrap(int row) /// /// Find a satisfactory plane on the board and move to one if that /// plane's plane edges. - /// + /// /// A plane on the board is satisfactory if it meets the following /// conditions: /// 1. Player has made exactly 4 moves on the plane. /// 2. Machine has made either 0 or one moves on the plane. /// Such a plane is one that the player could likely use to form traps. - /// + /// /// Original BASIC: 1830-2020 - /// + /// /// Line 1990 of the original basic calls 2370 (MovePlaneEdge). Only on /// this call to MovePlaneEdge can line 2440 of that method be reached, /// which surves to help this method iterate through the rows of a @@ -786,7 +786,7 @@ private MachineAction MoveByPlane() const double P4 = PLAYER * 4; const double P4_M1 = (PLAYER * 4) + MACHINE; if ( - (planeSum >= P4 && planeSum < P4 + 1) || + (planeSum >= P4 && planeSum < P4 + 1) || (planeSum >= P4_M1 && planeSum < P4_M1 + 1) ) { @@ -822,19 +822,19 @@ private MachineAction MoveByPlane() /// Given a row, move to the first space in that row that: /// 1. is a plane edge, and /// 2. has the given value in Board - /// + /// /// Plane edges are any spaces on a plane with one face exposed. The AI /// prefers to move to these spaces before others, presumably /// because they are powerful moves: a plane edge is contained on 3-4 /// winning rows of the cube. - /// + /// /// Original BASIC: 2360-2490 - /// + /// /// In the original BASIC, this code is pointed to from three different - /// locations by GOTOs: - /// - 1440/50, or MakePlayerTrap; + /// locations by GOTOs: + /// - 1440/50, or MakePlayerTrap; /// - 1160/70, or BlockMachineTrap; and - /// - 1990, or MoveByPlane. + /// - 1990, or MoveByPlane. /// At line 2440, this code jumps back to line 2000, which is in /// MoveByPlane. This makes it appear as though calling MakePlayerTrap /// or BlockPlayerTrap in the BASIC could jump into the middle of the @@ -871,12 +871,12 @@ private MachineAction MovePlaneEdge(int row, double spaceValue) // // The plane edge pieces have their row indices marked. The pattern // above shows that: - // + // // if row == 0 | 3, plane edge spaces = [1, 2] // if row == 1 | 2, plane edge spaces = [0, 3] // The below condition replaces the following BASIC code (2370): - // + // // I-(INT(I/4)*4)>1 // // which in C# would be: @@ -918,9 +918,9 @@ private MachineAction MovePlaneEdge(int row, double spaceValue) /// /// Find the first open corner or center in the board and move there. - /// + /// /// Original BASIC: 1200-1290 - /// + /// /// This is the only place where the Z variable from the BASIC code is /// used; here it is implied in the for loop. /// @@ -968,7 +968,7 @@ private MachineAction MoveAnyOpenSpace() /// /// Draw the game in the event that there are no open spaces. - /// + /// /// Original BASIC: 1810-1820 /// /// End @@ -987,22 +987,22 @@ private MachineAction DrawGame() /// /// Attempt to transform a cube coordinate to an index into Board. - /// + /// /// A valid cube coordinate is a three-digit number, where each digit /// of the number X satisfies 1 <= X <= 4. - /// + /// /// Examples: /// 111 -> 0 /// 444 -> 63 /// 232 -> 35 - /// + /// /// If the coord provided is not valid, the transformation fails. - /// + /// /// The conversion from coordinate to index is essentially a conversion /// between base 4 and base 10. - /// + /// /// Original BASIC: 525-580 - /// + /// /// This method fixes a bug in the original BASIC (525-526), which only /// checked whether the given coord satisfied 111 <= coord <= 444. This /// allows invalid coordinates such as 199 and 437, whose individual @@ -1037,15 +1037,15 @@ private static bool TryCoordToIndex(int coord, out int index) /// /// Transform a Board index into a valid cube coordinate. - /// + /// /// Examples: /// 0 -> 111 /// 63 -> 444 /// 35 -> 232 - /// + /// /// The conversion from index to coordinate is essentially a conversion /// between base 10 and base 4. - /// + /// /// Original BASIC: 1570-1610 /// /// Board index @@ -1072,7 +1072,7 @@ private static int IndexToCoord(int index) /// /// Refresh the values in RowSums to account for any changes. - /// + /// /// Original BASIC: 1640-1710 /// private void RefreshRowSums() @@ -1101,7 +1101,7 @@ private double RefreshRowSum(int row) /// /// Calculate the sum of spaces in one of the 18 cube planes in RowSums. - /// + /// /// Original BASIC: 1840-1890 /// /// the desired plane @@ -1122,14 +1122,14 @@ private double PlaneSum(int plane) /// /// Check whether the board is in a draw state, that is all spaces are /// full and neither the player nor the machine has won. - /// + /// /// The original BASIC contains a bug that if the player moves first, a /// draw will go undetected. An example series of player inputs /// resulting in such a draw (assuming player goes first): - /// + /// /// 114, 414, 144, 444, 122, 221, 112, 121, - /// 424, 332, 324, 421, 231, 232, 244, 311, - /// 333, 423, 331, 134, 241, 243, 143, 413, + /// 424, 332, 324, 421, 231, 232, 244, 311, + /// 333, 423, 331, 134, 241, 243, 143, 413, /// 142, 212, 314, 341, 432, 412, 431, 442 /// /// whether the game is a draw @@ -1160,7 +1160,7 @@ private bool CheckDraw() /// /// Reset POTENTIAL spaces in Board to EMPTY. - /// + /// /// Original BASIC: 2500-2540 /// private void ClearPotentialMoves() @@ -1176,7 +1176,7 @@ private void ClearPotentialMoves() /// /// Reset all spaces in Board to EMPTY. - /// + /// /// Original BASIC: 400-420 /// private void ClearBoard() diff --git a/88_3-D_Tic-Tac-Toe/csharp/QubicData.cs b/88_3-D_Tic-Tac-Toe/csharp/QubicData.cs index 298ee933e..1735904d7 100644 --- a/88_3-D_Tic-Tac-Toe/csharp/QubicData.cs +++ b/88_3-D_Tic-Tac-Toe/csharp/QubicData.cs @@ -3,7 +3,7 @@ /// /// Data in this class was originally given by the following DATA section in /// the BASIC program: - /// + /// /// 2030 DATA 1,49,52,4,13,61,64,16,22,39,23,38,26,42,27,43 /// 2040 DATA 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20 /// 2050 DATA 21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38 @@ -24,7 +24,7 @@ /// 2200 DATA 1,18,35,52,5,22,39,56,9,26,43,60,13,30,47,64 /// 2210 DATA 49,34,19,4,53,38,23,8,57,42,27,12,61,46,31,16 /// 2220 DATA 1,22,43,64,16,27,38,49,4,23,42,61,13,26,39,52 - /// + /// /// In short, each number is an index into the board. The data in this class /// is zero-indexed, as opposed to the original data which was one-indexed. /// @@ -33,9 +33,9 @@ internal static class QubicData /// /// The corners and centers of the Qubic board. They correspond to the /// following coordinates: - /// + /// /// [ - /// 111, 411, 414, 114, 141, 441, 444, 144, + /// 111, 411, 414, 114, 141, 441, 444, 144, /// 222, 323, 223, 322, 232, 332, 233, 333 /// ] /// @@ -57,7 +57,7 @@ internal static class QubicData // ( ) ( ) ( ) ( ) // (X) ( ) ( ) (X) - // ( ) ( ) ( ) ( ) + // ( ) ( ) ( ) ( ) // ( ) ( ) ( ) ( ) // (X) ( ) ( ) (X) @@ -68,13 +68,13 @@ internal static class QubicData /// A list of all "winning" rows in the Qubic board; that is, sets of /// four spaces that, if filled entirely by the player (or machine), /// would result in a win. - /// + /// /// Each group of four rows in the list corresponds to a plane in the /// cube, and each plane is organized so that the first and last rows /// are on the plane's edges, while the second and third rows are in /// the middle of the plane. The only exception is the last group of /// rows, which contains the corners and centers rather than a plane. - /// + /// /// The order of the rows in this list is key to how the Qubic AI /// decides its next move. /// @@ -123,7 +123,7 @@ internal static class QubicData // ( ) ( ) ( ) ( ) // ( ) ( ) ( ) ( ) // ( ) ( ) ( ) ( ) - // ( ) ( ) ( ) ( ) + // ( ) ( ) ( ) ( ) { 16,17,18,19, }, { 20,21,22,23, }, @@ -297,7 +297,7 @@ internal static class QubicData // (4) ( ) ( ) ( ) // (4) ( ) ( ) ( ) - // (4) ( ) ( ) ( ) + // (4) ( ) ( ) ( ) // (4) ( ) ( ) ( ) { 0, 4, 8, 12, }, @@ -463,7 +463,7 @@ internal static class QubicData // ( ) ( ) ( ) ( ) // ( ) ( ) ( ) ( ) // (1) (2) (3) (4) - // ( ) ( ) ( ) ( ) + // ( ) ( ) ( ) ( ) // ( ) ( ) ( ) ( ) // (1) (2) (3) (4) @@ -531,7 +531,7 @@ internal static class QubicData { 60,45,30,15, }, // (1) ( ) ( ) (3) - // ( ) ( ) ( ) ( ) + // ( ) ( ) ( ) ( ) // ( ) ( ) ( ) ( ) // (4) ( ) ( ) (2) diff --git a/88_3-D_Tic-Tac-Toe/javascript/qubit.js b/88_3-D_Tic-Tac-Toe/javascript/qubit.js index 9d73734d6..0057619fb 100644 --- a/88_3-D_Tic-Tac-Toe/javascript/qubit.js +++ b/88_3-D_Tic-Tac-Toe/javascript/qubit.js @@ -12,10 +12,10 @@ function input() { var input_element; var input_str; - + return new Promise(function (resolve) { input_element = document.createElement("INPUT"); - + print("? "); input_element.setAttribute("type", "text"); input_element.setAttribute("length", "50"); @@ -357,9 +357,9 @@ async function main() } while (++i <= 76) ; if (i <= 76) continue; - + process_board(); - + i = 1; do { la[i] = xa[ma[i][1]] + xa[ma[i][2]] + xa[ma[i][3]] + xa[ma[i][4]]; @@ -387,7 +387,7 @@ async function main() } while (++i <= 76) ; if (i <= 76) continue; - + for (k = 1; k <= 18; k++) { p = 0; for (i = 4 * k - 3; i <= 4 * k; i++) { diff --git a/88_3-D_Tic-Tac-Toe/python/qubit.py b/88_3-D_Tic-Tac-Toe/python/qubit.py index e8840a872..f6a752b98 100644 --- a/88_3-D_Tic-Tac-Toe/python/qubit.py +++ b/88_3-D_Tic-Tac-Toe/python/qubit.py @@ -8,7 +8,8 @@ class Move(Enum): - """ Game status and types of machine move """ + """Game status and types of machine move""" + HUMAN_WIN = 0 MACHINE_WIN = 1 DRAW = 2 @@ -20,104 +21,107 @@ class Move(Enum): NICE_TRY = 8 CONCEDES = 9 + class Player(Enum): EMPTY = 0 HUMAN = 1 MACHINE = 2 + class TicTacToe3D: - """ The game logic for 3D Tic Tac Toe and the machine opponent """ + """The game logic for 3D Tic Tac Toe and the machine opponent""" def __init__(self): - + # 4x4x4 board keeps track of which player occupies each place # and used by machine to work out its strategy self.board = [0] * 64 # starting move - self.corners = [0, 48, 51, 3, 12, 60, 63, 15, - 21, 38, 22, 37, 25, 41, 26, 42] + self.corners = [0, 48, 51, 3, 12, 60, 63, 15, 21, 38, 22, 37, 25, 41, 26, 42] # lines to check for end game - self.lines = [[0, 1, 2, 3], - [4, 5, 6, 7], - [8, 9, 10, 11], - [12, 13, 14, 15], - [16, 17, 18, 19], - [20, 21, 22, 23], - [24, 25, 26, 27], - [28, 29, 30, 31], - [32, 33, 34, 35], - [36, 37, 38, 39], - [40, 41, 42, 43], - [44, 45, 46, 47], - [48, 49, 50, 51], - [52, 53, 54, 55], - [56, 57, 58, 59], - [60, 61, 62, 63], - [0, 16, 32, 48], - [4, 20, 36, 52], - [8, 24, 40, 56], - [12, 28, 44, 60], - [1, 17, 33, 49], - [5, 21, 37, 53], - [9, 25, 41, 57], - [13, 29, 45, 61], - [2, 18, 34, 50], - [6, 22, 38, 54], - [10, 26, 42, 58], - [14, 30, 46, 62], - [3, 19, 35, 51], - [7, 23, 39, 55], - [11, 27, 43, 59], - [15, 31, 47, 63], - [0, 4, 8, 12], - [16, 20, 24, 28], - [32, 36, 40, 44], - [48, 52, 56, 60], - [1, 5, 9, 13], - [17, 21, 25, 29], - [33, 37, 41, 45], - [49, 53, 57, 61], - [2, 6, 10, 14], - [18, 22, 26, 30], - [34, 38, 42, 46], - [50, 54, 58, 62], - [3, 7, 11, 15], - [19, 23, 27, 31], - [35, 39, 43, 47], - [51, 55, 59, 63], - [0, 5, 10, 15], - [16, 21, 26, 31], - [32, 37, 42, 47], - [48, 53, 58, 63], - [12, 9, 6, 3], - [28, 25, 22, 19], - [44, 41, 38, 35], - [60, 57, 54, 51], - [0, 20, 40, 60], - [1, 21, 41, 61], - [2, 22, 42, 62], - [3, 23, 43, 63], - [48, 36, 24, 12], - [49, 37, 25, 13], - [50, 38, 26, 14], - [51, 39, 27, 15], - [0, 17, 34, 51], - [4, 21, 38, 55], - [8, 25, 42, 59], - [12, 29, 46, 63], - [48, 33, 18, 3], - [52, 37, 22, 7], - [56, 41, 26, 11], - [60, 45, 30, 15], - [0, 21, 42, 63], - [15, 26, 37, 48], - [3, 22, 41, 60], - [12, 25, 38, 51]] + self.lines = [ + [0, 1, 2, 3], + [4, 5, 6, 7], + [8, 9, 10, 11], + [12, 13, 14, 15], + [16, 17, 18, 19], + [20, 21, 22, 23], + [24, 25, 26, 27], + [28, 29, 30, 31], + [32, 33, 34, 35], + [36, 37, 38, 39], + [40, 41, 42, 43], + [44, 45, 46, 47], + [48, 49, 50, 51], + [52, 53, 54, 55], + [56, 57, 58, 59], + [60, 61, 62, 63], + [0, 16, 32, 48], + [4, 20, 36, 52], + [8, 24, 40, 56], + [12, 28, 44, 60], + [1, 17, 33, 49], + [5, 21, 37, 53], + [9, 25, 41, 57], + [13, 29, 45, 61], + [2, 18, 34, 50], + [6, 22, 38, 54], + [10, 26, 42, 58], + [14, 30, 46, 62], + [3, 19, 35, 51], + [7, 23, 39, 55], + [11, 27, 43, 59], + [15, 31, 47, 63], + [0, 4, 8, 12], + [16, 20, 24, 28], + [32, 36, 40, 44], + [48, 52, 56, 60], + [1, 5, 9, 13], + [17, 21, 25, 29], + [33, 37, 41, 45], + [49, 53, 57, 61], + [2, 6, 10, 14], + [18, 22, 26, 30], + [34, 38, 42, 46], + [50, 54, 58, 62], + [3, 7, 11, 15], + [19, 23, 27, 31], + [35, 39, 43, 47], + [51, 55, 59, 63], + [0, 5, 10, 15], + [16, 21, 26, 31], + [32, 37, 42, 47], + [48, 53, 58, 63], + [12, 9, 6, 3], + [28, 25, 22, 19], + [44, 41, 38, 35], + [60, 57, 54, 51], + [0, 20, 40, 60], + [1, 21, 41, 61], + [2, 22, 42, 62], + [3, 23, 43, 63], + [48, 36, 24, 12], + [49, 37, 25, 13], + [50, 38, 26, 14], + [51, 39, 27, 15], + [0, 17, 34, 51], + [4, 21, 38, 55], + [8, 25, 42, 59], + [12, 29, 46, 63], + [48, 33, 18, 3], + [52, 37, 22, 7], + [56, 41, 26, 11], + [60, 45, 30, 15], + [0, 21, 42, 63], + [15, 26, 37, 48], + [3, 22, 41, 60], + [12, 25, 38, 51], + ] def get(self, x, y, z): - m = self.board[4*(4*z + y) + x] + m = self.board[4 * (4 * z + y) + x] if m == 40: return Player.MACHINE elif m == 8: @@ -126,13 +130,13 @@ def get(self, x, y, z): return Player.EMPTY def move3D(self, x, y, z, player): - m = 4*(4*z + y) + x + m = 4 * (4 * z + y) + x return self.move(m, player) def move(self, m, player): if self.board[m] > 1: return False - + if player == Player.MACHINE: self.board[m] = 40 else: @@ -165,7 +169,7 @@ def clearStrategyMarks(self): self.board[i] = 0 def markAndMove(self, vlow, vhigh, vmove): - """ + """ mark lines that can potentially win the game for the human or the machine and choose best place to play """ @@ -187,13 +191,15 @@ def markAndMove(self, vlow, vhigh, vmove): return None def machineMove(self): - """ machine works out what move to play """ + """machine works out what move to play""" self.clearStrategyMarks() self.evaluateLines() - for value, event in [(32, self.humanWin), - (120, self.machineWin), - (24, self.blockHumanWin)]: + for value, event in [ + (32, self.humanWin), + (120, self.machineWin), + (24, self.blockHumanWin), + ]: for i in range(76): if self.lineValues[i] == value: return event(i) @@ -210,12 +216,12 @@ def machineMove(self): for k in range(18): value = 0 - for i in range(4*k, 4*k+4): + for i in range(4 * k, 4 * k + 4): for j in range(4): value += self.board[self.lines[i][j]] if (32 <= value < 40) or (72 <= value < 80): for s in [1, 0]: - for i in range(4*k, 4*k+4): + for i in range(4 * k, 4 * k + 4): m = self.moveDiagonals(i, s) if m != None: return m @@ -231,7 +237,7 @@ def machineMove(self): return (Move.LIKES, i) return (Move.DRAW, -1) - + def humanWin(self, i): return (Move.HUMAN_WIN, -1, i) @@ -249,9 +255,8 @@ def blockHumanWin(self, i): return (Move.NICE_TRY, m) return None - def moveTriple(self, i): - """ make two lines-of-3 or prevent human from doing this """ + """make two lines-of-3 or prevent human from doing this""" for j in range(4): m = self.lines[i][j] if self.board[m] == 1: @@ -273,12 +278,12 @@ def moveDiagonals(self, i, s): return (Move.TAKES, m) return None + class Qubit: - def moveCode(self, board, m): x, y, z = board.get3DPosition(m) - return "{:d}{:d}{:d}".format(z+1, y+1, x+1) - + return f"{z + 1:d}{y + 1:d}{x + 1:d}" + def showWin(self, board, i): for m in board.lines[i]: print(self.moveCode(board, m)) @@ -290,10 +295,10 @@ def showBoard(self, board): print(" " * y, end="") for x in range(4): p = board.get(x, y, z) - print("({}) ".format(c[p.value]), end="") + print(f"({c[p.value]}) ", end="") print("\n") print("\n") - + def humanMove(self, board): print("") c = "1234" @@ -310,13 +315,13 @@ def humanMove(self, board): z = c.find(h[0]) if board.move3D(x, y, z, Player.HUMAN): break - + print("That square is used. Try again.") else: print("Incorrect move. Retype it--") return True - + def play(self): print("Qubic\n") print("Create Computing Morristown, New Jersey\n\n\n") @@ -325,9 +330,9 @@ def play(self): if len(c) >= 1 and (c[0] in "ynYN"): break print("Incorrect answer. Please type 'yes' or 'no.") - + c = c.lower() - if c[0] == 'y': + if c[0] == "y": print("The game is Tic-Tac-Toe in a 4 x 4 x 4 cube.") print("Each move is indicated by a 3 digit number, with each") print("digit between 1 and 4 inclusive. The digits indicate the") @@ -341,8 +346,6 @@ def play(self): print("To stop the program run, type 1 as your move.\n\n") - - play_again = True while play_again: board = TicTacToe3D() @@ -355,12 +358,14 @@ def play(self): skipHuman = s[0] in "nN" - move_text = ["Machine moves to", - "Machine likes", - "Machine takes", - "Let's see you get out of this: Machine moves to", - "You fox. Just in the nick of time, machine moves to", - "Nice try. Machine moves to"] + move_text = [ + "Machine moves to", + "Machine likes", + "Machine takes", + "Let's see you get out of this: Machine moves to", + "You fox. Just in the nick of time, machine moves to", + "Nice try. Machine moves to", + ] while True: if not skipHuman: @@ -374,7 +379,11 @@ def play(self): self.showWin(board, m[2]) break elif m[0] == Move.MACHINE_WIN: - print("Machine moves to {}, and wins as follows".format(self.moveCode(board, m[1]))) + print( + "Machine moves to {}, and wins as follows".format( + self.moveCode(board, m[1]) + ) + ) self.showWin(board, m[2]) break elif m[0] == Move.DRAW: @@ -398,8 +407,7 @@ def play(self): print("Incorrect answer. Please Type 'yes' or 'no'.") play_again = x[0] in "yY" - - + if __name__ == "__main__": game = Qubit() diff --git a/88_3-D_Tic-Tac-Toe/qubit.bas b/88_3-D_Tic-Tac-Toe/qubit.bas index 8dadf79e9..473e955aa 100644 --- a/88_3-D_Tic-Tac-Toe/qubit.bas +++ b/88_3-D_Tic-Tac-Toe/qubit.bas @@ -92,7 +92,7 @@ 920 GOTO 1490 930 IF L(I)<>3 THEN 690 940 PRINT "NICE TRY. MACHINE MOVES TO"; -950 FOR J=1 TO 4 +950 FOR J=1 TO 4 960 LET M=M(I,J) 970 IF X(M)<>0 THEN 1010 980 LET X(M)=5 diff --git a/89_Tic-Tac-Toe/csharp/tictactoe2/Program.cs b/89_Tic-Tac-Toe/csharp/tictactoe2/Program.cs index 4bfe888f2..59de85862 100644 --- a/89_Tic-Tac-Toe/csharp/tictactoe2/Program.cs +++ b/89_Tic-Tac-Toe/csharp/tictactoe2/Program.cs @@ -67,7 +67,7 @@ char printBoard() { Console.Write("\n"); } } else { - Console.Write("!"); + Console.Write("!"); } } // horizontal check @@ -145,7 +145,7 @@ int computerMove(int lastMove) { return 6; } // check cross - int crossIndex = boardMap[getIndex(index + 4)]; + int crossIndex = boardMap[getIndex(index + 4)]; if (board[crossIndex] == ' ') { return crossIndex; } @@ -214,7 +214,7 @@ int computerMove(int lastMove) { if (board[stepBackward3] == ' ') { return stepBackward3; } - int crossIndex = boardMap[getIndex(index + 4)]; + int crossIndex = boardMap[getIndex(index + 4)]; if (board[crossIndex] == ' ') { return crossIndex; } diff --git a/89_Tic-Tac-Toe/java/src/Board.java b/89_Tic-Tac-Toe/java/src/Board.java index 834c91cab..361643877 100644 --- a/89_Tic-Tac-Toe/java/src/Board.java +++ b/89_Tic-Tac-Toe/java/src/Board.java @@ -11,8 +11,8 @@ public Board() { } } - - /** + + /** * Place 'X' or 'O' on the board position passed * @param position * @param player @@ -26,13 +26,13 @@ public void setArr(int position, char player) { } public void printBoard() { - System.out.format("%-3c ! %-3c ! %-3c\n----+----+----\n%-3c ! %-3c ! %-3c\n----+----+----\n%-3c ! %-3c ! %-3c\n", + System.out.format("%-3c ! %-3c ! %-3c\n----+----+----\n%-3c ! %-3c ! %-3c\n----+----+----\n%-3c ! %-3c ! %-3c\n", this.arr[0], this.arr[1], this.arr[2], this.arr[3], this.arr[4], this.arr[5], this.arr[6], this.arr[7], this.arr[8] ); - } + } + - - /** + /** * @param x * @return the value of the char at a given position */ @@ -40,37 +40,37 @@ public char getBoardValue(int x) { return arr[x-1]; } - - /** + + /** * Go through the board and check for win (horizontal, diagonal, vertical) * @param player * @return whether a win has occured */ public boolean checkWin(char player) { - if(this.arr[0] == player && this.arr[1] == player && this.arr[2] == player) + if(this.arr[0] == player && this.arr[1] == player && this.arr[2] == player) return true; - - if(this.arr[3] == player && this.arr[4] == player && this.arr[5] == player) + + if(this.arr[3] == player && this.arr[4] == player && this.arr[5] == player) return true; - - if(this.arr[6] == player && this.arr[7] == player && this.arr[8] == player) + + if(this.arr[6] == player && this.arr[7] == player && this.arr[8] == player) return true; - + if(this.arr[0] == player && this.arr[4] == player && this.arr[8] == player) return true; - + if(this.arr[2] == player && this.arr[4] == player && this.arr[6] == player) return true; - if(this.arr[0] == player && this.arr[3] == player && this.arr[6] == player) + if(this.arr[0] == player && this.arr[3] == player && this.arr[6] == player) return true; - if(this.arr[1] == player && this.arr[4] == player && this.arr[7] == player) + if(this.arr[1] == player && this.arr[4] == player && this.arr[7] == player) return true; - if(this.arr[2] == player && this.arr[5] == player && this.arr[8] == player) + if(this.arr[2] == player && this.arr[5] == player && this.arr[8] == player) return true; return false; @@ -80,9 +80,9 @@ public boolean checkDraw() { if(this.getBoardValue(1) != ' ' && this.getBoardValue(2) != ' ' && this.getBoardValue(3) != ' ' && this.getBoardValue(4) != ' ' && this.getBoardValue(5) != ' ' && this.getBoardValue(6) != ' ' && this.getBoardValue(7) != ' ' && this.getBoardValue(8) != ' ' && this.getBoardValue(9) != ' ' ) { return true; } - } - - return false; + } + + return false; } /** * Reset the board diff --git a/89_Tic-Tac-Toe/java/src/TicTacToe2.java b/89_Tic-Tac-Toe/java/src/TicTacToe2.java index a17ec3e7f..a2467b9df 100644 --- a/89_Tic-Tac-Toe/java/src/TicTacToe2.java +++ b/89_Tic-Tac-Toe/java/src/TicTacToe2.java @@ -148,9 +148,9 @@ public static void main(String[] args) { System.out.println("THATS NOT 'Y' OR 'N', TRY AGAIN"); in.nextLine(); } - } + } break; - } + } } } diff --git a/89_Tic-Tac-Toe/javascript/tictactoe1.js b/89_Tic-Tac-Toe/javascript/tictactoe1.js index fce4b7da4..8596febfc 100644 --- a/89_Tic-Tac-Toe/javascript/tictactoe1.js +++ b/89_Tic-Tac-Toe/javascript/tictactoe1.js @@ -12,10 +12,10 @@ function input() { var input_element; var input_str; - + return new Promise(function (resolve) { input_element = document.createElement("INPUT"); - + print("? "); input_element.setAttribute("type", "text"); input_element.setAttribute("length", "50"); @@ -78,19 +78,19 @@ async function main() print("\n"); a = 9; m = a; - + computer_moves(); print("YOUR MOVE"); m = parseInt(await input()); - + p = m; b = mf(p + 1); m = b; - + computer_moves(); print("YOUR MOVE"); m = parseInt(await input()); - + q = m; if (q != mf(b + 4)) { c = mf(b + 4); @@ -99,7 +99,7 @@ async function main() print("AND WINS ********\n"); continue; } - + c = mf(b + 2); m = c; @@ -115,7 +115,7 @@ async function main() print("AND WINS ********\n"); continue; } - + if (p % 2 == 0) { d = mf(c + 7); m = d; @@ -123,14 +123,14 @@ async function main() print("AND WINS ********\n"); continue; } - + d = mf(c + 3); m = d; - + computer_moves(); print("YOUR MOVE"); m = parseInt(await input()); - + s = m; if (s != mf(d + 4)) { e = mf(d + 4); diff --git a/89_Tic-Tac-Toe/javascript/tictactoe2.js b/89_Tic-Tac-Toe/javascript/tictactoe2.js index beab1df6d..9db5f99b7 100644 --- a/89_Tic-Tac-Toe/javascript/tictactoe2.js +++ b/89_Tic-Tac-Toe/javascript/tictactoe2.js @@ -12,10 +12,10 @@ function input() { var input_element; var input_str; - + return new Promise(function (resolve) { input_element = document.createElement("INPUT"); - + print("? "); input_element.setAttribute("type", "text"); input_element.setAttribute("length", "50"); diff --git a/89_Tic-Tac-Toe/kotlin/Board.kt b/89_Tic-Tac-Toe/kotlin/Board.kt index 287a8d370..e70d1be3b 100644 --- a/89_Tic-Tac-Toe/kotlin/Board.kt +++ b/89_Tic-Tac-Toe/kotlin/Board.kt @@ -77,4 +77,4 @@ class Board { fun clear() { boxes = arrayOfNulls(9) } -} \ No newline at end of file +} diff --git a/89_Tic-Tac-Toe/pascal/tictactoe1.pas b/89_Tic-Tac-Toe/pascal/tictactoe1.pas index 2329ce79f..2fed68d75 100644 --- a/89_Tic-Tac-Toe/pascal/tictactoe1.pas +++ b/89_Tic-Tac-Toe/pascal/tictactoe1.pas @@ -86,18 +86,18 @@ function padLeft(m: string; n: integer): string; writeln('AND WINS ********'); end end - else + else begin d := move(c + 4); computerMoves(d); writeln('AND WINS ********'); end end - else + else begin c := move(b + 4); computerMoves(c); writeln('AND WINS ********'); end; end; -end. \ No newline at end of file +end. diff --git a/89_Tic-Tac-Toe/python/tictactoe2.py b/89_Tic-Tac-Toe/python/tictactoe2.py index 181e86ebf..4f0aae67c 100755 --- a/89_Tic-Tac-Toe/python/tictactoe2.py +++ b/89_Tic-Tac-Toe/python/tictactoe2.py @@ -3,16 +3,16 @@ class OccupiedBy(Enum): - COMPUTER=-1 - EMPTY=0 - PLAYER=1 + COMPUTER = -1 + EMPTY = 0 + PLAYER = 1 class Winner(Enum): - NONE=0 - COMPUTER=1 - PLAYER=2 - DRAW=3 + NONE = 0 + COMPUTER = 1 + PLAYER = 2 + DRAW = 3 class Space(Enum): @@ -30,14 +30,26 @@ class Space(Enum): def line_170(board, g, h, j, k): if g == OccupiedBy.Player: if board[Space.MID_CENTER] == g: - if board[Space.TOP_RIGHT] == g and board[Space.BOTTOM_LEFT] is OccupiedBy.EMPTY: # Line 171 - return Space.BOTTOM_LEFT # Line 187 - elif board[Space.BOTTOM_RIGHT] == g and board[Space.TOP_LEFT] is OccupiedBy.EMPTY: # Line 172 - return Space.TOP_LEFT # Line 181 - elif board[Space.BOTTOM_LEFT] == g and board[Space.TOP_RIGHT] is OccupiedBy.EMPTY: # Line 173 - return Space.TOP_RIGHT # Line 183 - elif board[Space.BOTTOM_RIGHT] is OccupiedBy.PLAYER and board[Space.TOP_RIGHT] is OccupiedBy.EMPTY: # Line 174 - return Space.TOP_RIGHT # Line 189 + if ( + board[Space.TOP_RIGHT] == g + and board[Space.BOTTOM_LEFT] is OccupiedBy.EMPTY + ): # Line 171 + return Space.BOTTOM_LEFT # Line 187 + elif ( + board[Space.BOTTOM_RIGHT] == g + and board[Space.TOP_LEFT] is OccupiedBy.EMPTY + ): # Line 172 + return Space.TOP_LEFT # Line 181 + elif ( + board[Space.BOTTOM_LEFT] == g + and board[Space.TOP_RIGHT] is OccupiedBy.EMPTY + ): # Line 173 + return Space.TOP_RIGHT # Line 183 + elif ( + board[Space.BOTTOM_RIGHT] is OccupiedBy.PLAYER + and board[Space.TOP_RIGHT] is OccupiedBy.EMPTY + ): # Line 174 + return Space.TOP_RIGHT # Line 189 elif g is OccupiedBy.COMPUTER: g = OccupiedBy.PLAYER h = OccupiedBy.COMPUTER @@ -45,30 +57,32 @@ def line_170(board, g, h, j, k): def line_150(board, g, h, j, k): - if board[k] != g: # line 150 - if (board[k] == h # line 160 - or board[k + 6] != g # line 161 - or board[k + 3] != g): # line 162 - return -1 # Goto 170 + if board[k] != g: # line 150 + if ( + board[k] == h # line 160 + or board[k + 6] != g # line 161 + or board[k + 3] != g + ): # line 162 + return -1 # Goto 170 else: return k + 3 # Line 163 - elif board[k + 6] != g: # line 152 - if board[k + 6] != 0 or board[k + 3] != g: # line 165 - return -1 # Goto 170 - elif board[k + 3]: # line 156 - return - 1 + elif board[k + 6] != g: # line 152 + if board[k + 6] != 0 or board[k + 3] != g: # line 165 + return -1 # Goto 170 + elif board[k + 3]: # line 156 + return -1 return k + 6 def line_120(board, g, h, j, k): if board[j] != g: - if board[j] == h or board[j+2] != g or board[j+1] != g: + if board[j] == h or board[j + 2] != g or board[j + 1] != g: if board[k] != g: - if board[k + 6] != g and (board[k + 6] != 0 or board[k+3] != g): + if board[k + 6] != g and (board[k + 6] != 0 or board[k + 3] != g): # 450 IF G=1 THEN 465 pass - elif board[j + 2] is not g: # Line 122 + elif board[j + 2] is not g: # Line 122 pass elif board[j + 1] is not OccupiedBy.EMPTY: pass @@ -76,7 +90,7 @@ def line_120(board, g, h, j, k): def line_118(board, g, h): for j in range(7): - for k in range (3): + for k in range(3): return line_120(board, g, h, j, k) @@ -86,15 +100,23 @@ def think(board, g, h, moves): return Space.MID_CENTER if board[Space.MID_CENTER] is OccupiedBy.PLAYER: - if board[Space.TOP_CENTER] is OccupiedBy.PLAYER and board[Space.TOP_LEFT] is OccupiedBy.EMPTY \ - or board[Space.MID_LEFT] is OccupiedBy.PLAYER and board[Space.TOP_LEFT] is OccupiedBy.EMPTY: - return Space.BOT_LEFT - elif board[Space.MID_RIGHT] is OccupiedBy.PLAYER and board[Space.BOT_RIGHT] is OccupiedBy.EMPTY \ - or board[Space.BOT_CENTER] is OccupiedBy.PLAYER and board[Space.BOT_RIGHT] is OccupiedBy.EMPTY: - return Space.BOT_RIGHT + if ( + board[Space.TOP_CENTER] is OccupiedBy.PLAYER + and board[Space.TOP_LEFT] is OccupiedBy.EMPTY + or board[Space.MID_LEFT] is OccupiedBy.PLAYER + and board[Space.TOP_LEFT] is OccupiedBy.EMPTY + ): + return Space.BOT_LEFT + elif ( + board[Space.MID_RIGHT] is OccupiedBy.PLAYER + and board[Space.BOT_RIGHT] is OccupiedBy.EMPTY + or board[Space.BOT_CENTER] is OccupiedBy.PLAYER + and board[Space.BOT_RIGHT] is OccupiedBy.EMPTY + ): + return Space.BOT_RIGHT if g == OccupiedBy.PLAYER: - j = 3 * int((moves-1) / 3) + j = 3 * int((moves - 1) / 3) if move == j + 1: k = 1 if move == j + 2: @@ -105,42 +127,47 @@ def think(board, g, h, moves): def render_board(board, space_mapping): - vertical_divider = '!' - horizontal_divider = '---+---+---' + vertical_divider = "!" + horizontal_divider = "---+---+---" lines = [] lines.append(vertical_divider.join(space_mapping[space] for space in board[0:3])) lines.append(horizontal_divider) lines.append(vertical_divider.join(space_mapping[space] for space in board[3:6])) lines.append(horizontal_divider) lines.append(vertical_divider.join(space_mapping[space] for space in board[6:9])) - return '\n'.join(lines) + return "\n".join(lines) def determine_winner(board, g): # Check for matching horizontal lines - for i in range(Space.TOP_LEFT.value, Space.BOT_LEFT.value + 1, 3): # Line 1095 - if board[i] != board[i+1] or board[i] != board[i+2]: # Lines 1100 and 1105 - continue # First third of Line 1115 - elif board[i] == OccupiedBy.COMPUTER: # + for i in range(Space.TOP_LEFT.value, Space.BOT_LEFT.value + 1, 3): # Line 1095 + if board[i] != board[i + 1] or board[i] != board[i + 2]: # Lines 1100 and 1105 + continue # First third of Line 1115 + elif board[i] == OccupiedBy.COMPUTER: # return Winner.COMPUTER elif board[i] == OccupiedBy.PLAYER: return Winner.PLAYER # Check for matching vertical lines - for i in range(Space.TOP_LEFT.value, Space.TOP_RIGHT.value + 1, 1): # Second third of Line 1115 - if board[i] != board[i+3] or board[i] != board[i+6]: # Last third of Line 1115 - continue # First third of 1150 - elif board[i] == OccupiedBy.COMPUTER: # Line 1135 + for i in range( + Space.TOP_LEFT.value, Space.TOP_RIGHT.value + 1, 1 + ): # Second third of Line 1115 + if ( + board[i] != board[i + 3] or board[i] != board[i + 6] + ): # Last third of Line 1115 + continue # First third of 1150 + elif board[i] == OccupiedBy.COMPUTER: # Line 1135 return Winner.COMPUTER - elif board[i] == OccupiedBy.PLAYER: # Line 1137 + elif board[i] == OccupiedBy.PLAYER: # Line 1137 return Winner.PLAYER # Check diagonals if any(space is OccupiedBy.EMPTY for space in board): if board[Space.MID_CENTER.value] != g: return Winner.NONE - elif (board[Space.TOP_LEFT.value] == g and board[Space.BOT_RIGHT.value] == g) or \ - (board[Space.BOT_LEFT.value] == g and board[Space.TOP_RIGHT.value] == g): + elif ( + board[Space.TOP_LEFT.value] == g and board[Space.BOT_RIGHT.value] == g + ) or (board[Space.BOT_LEFT.value] == g and board[Space.TOP_RIGHT.value] == g): return Winner.COMPUTER if g is OccupiedBy.COMPUTER else Winner.PLAYER else: return Winner.NONE @@ -149,10 +176,11 @@ def determine_winner(board, g): def computer_think(board): - empty_indices = [index for index, space in enumerate(board) - if space is OccupiedBy.EMPTY] + empty_indices = [ + index for index, space in enumerate(board) if space is OccupiedBy.EMPTY + ] - return empty_indices[0] + return empty_indices[0] def prompt_player(board): @@ -170,23 +198,23 @@ def prompt_player(board): def play(): - print(' '*30 + 'TIC-TAC-TOE') - print(' '*15 + 'CREATIVE COMPUTING MORRISTOWN, NEW JERSEY') - print('\n\n') + print(" " * 30 + "TIC-TAC-TOE") + print(" " * 15 + "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY") + print("\n\n") - print('THE BOARD IS NUMBERED:') - print(' 1 2 3') - print(' 4 5 6') - print(' 7 8 9') - print('\n\n') + print("THE BOARD IS NUMBERED:") + print(" 1 2 3") + print(" 4 5 6") + print(" 7 8 9") + print("\n\n") # Default state board = [OccupiedBy.EMPTY] * 9 current_player = OccupiedBy.PLAYER space_mapping = { - OccupiedBy.EMPTY: ' ', - OccupiedBy.PLAYER: ' X ', - OccupiedBy.COMPUTER: ' O ' + OccupiedBy.EMPTY: " ", + OccupiedBy.PLAYER: " X ", + OccupiedBy.COMPUTER: " O ", } symbol = input("DO YOU WANT 'X' OR 'O'? ").upper() @@ -194,8 +222,8 @@ def play(): # If the player doesn't choose X, then assume you want O # and the computer goes first. if symbol != "X": - space_mapping[OccupiedBy.PLAYER] = ' O ' - space_mapping[OccupiedBy.COMPUTER] = ' X ' + space_mapping[OccupiedBy.PLAYER] = " O " + space_mapping[OccupiedBy.COMPUTER] = " X " current_player = OccupiedBy.COMPUTER while True: @@ -215,8 +243,8 @@ def play(): winner = determine_winner(board, current_player) if winner is not Winner.NONE: - print(winner) - break + print(winner) + break if current_player is OccupiedBy.COMPUTER: current_player = OccupiedBy.PLAYER @@ -224,5 +252,5 @@ def play(): current_player = OccupiedBy.COMPUTER -if __name__ == '__main__': +if __name__ == "__main__": play() diff --git a/89_Tic-Tac-Toe/rust/README.md b/89_Tic-Tac-Toe/rust/README.md index d05c9af4b..7ff91cd1b 100644 --- a/89_Tic-Tac-Toe/rust/README.md +++ b/89_Tic-Tac-Toe/rust/README.md @@ -3,4 +3,3 @@ README.md Original source downloaded from Vintage Basic Conversion to Rust - diff --git a/90_Tower/csharp/Models/Needle.cs b/90_Tower/csharp/Models/Needle.cs index 1cd929faa..8ea67aa4f 100644 --- a/90_Tower/csharp/Models/Needle.cs +++ b/90_Tower/csharp/Models/Needle.cs @@ -30,4 +30,4 @@ public IEnumerator GetEnumerator() => IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); } -} \ No newline at end of file +} diff --git a/90_Tower/csharp/Models/Towers.cs b/90_Tower/csharp/Models/Towers.cs index 4b03b933b..0625a5b75 100644 --- a/90_Tower/csharp/Models/Towers.cs +++ b/90_Tower/csharp/Models/Towers.cs @@ -84,4 +84,4 @@ public TowersEnumerator(Needle[] needles) public void Reset() => _enumerators.ForEach(e => e.Reset()); } } -} \ No newline at end of file +} diff --git a/90_Tower/csharp/Resources/DiskCountPrompt.txt b/90_Tower/csharp/Resources/DiskCountPrompt.txt index a45c3461d..454960fc6 100644 --- a/90_Tower/csharp/Resources/DiskCountPrompt.txt +++ b/90_Tower/csharp/Resources/DiskCountPrompt.txt @@ -1 +1 @@ -How many disks do you want to move (7 is max) \ No newline at end of file +How many disks do you want to move (7 is max) diff --git a/90_Tower/csharp/Resources/DiskCountQuit.txt b/90_Tower/csharp/Resources/DiskCountQuit.txt index b573854da..b33b3c51d 100644 --- a/90_Tower/csharp/Resources/DiskCountQuit.txt +++ b/90_Tower/csharp/Resources/DiskCountQuit.txt @@ -1,2 +1,2 @@ All right, wise guy, if you can't play the game right, I'll -just take my puzzle and go home. So long. \ No newline at end of file +just take my puzzle and go home. So long. diff --git a/90_Tower/csharp/Resources/DiskCountRetry.txt b/90_Tower/csharp/Resources/DiskCountRetry.txt index c8ec4b102..4857ffa41 100644 --- a/90_Tower/csharp/Resources/DiskCountRetry.txt +++ b/90_Tower/csharp/Resources/DiskCountRetry.txt @@ -1 +1 @@ -Sorry, but i can't do that job for you. \ No newline at end of file +Sorry, but i can't do that job for you. diff --git a/90_Tower/csharp/Resources/DiskNotInPlay.txt b/90_Tower/csharp/Resources/DiskNotInPlay.txt index 270ed0a58..817e8455c 100644 --- a/90_Tower/csharp/Resources/DiskNotInPlay.txt +++ b/90_Tower/csharp/Resources/DiskNotInPlay.txt @@ -1 +1 @@ -That disk is not in play. Make another choice. \ No newline at end of file +That disk is not in play. Make another choice. diff --git a/90_Tower/csharp/Resources/DiskPrompt.txt b/90_Tower/csharp/Resources/DiskPrompt.txt index a7f127dbf..91f2583c5 100644 --- a/90_Tower/csharp/Resources/DiskPrompt.txt +++ b/90_Tower/csharp/Resources/DiskPrompt.txt @@ -1 +1 @@ -Which disk would you like to move \ No newline at end of file +Which disk would you like to move diff --git a/90_Tower/csharp/Resources/DiskQuit.txt b/90_Tower/csharp/Resources/DiskQuit.txt index 56d19d5fa..240fe7d25 100644 --- a/90_Tower/csharp/Resources/DiskQuit.txt +++ b/90_Tower/csharp/Resources/DiskQuit.txt @@ -1 +1 @@ -Stop wasting my time. Go bother someone else. \ No newline at end of file +Stop wasting my time. Go bother someone else. diff --git a/90_Tower/csharp/Resources/DiskRetry.txt b/90_Tower/csharp/Resources/DiskRetry.txt index 1efe29b44..5927a86db 100644 --- a/90_Tower/csharp/Resources/DiskRetry.txt +++ b/90_Tower/csharp/Resources/DiskRetry.txt @@ -1 +1 @@ -Illegal entry... You may only type 3, 5, 7, 9, 11, 13, or 15. \ No newline at end of file +Illegal entry... You may only type 3, 5, 7, 9, 11, 13, or 15. diff --git a/90_Tower/csharp/Resources/DiskUnavailable.txt b/90_Tower/csharp/Resources/DiskUnavailable.txt index 721ddccfe..1ce62e02d 100644 --- a/90_Tower/csharp/Resources/DiskUnavailable.txt +++ b/90_Tower/csharp/Resources/DiskUnavailable.txt @@ -1 +1 @@ -That disk is below another one. Make another choice. \ No newline at end of file +That disk is below another one. Make another choice. diff --git a/90_Tower/csharp/Resources/IllegalMove.txt b/90_Tower/csharp/Resources/IllegalMove.txt index 243c8d8fa..ccb425e72 100644 --- a/90_Tower/csharp/Resources/IllegalMove.txt +++ b/90_Tower/csharp/Resources/IllegalMove.txt @@ -1,3 +1,3 @@ You can't place a larger disk on top of a smaller one, it might crush it! -Now then, \ No newline at end of file +Now then, diff --git a/90_Tower/csharp/Resources/Instructions.txt b/90_Tower/csharp/Resources/Instructions.txt index ca75537b2..93c71b8d8 100644 --- a/90_Tower/csharp/Resources/Instructions.txt +++ b/90_Tower/csharp/Resources/Instructions.txt @@ -8,4 +8,3 @@ startup with the disks on needle 1, and attempt to move them to needle 3. Good luck! - diff --git a/90_Tower/csharp/Resources/Intro.txt b/90_Tower/csharp/Resources/Intro.txt index e5345da63..160d81761 100644 --- a/90_Tower/csharp/Resources/Intro.txt +++ b/90_Tower/csharp/Resources/Intro.txt @@ -4,4 +4,3 @@ Towers of Hanoi puzzle. You must transfer the disks from the left to the right tower, one at a time, never putting a larger dish on a smaller disk. - diff --git a/90_Tower/csharp/Resources/NeedlePrompt.txt b/90_Tower/csharp/Resources/NeedlePrompt.txt index 59dcebe7e..9d70b47b8 100644 --- a/90_Tower/csharp/Resources/NeedlePrompt.txt +++ b/90_Tower/csharp/Resources/NeedlePrompt.txt @@ -1 +1 @@ -Place disk on which needle \ No newline at end of file +Place disk on which needle diff --git a/90_Tower/csharp/Resources/NeedleQuit.txt b/90_Tower/csharp/Resources/NeedleQuit.txt index e75e3d87b..942298e44 100644 --- a/90_Tower/csharp/Resources/NeedleQuit.txt +++ b/90_Tower/csharp/Resources/NeedleQuit.txt @@ -1,2 +1,2 @@ I tried to warn you, but you wouldn't listen, -Bye bye, big shot. \ No newline at end of file +Bye bye, big shot. diff --git a/90_Tower/csharp/Resources/NeedleRetry.txt b/90_Tower/csharp/Resources/NeedleRetry.txt index 19701eec9..2c4a2286f 100644 --- a/90_Tower/csharp/Resources/NeedleRetry.txt +++ b/90_Tower/csharp/Resources/NeedleRetry.txt @@ -1,2 +1,2 @@ I'll assume you hit the wrong key this time. But watch it, -I only allow one mistake \ No newline at end of file +I only allow one mistake diff --git a/90_Tower/csharp/Resources/PlayAgainPrompt.txt b/90_Tower/csharp/Resources/PlayAgainPrompt.txt index 3972e7bde..793486ddb 100644 --- a/90_Tower/csharp/Resources/PlayAgainPrompt.txt +++ b/90_Tower/csharp/Resources/PlayAgainPrompt.txt @@ -1,2 +1,2 @@ -Try again (Yes or No) \ No newline at end of file +Try again (Yes or No) diff --git a/90_Tower/csharp/Resources/TaskFinished.txt b/90_Tower/csharp/Resources/TaskFinished.txt index e1ea1309b..454bc1f41 100644 --- a/90_Tower/csharp/Resources/TaskFinished.txt +++ b/90_Tower/csharp/Resources/TaskFinished.txt @@ -1,2 +1,2 @@ -You have performed the task in {0} moves. \ No newline at end of file +You have performed the task in {0} moves. diff --git a/90_Tower/csharp/Resources/Title.txt b/90_Tower/csharp/Resources/Title.txt index ae130577e..af05e12ed 100644 --- a/90_Tower/csharp/Resources/Title.txt +++ b/90_Tower/csharp/Resources/Title.txt @@ -1,5 +1,2 @@ Towers Creative Computing Morristown, New Jersey - - - diff --git a/90_Tower/csharp/Resources/TooManyMoves.txt b/90_Tower/csharp/Resources/TooManyMoves.txt index 680803a51..5c190ec34 100644 --- a/90_Tower/csharp/Resources/TooManyMoves.txt +++ b/90_Tower/csharp/Resources/TooManyMoves.txt @@ -1,2 +1,2 @@ Sorry, but I have orders to stop if you make more than -128 moves. \ No newline at end of file +128 moves. diff --git a/90_Tower/csharp/Resources/YesNoPrompt.txt b/90_Tower/csharp/Resources/YesNoPrompt.txt index 62612ce2e..c4539f5a2 100644 --- a/90_Tower/csharp/Resources/YesNoPrompt.txt +++ b/90_Tower/csharp/Resources/YesNoPrompt.txt @@ -1,2 +1,2 @@ -'Yes' or 'No' please \ No newline at end of file +'Yes' or 'No' please diff --git a/90_Tower/csharp/UI/Prompt.cs b/90_Tower/csharp/UI/Prompt.cs index bc83f7a67..34477bb75 100644 --- a/90_Tower/csharp/UI/Prompt.cs +++ b/90_Tower/csharp/UI/Prompt.cs @@ -38,4 +38,4 @@ public bool TryValidateResponse(float number, out int integer) return integer == number && _validValues.Contains(integer); } } -} \ No newline at end of file +} diff --git a/90_Tower/csharp/UI/TowerDisplay.cs b/90_Tower/csharp/UI/TowerDisplay.cs index 2493201f2..d6917fd94 100644 --- a/90_Tower/csharp/UI/TowerDisplay.cs +++ b/90_Tower/csharp/UI/TowerDisplay.cs @@ -34,4 +34,4 @@ void AppendTower(int size) } } } -} \ No newline at end of file +} diff --git a/90_Tower/java/Tower.java b/90_Tower/java/Tower.java index ed4c454fc..a1705c8b6 100644 --- a/90_Tower/java/Tower.java +++ b/90_Tower/java/Tower.java @@ -9,100 +9,100 @@ *

* Note: The idea was to create a version of the 1970's BASIC game in Java, without introducing * new features - no additional text, error checking, etc has been added. - * + * * Converted from BASIC to Java by Darren Cardenas. */ - + public class Tower { - + private final static int MAX_DISK_SIZE = 15; - + private final static int MAX_NUM_COLUMNS = 3; - + private final static int MAX_NUM_MOVES = 128; - - private final static int MAX_NUM_ROWS = 7; - + + private final static int MAX_NUM_ROWS = 7; + private final Scanner scan; // For user input - + // Represent all possible disk positions private int[][] positions; - + private enum Step { INITIALIZE, SELECT_TOTAL_DISKS, SELECT_DISK_MOVE, SELECT_NEEDLE, CHECK_SOLUTION - } - - + } + + public Tower() { - - scan = new Scanner(System.in); - + + scan = new Scanner(System.in); + // Row 0 and column 0 are not used - positions = new int[MAX_NUM_ROWS + 1][MAX_NUM_COLUMNS + 1]; - - } // End of constructor Tower - - + positions = new int[MAX_NUM_ROWS + 1][MAX_NUM_COLUMNS + 1]; + + } // End of constructor Tower + + public class Position { - + public int row; public int column; - + public Position(int row, int column) { this.row = row; this.column = column; - + } // End of constructor Position - + } // End of inner class Position - - + + public void play() { showIntro(); startGame(); - } // End of method play - - - private void showIntro() { - + } // End of method play + + + private void showIntro() { + System.out.println(" ".repeat(32) + "TOWERS"); System.out.println(" ".repeat(14) + "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY"); System.out.println("\n\n"); - - } // End of method showIntro + } // End of method showIntro - private void startGame() { + + private void startGame() { boolean diskMoved = false; - + int column = 0; - int disk = 0; - int needle = 0; + int disk = 0; + int needle = 0; int numDisks = 0; int numErrors = 0; int numMoves = 0; - int row = 0; - - Step nextStep = Step.INITIALIZE; - + int row = 0; + + Step nextStep = Step.INITIALIZE; + String userResponse = ""; - + Position diskPosition = new Position(0, 0); - - // Begin outer while loop + + // Begin outer while loop while (true) { - + switch (nextStep) { - - + + case INITIALIZE: - + // Initialize error count numErrors = 0; - + // Initialize positions for (row = 1; row <= MAX_NUM_ROWS; row++) { for (column = 1; column <= MAX_NUM_COLUMNS; column++) { @@ -116,46 +116,46 @@ private void startGame() { System.out.println("YOU MUST TRANSFER THE DISKS FROM THE LEFT TO THE RIGHT"); System.out.println("TOWER, ONE AT A TIME, NEVER PUTTING A LARGER DISK ON A"); System.out.println("SMALLER DISK.\n"); - + nextStep = Step.SELECT_TOTAL_DISKS; break; - - - case SELECT_TOTAL_DISKS: + + + case SELECT_TOTAL_DISKS: while (numErrors <= 2) { - + // Get user input System.out.print("HOW MANY DISKS DO YOU WANT TO MOVE (" + MAX_NUM_ROWS + " IS MAX)? "); numDisks = scan.nextInt(); System.out.println(""); - + numMoves = 0; - + // Ensure the number of disks is valid if ((numDisks < 1) || (numDisks > MAX_NUM_ROWS)) { - + numErrors++; - + // Handle user input errors if (numErrors < 3) { - System.out.println("SORRY, BUT I CAN'T DO THAT JOB FOR YOU."); - } - + System.out.println("SORRY, BUT I CAN'T DO THAT JOB FOR YOU."); + } + } else { break; // Leave the while loop } - } - + } + // Too many user input errors - if (numErrors > 2) { + if (numErrors > 2) { System.out.println("ALL RIGHT, WISE GUY, IF YOU CAN'T PLAY THE GAME RIGHT, I'LL"); System.out.println("JUST TAKE MY PUZZLE AND GO HOME. SO LONG."); - return; + return; } - // Display detailed instructions + // Display detailed instructions System.out.println("IN THIS PROGRAM, WE SHALL REFER TO DISKS BY NUMERICAL CODE."); System.out.println("3 WILL REPRESENT THE SMALLEST DISK, 5 THE NEXT SIZE,"); System.out.println("7 THE NEXT, AND SO ON, UP TO 15. IF YOU DO THE PUZZLE WITH"); @@ -164,28 +164,28 @@ private void startGame() { System.out.println("ARE NUMBERED FROM LEFT TO RIGHT, 1 TO 3. WE WILL"); System.out.println("START WITH THE DISKS ON NEEDLE 1, AND ATTEMPT TO MOVE THEM"); System.out.println("TO NEEDLE 3.\n"); - System.out.println("GOOD LUCK!\n"); - + System.out.println("GOOD LUCK!\n"); + disk = MAX_DISK_SIZE; - + // Set disk starting positions - for (row = MAX_NUM_ROWS; row > (MAX_NUM_ROWS - numDisks); row--) { - positions[row][1] = disk; - disk = disk - 2; - } - + for (row = MAX_NUM_ROWS; row > (MAX_NUM_ROWS - numDisks); row--) { + positions[row][1] = disk; + disk = disk - 2; + } + printPositions(); - + nextStep = Step.SELECT_DISK_MOVE; break; - + case SELECT_DISK_MOVE: - + System.out.print("WHICH DISK WOULD YOU LIKE TO MOVE? "); - + numErrors = 0; - + while (numErrors < 2) { disk = scan.nextInt(); @@ -194,154 +194,154 @@ private void startGame() { // Check if disk exists diskPosition = getDiskPosition(disk); - + // Disk found if ((diskPosition.row > 0) && (diskPosition.column > 0)) { // Disk can be moved if (isDiskMovable(disk, diskPosition.row, diskPosition.column) == true) { - + break; - + } // Disk cannot be moved else { - - System.out.println("THAT DISK IS BELOW ANOTHER ONE. MAKE ANOTHER CHOICE."); - System.out.print("WHICH DISK WOULD YOU LIKE TO MOVE? "); - - } + + System.out.println("THAT DISK IS BELOW ANOTHER ONE. MAKE ANOTHER CHOICE."); + System.out.print("WHICH DISK WOULD YOU LIKE TO MOVE? "); + + } } // Mimic legacy handling of valid disk number but disk not found else { - + System.out.println("THAT DISK IS BELOW ANOTHER ONE. MAKE ANOTHER CHOICE."); System.out.print("WHICH DISK WOULD YOU LIKE TO MOVE? "); numErrors = 0; continue; - - } - + + } + } // Invalid disk number else { - - System.out.println("ILLEGAL ENTRY... YOU MAY ONLY TYPE 3,5,7,9,11,13, OR 15."); + + System.out.println("ILLEGAL ENTRY... YOU MAY ONLY TYPE 3,5,7,9,11,13, OR 15."); numErrors++; - - if (numErrors > 1) { + + if (numErrors > 1) { break; - } - + } + System.out.print("? "); - + } } - if (numErrors > 1) { - + if (numErrors > 1) { + System.out.println("STOP WASTING MY TIME. GO BOTHER SOMEONE ELSE."); return; } - - nextStep = Step.SELECT_NEEDLE; + + nextStep = Step.SELECT_NEEDLE; break; - + case SELECT_NEEDLE: - + numErrors = 0; while (true) { - + System.out.print("PLACE DISK ON WHICH NEEDLE? "); needle = scan.nextInt(); - + // Handle valid needle numbers - if ((needle - 1) * (needle - 2) * (needle - 3) == 0) { - - // Ensure needle is safe for disk move + if ((needle - 1) * (needle - 2) * (needle - 3) == 0) { + + // Ensure needle is safe for disk move if (isNeedleSafe(needle, disk, row) == false) { - + System.out.println("YOU CAN'T PLACE A LARGER DISK ON TOP OF A SMALLER ONE,"); System.out.println("IT MIGHT CRUSH IT!"); - System.out.print("NOW THEN, "); + System.out.print("NOW THEN, "); nextStep = Step.SELECT_DISK_MOVE; - break; + break; } - + diskPosition = getDiskPosition(disk); - + // Attempt to move the disk on a non-empty needle - diskMoved = false; + diskMoved = false; for (row = 1; row <= MAX_NUM_ROWS; row++) { if (positions[row][needle] != 0) { row--; - + positions[row][needle] = positions[diskPosition.row][diskPosition.column]; positions[diskPosition.row][diskPosition.column] = 0; - + diskMoved = true; - break; - } + break; + } } - + // Needle was empty, so move disk to the bottom if (diskMoved == false) { positions[MAX_NUM_ROWS][needle] = positions[diskPosition.row][diskPosition.column]; - positions[diskPosition.row][diskPosition.column] = 0; - } - + positions[diskPosition.row][diskPosition.column] = 0; + } + nextStep = Step.CHECK_SOLUTION; break; - + } // Handle invalid needle numbers else { - + numErrors++; - - if (numErrors > 1) { + + if (numErrors > 1) { System.out.println("I TRIED TO WARN YOU, BUT YOU WOULDN'T LISTEN."); System.out.println("BYE BYE, BIG SHOT."); return; } - else { + else { System.out.println("I'LL ASSUME YOU HIT THE WRONG KEY THIS TIME. BUT WATCH IT,"); - System.out.println("I ONLY ALLOW ONE MISTAKE."); - } + System.out.println("I ONLY ALLOW ONE MISTAKE."); + } } - - } + + } break; - + case CHECK_SOLUTION: - - printPositions(); - + + printPositions(); + numMoves++; - + // Puzzle is solved if (isPuzzleSolved() == true) { - + // Check for optimal solution if (numMoves == (Math.pow(2, numDisks) - 1)) { System.out.println(""); - System.out.println("CONGRATULATIONS!!\n"); + System.out.println("CONGRATULATIONS!!\n"); } - + System.out.println("YOU HAVE PERFORMED THE TASK IN " + numMoves + " MOVES.\n"); - System.out.print("TRY AGAIN (YES OR NO)? "); + System.out.print("TRY AGAIN (YES OR NO)? "); // Prompt for retries while (true) { userResponse = scan.next(); - - if (userResponse.toUpperCase().equals("YES")) { - nextStep = Step.INITIALIZE; + + if (userResponse.toUpperCase().equals("YES")) { + nextStep = Step.INITIALIZE; break; } else if (userResponse.toUpperCase().equals("NO")) { @@ -352,86 +352,86 @@ else if (userResponse.toUpperCase().equals("NO")) { else { System.out.print("'YES' OR 'NO' PLEASE? "); } - } + } } // Puzzle is not solved else { - + // Exceeded maximum number of moves if (numMoves > MAX_NUM_MOVES) { System.out.println("SORRY, BUT I HAVE ORDERS TO STOP IF YOU MAKE MORE THAN"); - System.out.println("128 MOVES."); - return; - } + System.out.println("128 MOVES."); + return; + } nextStep = Step.SELECT_DISK_MOVE; - break; - } - + break; + } + break; - + default: System.out.println("INVALID STEP"); - break; + break; + + } + + } // End outer while loop - } - - } // End outer while loop - } // End of method startGame - + private boolean isPuzzleSolved() { - + int column = 0; int row = 0; - // Puzzle is solved if first 2 needles are empty - for (row = 1; row <= MAX_NUM_ROWS; row++) { - for (column = 1; column <= 2; column++) { + // Puzzle is solved if first 2 needles are empty + for (row = 1; row <= MAX_NUM_ROWS; row++) { + for (column = 1; column <= 2; column++) { if (positions[row][column] != 0) { - return false; - } - } - } + return false; + } + } + } return true; - + } // End of method isPuzzleSolved - + private Position getDiskPosition(int disk) { - + int column = 0; int row = 0; - + Position pos = new Position(0, 0); - // Begin loop through all rows + // Begin loop through all rows for (row = 1; row <= MAX_NUM_ROWS; row++) { - + // Begin loop through all columns for (column = 1; column <= MAX_NUM_COLUMNS; column++) { - + // Found the disk if (positions[row][column] == disk) { - + pos.row = row; pos.column = column; return pos; } - + } // End loop through all columns - } // End loop through all rows - + } // End loop through all rows + return pos; - - } // End of method getDiskPosition - - private boolean isDiskMovable(int disk, int row, int column) { + } // End of method getDiskPosition + + + private boolean isDiskMovable(int disk, int row, int column) { int ii = 0; // Loop iterator @@ -440,88 +440,88 @@ private boolean isDiskMovable(int disk, int row, int column) { // Disk can be moved if (positions[ii][column] == 0) { - continue; + continue; } - + // Disk cannot be moved if (positions[ii][column] < disk) { - return false; + return false; } } // End loop through all rows above disk - + return true; - } // End of method isDiskMovable + } // End of method isDiskMovable private boolean isNeedleSafe(int needle, int disk, int row) { - + for (row = 1; row <= MAX_NUM_ROWS; row++) { // Needle is not empty if (positions[row][needle] != 0) { - + // Disk crush condition - if (disk >= positions[row][needle]) { + if (disk >= positions[row][needle]) { return false; } } } - + return true; - + } // End of method isNeedleSafe - - + + private void printPositions() { - + int column = 1; int ii = 0; // Loop iterator - int numSpaces = 0; - int row = 1; - + int numSpaces = 0; + int row = 1; + // Begin loop through all rows for (row = 1; row <= MAX_NUM_ROWS; row++) { - - numSpaces = 9; - + + numSpaces = 9; + // Begin loop through all columns for (column = 1; column <= MAX_NUM_COLUMNS; column++) { // No disk at the current position if (positions[row][column] == 0) { - + System.out.print(" ".repeat(numSpaces) + "*"); - numSpaces = 20; - } - + numSpaces = 20; + } + // Draw a disk at the current position else { - + System.out.print(" ".repeat(numSpaces - ((int) (positions[row][column] / 2)))); for (ii = 1; ii <= positions[row][column]; ii++) { - System.out.print("*"); - } - + System.out.print("*"); + } + numSpaces = 20 - ((int) (positions[row][column] / 2)); - } - + } + } // End loop through all columns - - System.out.println(""); - - } // End loop through all rows - - } // End of method printPositions - + + System.out.println(""); + + } // End loop through all rows + + } // End of method printPositions + public static void main(String[] args) { - + Tower tower = new Tower(); tower.play(); - + } // End of method main -} // End of class Tower \ No newline at end of file +} // End of class Tower diff --git a/90_Tower/javascript/tower.js b/90_Tower/javascript/tower.js index 06e8745c0..18f1f8fd1 100644 --- a/90_Tower/javascript/tower.js +++ b/90_Tower/javascript/tower.js @@ -12,10 +12,10 @@ function input() { var input_element; var input_str; - + return new Promise(function (resolve) { input_element = document.createElement("INPUT"); - + print("? "); input_element.setAttribute("type", "text"); input_element.setAttribute("length", "50"); @@ -48,7 +48,7 @@ var ta = []; function show_towers() { var z; - + for (var k = 1; k <= 7; k++) { z = 10; str = ""; diff --git a/90_Tower/python/tower.py b/90_Tower/python/tower.py index 5e4a25b79..9fddce602 100644 --- a/90_Tower/python/tower.py +++ b/90_Tower/python/tower.py @@ -1,5 +1,6 @@ import sys + class Disk: def __init__(self, size): self.__size = size @@ -10,6 +11,7 @@ def size(self): def print(self): print("[ %s ]" % self.size()) + class Tower: def __init__(self): self.__disks = [] @@ -27,7 +29,9 @@ def add(self, disk): if not self.empty(): t = self.top() if disk.size() > t.size(): - raise Exception("YOU CAN'T PLACE A LARGER DISK ON TOP OF A SMALLER ONE, IT MIGHT CRUSH IT!") + raise Exception( + "YOU CAN'T PLACE A LARGER DISK ON TOP OF A SMALLER ONE, IT MIGHT CRUSH IT!" + ) self.__disks.append(disk) def pop(self): @@ -40,8 +44,8 @@ def print(self): print(r) - -print(""" +print( + """ IN THIS PROGRAM, WE SHALL REFER TO DISKS BY NUMERICAL CODE. 3 WILL REPRESENT THE SMALLEST DISK, 5 THE NEXT SIZE, 7 THE NEXT, AND SO ON, UP TO 15. IF YOU DO THE PUZZLE WITH @@ -53,9 +57,8 @@ def print(self): GOOD LUCK! -""") - - +""" +) class Game: @@ -63,7 +66,7 @@ def __init__(self): # use fewer sizes to make debugging easier # self.__sizes = [3, 5, 7] # ,9,11,13,15] self.__sizes = [3, 5, 7, 9, 11, 13, 15] - + self.__sizes.sort() self.__towers = [] @@ -113,7 +116,9 @@ def which_tower(self): needle = int(input("PLACE DISK ON WHICH NEEDLE\n")) tower = self.__towers[needle - 1] except: - print("I'LL ASSUME YOU HIT THE WRONG KEY THIS TIME. BUT WATCH IT,\nI ONLY ALLOW ONE MISTAKE.\n") + print( + "I'LL ASSUME YOU HIT THE WRONG KEY THIS TIME. BUT WATCH IT,\nI ONLY ALLOW ONE MISTAKE.\n" + ) return None else: return tower @@ -133,12 +138,13 @@ def take_turn(self): disk = from_tower.pop() try: - to_tower.add( disk ) + to_tower.add(disk) self.__moves += 1 except Exception as err: print(err) from_tower.add(disk) + game = Game() while True: game.print() @@ -146,7 +152,10 @@ def take_turn(self): game.take_turn() if game.winner(): - print("CONGRATULATIONS!!\nYOU HAVE PERFORMED THE TASK IN %s MOVES.\n" % game.moves()) + print( + "CONGRATULATIONS!!\nYOU HAVE PERFORMED THE TASK IN %s MOVES.\n" + % game.moves() + ) while True: yesno = input("TRY AGAIN (YES OR NO)\n") if yesno.upper() == "YES": diff --git a/90_Tower/python/tower_test.py b/90_Tower/python/tower_test.py index a7023a0fa..b3e0e2f0e 100644 --- a/90_Tower/python/tower_test.py +++ b/90_Tower/python/tower_test.py @@ -1,6 +1,8 @@ import unittest + import tower + class MyTestCase(unittest.TestCase): def test_something(self): t = tower.Tower() @@ -43,7 +45,8 @@ def test_format(self): t.add(d3) f = t.vertical_format(6, 3) - self.assertEqual(f, [' ', '[ 3 ] ', '[ 5 ] ']) + self.assertEqual(f, [" ", "[ 3 ] ", "[ 5 ] "]) + -if __name__ == '__main__': +if __name__ == "__main__": unittest.main() diff --git a/91_Train/javascript/train.js b/91_Train/javascript/train.js index e49d00bc0..b05e67912 100644 --- a/91_Train/javascript/train.js +++ b/91_Train/javascript/train.js @@ -12,10 +12,10 @@ function input() { var input_element; var input_str; - + return new Promise(function (resolve) { input_element = document.createElement("INPUT"); - + print("? "); input_element.setAttribute("type", "text"); input_element.setAttribute("length", "50"); diff --git a/91_Train/perl/train.pl b/91_Train/perl/train.pl index d628b12c4..f2a4c1d5a 100755 --- a/91_Train/perl/train.pl +++ b/91_Train/perl/train.pl @@ -21,7 +21,7 @@ my $V= $D*$T/($C-$T); my $E= int(abs(($V-$A)*100/$A)+.5); - if ($E>5) { + if ($E>5) { print "SORRY. YOU WERE OFF BY $E PERCENT.\n"; } else { print "GOOD! ANSWER WITHIN $E PERCENT.\n"; diff --git a/91_Train/python/train.py b/91_Train/python/train.py index 0fd68b3c0..bf4329d24 100644 --- a/91_Train/python/train.py +++ b/91_Train/python/train.py @@ -19,8 +19,8 @@ def play_game(): time_answer = float(input("How long does the trip take by car ")) except ValueError: print("Please enter a number.") - car_time = time_difference*train_speed/(car_speed-train_speed) - error_percent = int(abs((car_time-time_answer)*100/time_answer)+.5) + car_time = time_difference * train_speed / (car_speed - train_speed) + error_percent = int(abs((car_time - time_answer) * 100 / time_answer) + 0.5) if error_percent > 5: print("Sorry. You were off by", error_percent, "percent.") print("Correct answer is", round(car_time, 6), "hours") @@ -36,8 +36,7 @@ def main(): keep_playing = True while keep_playing: play_game() - keep_playing = input( - "\nAnother problem (yes or no) ").lower().startswith("y") + keep_playing = input("\nAnother problem (yes or no) ").lower().startswith("y") if __name__ == "__main__": diff --git a/91_Train/ruby/train.rb b/91_Train/ruby/train.rb index c6850035e..6499cb24a 100644 --- a/91_Train/ruby/train.rb +++ b/91_Train/ruby/train.rb @@ -55,4 +55,4 @@ def main trap "SIGINT" do puts; exit 130 end -main \ No newline at end of file +main diff --git a/92_Trap/csharp/Program.cs b/92_Trap/csharp/Program.cs index 6cd74d10d..1769eb75c 100644 --- a/92_Trap/csharp/Program.cs +++ b/92_Trap/csharp/Program.cs @@ -79,7 +79,7 @@ static void PrintInstructions() } } static void Print(string stringToPrint) - { + { Console.WriteLine(stringToPrint); } static void Print() diff --git a/92_Trap/java/src/Trap.java b/92_Trap/java/src/Trap.java index d3dd58245..3643ed7ef 100644 --- a/92_Trap/java/src/Trap.java +++ b/92_Trap/java/src/Trap.java @@ -198,4 +198,4 @@ private int randomNumber() { return (int) (Math.random() * (HIGH_NUMBER_RANGE) + 1); } -} \ No newline at end of file +} diff --git a/92_Trap/javascript/trap.js b/92_Trap/javascript/trap.js index c2a5a2f30..047454633 100644 --- a/92_Trap/javascript/trap.js +++ b/92_Trap/javascript/trap.js @@ -12,10 +12,10 @@ function input() { var input_element; var input_str; - + return new Promise(function (resolve) { input_element = document.createElement("INPUT"); - + print("? "); input_element.setAttribute("type", "text"); input_element.setAttribute("length", "50"); diff --git a/92_Trap/perl/trap.pl b/92_Trap/perl/trap.pl index 803490565..c0f69c8c0 100755 --- a/92_Trap/perl/trap.pl +++ b/92_Trap/perl/trap.pl @@ -56,7 +56,5 @@ print "TRY AGAIN.\n"; print "\n"; } - -exit; - +exit; diff --git a/92_Trap/python/trap.py b/92_Trap/python/trap.py index 772bd3c54..f1f294f7b 100644 --- a/92_Trap/python/trap.py +++ b/92_Trap/python/trap.py @@ -20,8 +20,10 @@ def play_game(): user_guess = [-1, -1] while user_guess == [-1, -1]: try: - user_input = [int(item) for item in input( - "\nGuess # " + str(turn) + " ? ").split(",")] + user_input = [ + int(item) + for item in input("\nGuess # " + str(turn) + " ? ").split(",") + ] if len(user_input) == 2: if sum(1 < x < number_max for x in user_input) == 2: user_guess = user_input @@ -65,8 +67,7 @@ def main(): keep_playing = True while keep_playing: play_game() - keep_playing = input( - "\nTry again. ").lower().startswith("y") + keep_playing = input("\nTry again. ").lower().startswith("y") if __name__ == "__main__": diff --git a/92_Trap/trap.bas b/92_Trap/trap.bas index 2d5624b59..7827f8ca0 100644 --- a/92_Trap/trap.bas +++ b/92_Trap/trap.bas @@ -20,7 +20,7 @@ 170 PRINT "YOU GET";G;"GUESSES TO GET MY NUMBER." 180 X=INT(N*RND(1))+1 190 FOR Q=1 TO G -200 PRINT +200 PRINT 210 PRINT "GUESS #";Q; 220 INPUT A,B 230 IF A=B AND X=A THEN 400 @@ -40,9 +40,9 @@ 360 R=A 370 A=B 380 B=R -390 RETURN +390 RETURN 400 PRINT "YOU GOT IT!!!" -410 PRINT +410 PRINT 420 PRINT "TRY AGAIN." 430 PRINT 440 GOTO 180 diff --git a/93_23_Matches/csharp/README.md b/93_23_Matches/csharp/README.md index 0f4d812af..fd759c067 100644 --- a/93_23_Matches/csharp/README.md +++ b/93_23_Matches/csharp/README.md @@ -2,4 +2,4 @@ Original source downloaded [from Vintage Basic](http://www.vintage-basic.net/gam Conversion to [Microsoft C#](https://docs.microsoft.com/en-us/dotnet/csharp/) -The program is available in two versions, a "goto" version that mimics the original program and an "object-oriented" version. \ No newline at end of file +The program is available in two versions, a "goto" version that mimics the original program and an "object-oriented" version. diff --git a/93_23_Matches/java/Messages.java b/93_23_Matches/java/Messages.java index c0e52b7c3..739486913 100644 --- a/93_23_Matches/java/Messages.java +++ b/93_23_Matches/java/Messages.java @@ -9,15 +9,15 @@ private Messages() { public static final String INTRO = """ 23 MATCHES CREATIVE COMPUTING MORRISTOWN, NEW JERSEY - - - + + + THIS IS A GAME CALLED '23 MATCHES'. - + WHEN IT IS YOUR TURN, YOU MAY TAKE ONE, TWO, OR THREE MATCHES. THE OBJECT OF THE GAME IS NOT TO HAVE TO TAKE THE LAST MATCH. - + LET'S FLIP A COIN TO SEE WHO GOES FIRST. IF IT COMES UP HEADS, I WILL WIN THE TOSS. """; @@ -25,7 +25,7 @@ private Messages() { public static final String HEADS = """ HEADS! I WIN! HA! HA! PREPARE TO LOSE, MEATBALL-NOSE!! - + I TAKE 2 MATCHES """; @@ -35,7 +35,7 @@ private Messages() { public static final String MATCHES_LEFT = """ THE NUMBER OF MATCHES IS NOW %d - + YOUR TURN -- YOU MAY TAKE 1, 2 OR 3 MATCHES. """; @@ -64,7 +64,7 @@ private Messages() { public static final String LOSE = """ YOU POOR BOOB! YOU TOOK THE LAST MATCH! I GOTCHA!! HA ! HA ! I BEAT YOU !!! - + GOOD BYE LOSER! """; } diff --git a/93_23_Matches/javascript/23matches.js b/93_23_Matches/javascript/23matches.js index 2233cda6e..faf2b0424 100644 --- a/93_23_Matches/javascript/23matches.js +++ b/93_23_Matches/javascript/23matches.js @@ -12,10 +12,10 @@ function input() { var input_element; var input_str; - + return new Promise(function (resolve) { input_element = document.createElement("INPUT"); - + print("? "); input_element.setAttribute("type", "text"); input_element.setAttribute("length", "50"); @@ -116,7 +116,7 @@ async function main() } q = 1; } - + } main(); diff --git a/93_23_Matches/python/23matches.py b/93_23_Matches/python/23matches.py index 189f5aa66..226b0f3ac 100755 --- a/93_23_Matches/python/23matches.py +++ b/93_23_Matches/python/23matches.py @@ -73,8 +73,7 @@ def main(): keep_playing = True while keep_playing: play_game() - keep_playing = input( - "\nPlay again? (yes or no) ").lower().startswith("y") + keep_playing = input("\nPlay again? (yes or no) ").lower().startswith("y") if __name__ == "__main__": diff --git a/94_War/java/War.java b/94_War/java/War.java index b09a46160..ce5f3560c 100644 --- a/94_War/java/War.java +++ b/94_War/java/War.java @@ -5,7 +5,7 @@ /** * Converted FROM BASIC to Java by Nahid Mondol. - * + * * Based on Trevor Hobsons approach. */ public class War { @@ -77,7 +77,7 @@ private static void playGame() { invalidInput = true; while (invalidInput) { if (endedEarly()) { - // Player ended game early. + // Player ended game early. // Break out of game loop and show end game output. gameEndedEarly = true; break outerloop; @@ -90,7 +90,7 @@ private static void playGame() { /** * Outputs the winner of the current round. - * + * * @param playerCard Players card. * @param computerCard Computers card. */ @@ -153,7 +153,7 @@ private static boolean endedEarly() { /** * Show output based on if the game was ended early or not. - * + * * @param endedEarly true if the game was ended early, false otherwise. */ private static void endGameOutput(boolean endedEarly) { @@ -195,4 +195,4 @@ private static int computerWonRound() { private static int getComputerScore() { return computerTotalScore; } -} \ No newline at end of file +} diff --git a/94_War/javascript/war.js b/94_War/javascript/war.js index ca11d063c..727742602 100644 --- a/94_War/javascript/war.js +++ b/94_War/javascript/war.js @@ -124,15 +124,15 @@ const cards = [ async function main() { printTitle(); await askAboutInstructions(); - + let computerScore = 0; let playerScore = 0; - + // Generate a random deck const gameSize = cards.length; // Number of cards to shuffle into the game deck. Can be <= cards.length. const deck = createGameDeck(cards, gameSize); let shouldContinuePlaying = true; - + while (deck.length > 0 && shouldContinuePlaying) { const playerCard = deck.shift(); // Take a card const computerCard = deck.shift(); // Take a card diff --git a/94_War/python/war.py b/94_War/python/war.py index f512a6fa0..682771f81 100755 --- a/94_War/python/war.py +++ b/94_War/python/war.py @@ -7,17 +7,65 @@ def card_value(input): - return ["2", "3", "4", "5", "6", "7", "8", - "9", "10", "J", "Q", "K", "A"].index(input.split("-")[1]) + return ["2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"].index( + input.split("-")[1] + ) -cards = ["S-2", "H-2", "C-2", "D-2", "S-3", "H-3", "C-3", "D-3", - "S-4", "H-4", "C-4", "D-4", "S-5", "H-5", "C-5", "D-5", - "S-6", "H-6", "C-6", "D-6", "S-7", "H-7", "C-7", "D-7", - "S-8", "H-8", "C-8", "D-8", "S-9", "H-9", "C-9", "D-9", - "S-10", "H-10", "C-10", "D-10", "S-J", "H-J", "C-J", "D-J", - "S-Q", "H-Q", "C-Q", "D-Q", "S-K", "H-K", "C-K", "D-K", - "S-A", "H-A", "C-A", "D-A"] +cards = [ + "S-2", + "H-2", + "C-2", + "D-2", + "S-3", + "H-3", + "C-3", + "D-3", + "S-4", + "H-4", + "C-4", + "D-4", + "S-5", + "H-5", + "C-5", + "D-5", + "S-6", + "H-6", + "C-6", + "D-6", + "S-7", + "H-7", + "C-7", + "D-7", + "S-8", + "H-8", + "C-8", + "D-8", + "S-9", + "H-9", + "C-9", + "D-9", + "S-10", + "H-10", + "C-10", + "D-10", + "S-J", + "H-J", + "C-J", + "D-J", + "S-Q", + "H-Q", + "C-Q", + "D-Q", + "S-K", + "H-K", + "C-K", + "D-K", + "S-A", + "H-A", + "C-A", + "D-A", +] def play_game(): @@ -31,18 +79,22 @@ def play_game(): print() card_you = cards[round] card_computer = cards[round * 2] - print("You:", card_you, " " * (8 - len(card_you)) + - "Computer:", card_computer) + print("You:", card_you, " " * (8 - len(card_you)) + "Computer:", card_computer) value_you = card_value(card_you) value_computer = card_value(card_computer) if value_you > value_computer: score_you += 1 - print("You win. You have", score_you, - "and the computer has", score_computer) + print( + "You win. You have", score_you, "and the computer has", score_computer + ) elif value_computer > value_you: score_computer += 1 - print("The computer wins!!! You have", score_you, - "and the computer has", score_computer) + print( + "The computer wins!!! You have", + score_you, + "and the computer has", + score_computer, + ) else: print("Tie. No score change.") cards_left -= 2 @@ -50,8 +102,12 @@ def play_game(): if input("Do you want to continue ").lower().startswith("n"): break if cards_left == 0: - print("\nWe have run out of cards. Final score: You:", - score_you, "the computer:", score_computer) + print( + "\nWe have run out of cards. Final score: You:", + score_you, + "the computer:", + score_computer, + ) print("\nThanks for playing. It was fun.") @@ -68,8 +124,7 @@ def main(): keep_playing = True while keep_playing: play_game() - keep_playing = input( - "\nPlay again? (yes or no) ").lower().startswith("y") + keep_playing = input("\nPlay again? (yes or no) ").lower().startswith("y") if __name__ == "__main__": diff --git a/94_War/rust/README.md b/94_War/rust/README.md index f84e546c2..7e85f9a15 100644 --- a/94_War/rust/README.md +++ b/94_War/rust/README.md @@ -1,3 +1,3 @@ Original source downloaded [from Vintage Basic](http://www.vintage-basic.net/games.html) -Conversion to [Rust](https://www.rust-lang.org/) by Anthony Rubick [AnthonyMichaelTDM](https://github.com/AnthonyMichaelTDM) \ No newline at end of file +Conversion to [Rust](https://www.rust-lang.org/) by Anthony Rubick [AnthonyMichaelTDM](https://github.com/AnthonyMichaelTDM) diff --git a/94_War/rust/src/main.rs b/94_War/rust/src/main.rs index 5243fa710..fb8a55fc1 100644 --- a/94_War/rust/src/main.rs +++ b/94_War/rust/src/main.rs @@ -105,7 +105,7 @@ impl GAME { fn main() { //print welcome message welcome(); - + //game loop let mut game = GAME::new(); loop { @@ -155,4 +155,4 @@ fn get_yes_no_from_user_input(prompt: &str) -> bool { } //default case return false; -} \ No newline at end of file +} diff --git a/95_Weekday/csharp/Program.cs b/95_Weekday/csharp/Program.cs index d2e531bcb..e19be76d6 100644 --- a/95_Weekday/csharp/Program.cs +++ b/95_Weekday/csharp/Program.cs @@ -187,7 +187,7 @@ public void PlayTheGame() TodaysDate = PromptForADate("Enter today's date in the form: 3,24,1978 ? "); BirthDate = PromptForADate("Enter day of birth (or other day of interest)? "); - DisplayOutput(TodaysDate, BirthDate); + DisplayOutput(TodaysDate, BirthDate); } } @@ -200,4 +200,4 @@ static void Main(string[] args) } } -} \ No newline at end of file +} diff --git a/95_Weekday/python/weekday.py b/95_Weekday/python/weekday.py index 29750279e..1d6407dc4 100644 --- a/95_Weekday/python/weekday.py +++ b/95_Weekday/python/weekday.py @@ -29,7 +29,7 @@ def get_date_from_user(prompt): print(prompt) date_str = input() try: - month_num, day_num, year_num = [int(x) for x in date_str.split(",")] + month_num, day_num, year_num = (int(x) for x in date_str.split(",")) except Exception as e: print("I COULDN'T UNDERSTAND THAT. TRY AGAIN.") return month_num, day_num, year_num diff --git a/95_Weekday/weekday.bas b/95_Weekday/weekday.bas index 77efcaea9..33f982e88 100644 --- a/95_Weekday/weekday.bas +++ b/95_Weekday/weekday.bas @@ -104,7 +104,7 @@ 1080 GOSUB 1370 1085 GOTO 1530 1090 PRINT "YOU HAVE RELAXED ",K5,K6,K7 -1100 PRINT +1100 PRINT 1110 PRINT TAB(16);"*** YOU MAY RETIRE IN";E;" ***" 1120 PRINT 1140 PRINT diff --git a/96_Word/csharp/Program.cs b/96_Word/csharp/Program.cs index 464787c50..76fb3582d 100644 --- a/96_Word/csharp/Program.cs +++ b/96_Word/csharp/Program.cs @@ -58,7 +58,7 @@ private string get_guess() /// The integer value showing the number of character matches between guess and target private int check_guess(string guess, string target, StringBuilder progress) { - // Go through each letter of the guess and see which + // Go through each letter of the guess and see which // letters match up to the target word. // For each position that matches, update the progress // to reflect the guess diff --git a/96_Word/java/Word.java b/96_Word/java/Word.java index 7cae9124b..d8bde3d9e 100644 --- a/96_Word/java/Word.java +++ b/96_Word/java/Word.java @@ -9,215 +9,215 @@ *

* Note: The idea was to create a version of the 1970's BASIC game in Java, without introducing * new features - no additional text, error checking, etc has been added. - * + * * Converted from BASIC to Java by Darren Cardenas. */ - + public class Word { - - private final static String[] WORDS = { + + private final static String[] WORDS = { "DINKY", "SMOKE", "WATER", "GRASS", "TRAIN", "MIGHT", "FIRST", "CANDY", "CHAMP", "WOULD", "CLUMP", "DOPEY" }; - + private final Scanner scan; // For user input - + private enum Step { INITIALIZE, MAKE_GUESS, USER_WINS - } - + } + public Word() { - - scan = new Scanner(System.in); - } // End of constructor Word - + scan = new Scanner(System.in); + + } // End of constructor Word + public void play() { showIntro(); startGame(); - } // End of method play - - private void showIntro() { - + } // End of method play + + private void showIntro() { + System.out.println(" ".repeat(32) + "WORD"); System.out.println(" ".repeat(14) + "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY"); System.out.println("\n\n"); - + System.out.println("I AM THINKING OF A WORD -- YOU GUESS IT. I WILL GIVE YOU"); System.out.println("CLUES TO HELP YOU GET IT. GOOD LUCK!!"); System.out.println("\n"); - - } // End of method showIntro - private void startGame() { - + } // End of method showIntro + + private void startGame() { + char[] commonLetters = new char[8]; char[] exactLetters = new char[8]; - + int commonIndex = 0; int ii = 0; // Loop iterator - int jj = 0; // Loop iterator + int jj = 0; // Loop iterator int numGuesses = 0; int numMatches = 0; int wordIndex = 0; - - Step nextStep = Step.INITIALIZE; - String commonString = ""; + Step nextStep = Step.INITIALIZE; + + String commonString = ""; String exactString = ""; String guessWord = ""; - String secretWord = ""; + String secretWord = ""; String userResponse = ""; - // Begin outer while loop + // Begin outer while loop while (true) { - + switch (nextStep) { case INITIALIZE: - + System.out.println("\n"); System.out.println("YOU ARE STARTING A NEW GAME..."); // Select a secret word from the list wordIndex = (int) (Math.random() * WORDS.length); - secretWord = WORDS[wordIndex]; - + secretWord = WORDS[wordIndex]; + numGuesses = 0; - + Arrays.fill(exactLetters, 1, 6, '-'); Arrays.fill(commonLetters, 1, 6, '\0'); nextStep = Step.MAKE_GUESS; - break; - + break; + case MAKE_GUESS: - + System.out.print("GUESS A FIVE LETTER WORD? "); guessWord = scan.nextLine().toUpperCase(); numGuesses++; - + // Win condition - if (guessWord.equals(secretWord)) { + if (guessWord.equals(secretWord)) { nextStep = Step.USER_WINS; continue; } - - Arrays.fill(commonLetters, 1, 8, '\0'); + + Arrays.fill(commonLetters, 1, 8, '\0'); // Surrender condition - if (guessWord.equals("?")) { + if (guessWord.equals("?")) { System.out.println("THE SECRET WORD IS " + secretWord); System.out.println(""); nextStep = Step.INITIALIZE; // Play again - continue; + continue; } - + // Check for valid input - if (guessWord.length() != 5) { - System.out.println("YOU MUST GUESS A 5 LETTER WORD. START AGAIN."); + if (guessWord.length() != 5) { + System.out.println("YOU MUST GUESS A 5 LETTER WORD. START AGAIN."); numGuesses--; nextStep = Step.MAKE_GUESS; // Guess again - continue; + continue; } - + numMatches = 0; - commonIndex = 1; - - for (ii = 1; ii <= 5; ii++) { - - for (jj = 1; jj <= 5; jj++) { - - if (secretWord.charAt(ii - 1) != guessWord.charAt(jj - 1)) { - continue; - } + commonIndex = 1; + + for (ii = 1; ii <= 5; ii++) { + + for (jj = 1; jj <= 5; jj++) { + + if (secretWord.charAt(ii - 1) != guessWord.charAt(jj - 1)) { + continue; + } // Avoid out of bounds errors if (commonIndex <= 5) { commonLetters[commonIndex] = guessWord.charAt(jj - 1); commonIndex++; - } + } - if (ii == jj) { - exactLetters[jj] = guessWord.charAt(jj - 1); + if (ii == jj) { + exactLetters[jj] = guessWord.charAt(jj - 1); } - + // Avoid out of bounds errors if (numMatches < 5) { numMatches++; } - } + } } - + exactString = ""; commonString = ""; - + // Build the exact letters string - for (ii = 1; ii <= 5; ii++) { - exactString += exactLetters[ii]; + for (ii = 1; ii <= 5; ii++) { + exactString += exactLetters[ii]; } - + // Build the common letters string - for (ii = 1; ii <= numMatches; ii++) { - commonString += commonLetters[ii]; + for (ii = 1; ii <= numMatches; ii++) { + commonString += commonLetters[ii]; } - - System.out.println("THERE WERE " + numMatches + " MATCHES AND THE COMMON LETTERS WERE..." + + System.out.println("THERE WERE " + numMatches + " MATCHES AND THE COMMON LETTERS WERE..." + commonString); - + System.out.println("FROM THE EXACT LETTER MATCHES, YOU KNOW................" + exactString); - + // Win condition - if (exactString.equals(secretWord)) { + if (exactString.equals(secretWord)) { nextStep = Step.USER_WINS; - continue; + continue; } - + // No matches if (numMatches <= 1) { System.out.println(""); System.out.println("IF YOU GIVE UP, TYPE '?' FOR YOUR NEXT GUESS."); } - + System.out.println(""); nextStep = Step.MAKE_GUESS; - break; - + break; + case USER_WINS: - + System.out.println("YOU HAVE GUESSED THE WORD. IT TOOK " + numGuesses + " GUESSES!"); System.out.println(""); - + System.out.print("WANT TO PLAY AGAIN? "); userResponse = scan.nextLine(); - if (userResponse.toUpperCase().equals("YES")) { - nextStep = Step.INITIALIZE; // Play again - } else { - return; // Quit game - } + if (userResponse.toUpperCase().equals("YES")) { + nextStep = Step.INITIALIZE; // Play again + } else { + return; // Quit game + } break; - + default: System.out.println("INVALID STEP"); - break; + break; + + } + + } // End outer while loop - } - - } // End outer while loop - } // End of method startGame - + public static void main(String[] args) { - + Word word = new Word(); word.play(); - + } // End of method main } // End of class Word diff --git a/96_Word/python/word.py b/96_Word/python/word.py index a3689f961..10d1fd209 100644 --- a/96_Word/python/word.py +++ b/96_Word/python/word.py @@ -5,8 +5,20 @@ import random -words = ["DINKY", "SMOKE", "WATER", "GRASS", "TRAIN", "MIGHT", "FIRST", - "CANDY", "CHAMP", "WOULD", "CLUMP", "DOPEY"] +words = [ + "DINKY", + "SMOKE", + "WATER", + "GRASS", + "TRAIN", + "MIGHT", + "FIRST", + "CANDY", + "CHAMP", + "WOULD", + "CLUMP", + "DOPEY", +] def play_game(): @@ -41,13 +53,17 @@ def play_game(): common_letters = common_letters + guess_word[i] if i == j: guess_progress[j] = guess_word[i] - print("There were", matches, - "matches and the common letters were... " + common_letters) print( - "From the exact letter matches, you know............ " + "".join(guess_progress)) + "There were", + matches, + "matches and the common letters were... " + common_letters, + ) + print( + "From the exact letter matches, you know............ " + + "".join(guess_progress) + ) if "".join(guess_progress) == guess_word: - print("\nYou have guessed the word. It took", - guess_count, "guesses!") + print("\nYou have guessed the word. It took", guess_count, "guesses!") break elif matches == 0: print("\nIf you give up, type '?' for you next guess.") @@ -63,8 +79,7 @@ def main(): keep_playing = True while keep_playing: play_game() - keep_playing = input( - "\nWant to play again? ").lower().startswith("y") + keep_playing = input("\nWant to play again? ").lower().startswith("y") if __name__ == "__main__": diff --git a/96_Word/vbnet/Program.vb b/96_Word/vbnet/Program.vb index cc807e567..4aa585cb4 100644 --- a/96_Word/vbnet/Program.vb +++ b/96_Word/vbnet/Program.vb @@ -50,7 +50,7 @@ Module Word ' A string showing which specific letters have already been guessed ' The integer value showing the number of character matches between guess and target Private Function check_guess(guess As String, target As String, progress As StringBuilder) As Integer - ' Go through each letter of the guess And see which + ' Go through each letter of the guess And see which ' letters match up to the target word. ' For each position that matches, update the progress ' to reflect the guess diff --git a/Sudoku/pascal/sudoku.pas b/Sudoku/pascal/sudoku.pas index 5edd5d157..c5a61762d 100644 --- a/Sudoku/pascal/sudoku.pas +++ b/Sudoku/pascal/sudoku.pas @@ -156,7 +156,7 @@ goto repeatative2 end; goto randoms -end; +end; end; end; @@ -333,7 +333,7 @@ -2 : x:=4; 58 : x:=52; end; - + gotoxy(x,y); v:=true; @@ -379,4 +379,4 @@ yn:=readkey; until yn=chr(13); -end. \ No newline at end of file +end. diff --git a/buildJvm/README.md b/buildJvm/README.md index c08811b9d..42e540a35 100644 --- a/buildJvm/README.md +++ b/buildJvm/README.md @@ -40,7 +40,7 @@ own fork this will be `https://github.com/YOURNAMEHERE/basic-computer-games.git` 2. Choose a directory for the clone to live in 3. Click `Clone` -The project will open, and eventually you will get a little alert box in the bottom right corner saying "Gradle build script found". +The project will open, and eventually you will get a little alert box in the bottom right corner saying "Gradle build script found". Click the "Load" link in the alert box, to load the gradle project. @@ -58,7 +58,7 @@ local clone to point to your new forked project. These are build scripts for all JVM games contributed so far. New games can be added: - Create a new `build_NUMBER_NAME_[java/kotlin]` directory -- Add a `build.gradle` file to that directory. +- Add a `build.gradle` file to that directory. All `build.gradle` files under `build_NUMBER_*` are identical. - Add a `gradle.properties` file to that directory, defining the source directory for the java or kotlin file, and the class that contains the `main` method. @@ -121,7 +121,7 @@ dependencies { } ``` -The gradle.properties needs an additional directory name for the tests, as `gameTest` : +The gradle.properties needs an additional directory name for the tests, as `gameTest` : ``` gameSource=03_Animal/java/src gameTest=03_Animal/java/test @@ -155,11 +155,11 @@ class AnimalJavaTest : ConsoleTest() { ``` Curly brackets are the expected user input. -Note - this is actually just a way of defining the expected input as "PAUL" and "YES" +Note - this is actually just a way of defining the expected input as "PAUL" and "YES" and not that the input happens at the exact prompt position. Thus this is equivalent: ```kotlin """ -{PAUL} {YES} WHAT'S YOUR NAME? +{PAUL} {YES} WHAT'S YOUR NAME? YOUR NAME IS PAUL? THANKS FOR PLAYING """ diff --git a/buildJvm/build.gradle.kts b/buildJvm/build.gradle.kts index 6cfba2e7b..0d37953de 100644 --- a/buildJvm/build.gradle.kts +++ b/buildJvm/build.gradle.kts @@ -60,4 +60,4 @@ fun filesType(type: String) = fileTree("$buildDir/..").files.filter { it.path.contains("build/install/build_.*/$type".toRegex()) && it.isFile - } \ No newline at end of file + } diff --git a/buildJvm/build_24_Chemist_java/gradle.properties b/buildJvm/build_24_Chemist_java/gradle.properties index 84362ea33..e4a4a594c 100644 --- a/buildJvm/build_24_Chemist_java/gradle.properties +++ b/buildJvm/build_24_Chemist_java/gradle.properties @@ -1,2 +1,2 @@ gameSource=24_Chemist/java/src -gameMain=ChemistGame \ No newline at end of file +gameMain=ChemistGame diff --git a/buildJvm/build_25_Chief_java/gradle.properties b/buildJvm/build_25_Chief_java/gradle.properties index af8dd77a3..e0eed8634 100644 --- a/buildJvm/build_25_Chief_java/gradle.properties +++ b/buildJvm/build_25_Chief_java/gradle.properties @@ -1,2 +1,2 @@ gameSource=25_Chief/java/src -gameMain=ChiefGame \ No newline at end of file +gameMain=ChiefGame diff --git a/buildJvm/build_33_Dice_java/gradle.properties b/buildJvm/build_33_Dice_java/gradle.properties index a04a70cfa..77cfe4285 100644 --- a/buildJvm/build_33_Dice_java/gradle.properties +++ b/buildJvm/build_33_Dice_java/gradle.properties @@ -1,2 +1,2 @@ gameSource=33_Dice/java/src -gameMain=DiceGame \ No newline at end of file +gameMain=DiceGame diff --git a/buildJvm/build_38_Fur_Trader_java/gradle.properties b/buildJvm/build_38_Fur_Trader_java/gradle.properties index 13eafeb46..4ff34b338 100644 --- a/buildJvm/build_38_Fur_Trader_java/gradle.properties +++ b/buildJvm/build_38_Fur_Trader_java/gradle.properties @@ -1,2 +1,2 @@ gameSource=38_Fur_Trader/java/src -gameMain=FurTraderGame \ No newline at end of file +gameMain=FurTraderGame diff --git a/buildJvm/build_41_Guess_java/gradle.properties b/buildJvm/build_41_Guess_java/gradle.properties index f03bfad15..19b97033a 100644 --- a/buildJvm/build_41_Guess_java/gradle.properties +++ b/buildJvm/build_41_Guess_java/gradle.properties @@ -1,2 +1,2 @@ gameSource=41_Guess/java/src -gameMain=GuessGame \ No newline at end of file +gameMain=GuessGame diff --git a/buildJvm/build_47_Hi-Lo_java/gradle.properties b/buildJvm/build_47_Hi-Lo_java/gradle.properties index 5ee2a2373..f464c19e4 100644 --- a/buildJvm/build_47_Hi-Lo_java/gradle.properties +++ b/buildJvm/build_47_Hi-Lo_java/gradle.properties @@ -1,2 +1,2 @@ gameSource=47_Hi-Lo/java/src -gameMain=HiLoGame \ No newline at end of file +gameMain=HiLoGame diff --git a/buildJvm/build_51_Hurkle_java/gradle.properties b/buildJvm/build_51_Hurkle_java/gradle.properties index 508804ffc..7151e8d4d 100644 --- a/buildJvm/build_51_Hurkle_java/gradle.properties +++ b/buildJvm/build_51_Hurkle_java/gradle.properties @@ -1,2 +1,2 @@ gameSource=51_Hurkle/java/src -gameMain=HurkleGame \ No newline at end of file +gameMain=HurkleGame diff --git a/buildJvm/build_52_Kinema_java/gradle.properties b/buildJvm/build_52_Kinema_java/gradle.properties index 8ab182cf9..bfa9a2573 100644 --- a/buildJvm/build_52_Kinema_java/gradle.properties +++ b/buildJvm/build_52_Kinema_java/gradle.properties @@ -1,2 +1,2 @@ gameSource=52_Kinema/java/src -gameMain=KinemaGame \ No newline at end of file +gameMain=KinemaGame diff --git a/buildJvm/build_54_Letter_java/gradle.properties b/buildJvm/build_54_Letter_java/gradle.properties index bda98ac65..37511a56c 100644 --- a/buildJvm/build_54_Letter_java/gradle.properties +++ b/buildJvm/build_54_Letter_java/gradle.properties @@ -1,2 +1,2 @@ gameSource=54_Letter/java/src -gameMain=LetterGame \ No newline at end of file +gameMain=LetterGame diff --git a/buildJvm/build_61_Math_Dice_java/gradle.properties b/buildJvm/build_61_Math_Dice_java/gradle.properties index 0439407b0..7644f2be4 100644 --- a/buildJvm/build_61_Math_Dice_java/gradle.properties +++ b/buildJvm/build_61_Math_Dice_java/gradle.properties @@ -1,2 +1,2 @@ gameSource=61_Math_Dice/java -gameMain=MathDice \ No newline at end of file +gameMain=MathDice diff --git a/buildJvm/build_92_Trap_java/gradle.properties b/buildJvm/build_92_Trap_java/gradle.properties index a01ba4ea5..3b4e9a752 100644 --- a/buildJvm/build_92_Trap_java/gradle.properties +++ b/buildJvm/build_92_Trap_java/gradle.properties @@ -1,2 +1,2 @@ gameSource=92_Trap/java/src -gameMain=TrapGame \ No newline at end of file +gameMain=TrapGame diff --git a/buildJvm/build_93_23_Matches_java/gradle.properties b/buildJvm/build_93_23_Matches_java/gradle.properties index c1b1c2697..b9ae6b7bc 100644 --- a/buildJvm/build_93_23_Matches_java/gradle.properties +++ b/buildJvm/build_93_23_Matches_java/gradle.properties @@ -1,2 +1,2 @@ gameSource=93_23_Matches/java -gameMain=TwentyThreeMatchesGame \ No newline at end of file +gameMain=TwentyThreeMatchesGame