diff --git a/src/day-1-toy/args.py b/src/day-1-toy/args.py index 06a830e4c8..2d84cb247f 100644 --- a/src/day-1-toy/args.py +++ b/src/day-1-toy/args.py @@ -5,13 +5,19 @@ # the sum. This is what you'd consider to be a regular, normal function. #def f1(... - -print(f1(1, 2)) +def f1(arg1, arg2): + return arg1 + arg2 +print("hello", f1(1, 2)) # Write a function f2 that takes any number of iteger arguments and prints the # sum. Google for "python arbitrary arguments" and look for "*args" # def f2(... +def f2(*args): + total = 0 + for i in args: + total += i + return total print(f2(1)) # Should print 1 print(f2(1, 3)) # Should print 4 @@ -21,14 +27,25 @@ a = [7, 6, 5, 4] # What thing do you have to add to make this work? -print(f2(a)) # Should print 22 +print(f2(*a)) # Should print 22 # Write a function f3 that accepts either one or two arguments. If one argument, # it returns that value plus 1. If two arguments, it returns the sum of the # arguments. Google "python default arguments" for a hint. #def f3(... - +# def f3(*args): +# total = 0 +# if len(args) > 1: +# for i in args: +# total += i +# else: +# for i in args: +# total += i + 1 +# return total + +def f3(a, b=1): + return a + b print(f3(1, 2)) # Should print 3 print(f3(8)) # Should print 9 @@ -42,7 +59,9 @@ # Google "python keyword arguments". #def f4(... - +def f4(**kwargs): + for key, value in kwargs.items(): + print(f'key: {key}, value: {value}') # Should print # key: a, value: 12 # key: b, value: 30 @@ -60,4 +79,4 @@ } # What thing do you have to add to make this work? -f4(d) \ No newline at end of file +f4(**d) \ No newline at end of file diff --git a/src/day-1-toy/bar.txt b/src/day-1-toy/bar.txt new file mode 100644 index 0000000000..53681d8af4 --- /dev/null +++ b/src/day-1-toy/bar.txt @@ -0,0 +1,3 @@ +Hi +This is +a new line \ No newline at end of file diff --git a/src/day-1-toy/bignum.py b/src/day-1-toy/bignum.py index 77e8d66ffa..e0a7f0fe7e 100644 --- a/src/day-1-toy/bignum.py +++ b/src/day-1-toy/bignum.py @@ -1 +1,5 @@ -# Print out 2 to the 65536 power \ No newline at end of file +# Print out 2 to the 65536 power + +print( 2 ** 65536) + +# print (pow(2, 65536)) \ No newline at end of file diff --git a/src/day-1-toy/cal.py b/src/day-1-toy/cal.py index 2a3771eb5b..2bcac44c29 100644 --- a/src/day-1-toy/cal.py +++ b/src/day-1-toy/cal.py @@ -14,3 +14,38 @@ # docs for the calendar module closely. import sys +import calendar +import datetime + +month = sys.argv[1] +year = sys.argv[2] +print(str(month) + ", " + str(year)) + +if month == None: + month = 8 + +if year == None: + year = 2018 + +myCal = calendar.TextCalendar() +print( myCal.formatmonth( int(year), int(month))) + + +# current = datetime.datetime.now() +# cal = calendar.TextCalendar() + +# year = input("Enter 4 Digit Year: ") +# month = input("Enter Month 1 - 12: ") + +# if len(sys.argv) == 3: +# year = int(sys.argv[1]) +# month = int(sys.argv[2]) +# print(cal.formatmonth(int(year), int(month))) +# else: +# year = current.year +# month = current.month +# print(cal.formatmonth(int(year), int(month))) + + + + diff --git a/src/day-1-toy/comp.py b/src/day-1-toy/comp.py index 083e9b9140..d9839bcaba 100644 --- a/src/day-1-toy/comp.py +++ b/src/day-1-toy/comp.py @@ -1,13 +1,13 @@ # Write a list comprehension to produce the array [1, 2, 3, 4, 5] -y = [] +y = [i for i in range(6)] print (y) # Write a list comprehension to produce the cubes of the numbers 0-9: # [0, 1, 8, 27, 64, 125, 216, 343, 512, 729] -y = [] +y = [ i **3 for i in range(10)] print(y) @@ -16,7 +16,7 @@ a = ["foo", "bar", "baz"] -y = [] +y = [str.upper() for str in a] print(y) @@ -26,7 +26,8 @@ x = input("Enter comma-separated numbers: ").split(',') # What do you need between the square brackets to make it work? -y = [] +y = [int(i) for i in x if int(i) %2 == 0] print(y) +# or y = [int(num) for num in x if int(num) %2 == 0] diff --git a/src/day-1-toy/datatypes.py b/src/day-1-toy/datatypes.py index f5967611a7..aaa2797b2c 100644 --- a/src/day-1-toy/datatypes.py +++ b/src/day-1-toy/datatypes.py @@ -2,7 +2,7 @@ y = "7" # Write a print statement that combines x + y into the integer value 12 -print(x + y) +print(x + int(y)) # Write a print statement that combines x + y into the string value 57 -print(x + y) \ No newline at end of file +print(str(x) + y) \ No newline at end of file diff --git a/src/day-1-toy/dicts.py b/src/day-1-toy/dicts.py index eac1779a42..a79af3fa9e 100644 --- a/src/day-1-toy/dicts.py +++ b/src/day-1-toy/dicts.py @@ -21,9 +21,26 @@ "lat": 43, "lon": -122, "name": "a third place" + }, + { + "lat": 42, + "lon": -333, + "name": "a new world" } ] # Write a loop that prints out all the field values for all the waypoints +# print([key for key in waypoints]) +# for i in waypoints: +# print(i["lat"]) +# print(i["lon"]) +# print(i["name"]) + +for w in waypoints: + print( str(w["lat"]) + " " + str(w["lon"]) + " " + str(w["name"])) # Add a new waypoint to the list +waypoints.append({"lat": 44, "lon": -22, "name": "newwe"}) + +for w in waypoints: + print( str(w["lat"]) + " " + str(w["lon"]) + " " + str(w["name"])) diff --git a/src/day-1-toy/fileio.py b/src/day-1-toy/fileio.py index bc8e79b7cc..1171142c69 100644 --- a/src/day-1-toy/fileio.py +++ b/src/day-1-toy/fileio.py @@ -1,12 +1,19 @@ # Use open to open file "foo.txt" for reading +file = open('foo.txt', 'r') # Print all the lines in the file +for line in file: + print(line) # Close the file - +file.close() # Use open to open file "bar.txt" for writing - +file = open('bar.txt', 'w') # Use the write() method to write three lines to the file +file.write("Hi\n") +file.write("This is\n") +file.write("a new line") -# Close the file \ No newline at end of file +# Close the file +file.close() \ No newline at end of file diff --git a/src/day-1-toy/func.py b/src/day-1-toy/func.py index 2b7f435ffa..bb4cdadce4 100644 --- a/src/day-1-toy/func.py +++ b/src/day-1-toy/func.py @@ -3,4 +3,10 @@ # Read a number from the keyboard num = input("Enter a number: ") +def is_even(num): + if int(num) % 2 == 0: + return "Even!" + else: + return "Odd" +print(is_even(num)) # Print out "Even!" if the number is even. Otherwise print "Odd" \ No newline at end of file diff --git a/src/day-1-toy/hello.py b/src/day-1-toy/hello.py index 37968da4d4..bab8bf269e 100644 --- a/src/day-1-toy/hello.py +++ b/src/day-1-toy/hello.py @@ -1 +1,3 @@ -# Write Hello, world \ No newline at end of file +# Write Hello, world + +print("Hello, world") \ No newline at end of file diff --git a/src/day-1-toy/lists.py b/src/day-1-toy/lists.py index 6076f340a9..e231f260ff 100644 --- a/src/day-1-toy/lists.py +++ b/src/day-1-toy/lists.py @@ -8,22 +8,29 @@ # Change x so that it is [1, 2, 3, 4] # [command here] +x.append(4) print(x) # Using y, change x so that it is [1, 2, 3, 4, 8, 9, 10] # [command here] +x.extend(y) #x = x+ y print(x) # Change x so that it is [1, 2, 3, 4, 9, 10] # [command here] +x.remove(8) print(x) # Change x so that it is [1, 2, 3, 4, 9, 99, 10] # [command here] +x.insert(5, 99) print(x) # Print the length of list x # [command here] print(len(x)) -# Using a for loop, print all the element values multiplied by 1000 \ No newline at end of file +# Using a for loop, print all the element values multiplied by 1000 + +for i in x: + print(i * 1000) \ No newline at end of file diff --git a/src/day-1-toy/modules.py b/src/day-1-toy/modules.py index 5313fc1934..a4290b7879 100644 --- a/src/day-1-toy/modules.py +++ b/src/day-1-toy/modules.py @@ -7,12 +7,16 @@ # Print out the command line arguments in sys.argv, one per line: +# print(sys.argv[0]) +for arg in sys.argv: + print(arg) # Print out the plaform from sys: -print() +print(sys.platform) # Print out the Python version from sys: -print() +# print(sys.version_info) +print(sys.version) @@ -21,11 +25,11 @@ # See the docs for the OS module: https://docs.python.org/3.7/library/os.html # Print the current process ID -print() +print(os.getpid()) # Print the current working directory (cwd): -print() +print(os.getcwd()) # Print your login name -print() +print(os.getlogin()) diff --git a/src/day-1-toy/obj.py b/src/day-1-toy/obj.py index 84c78a2f53..9c1f4772fe 100644 --- a/src/day-1-toy/obj.py +++ b/src/day-1-toy/obj.py @@ -1,14 +1,32 @@ # Make a class LatLon that can be passed parameters `lat` and `lon` to the # constructor - +class LatLon: + def __init__(self, lat, lon): + self.lat = lat + self.lon = lon # Make a class Waypoint that can be passed parameters `name`, `lat`, and `lon` to the # constructor. It should inherit from LatLon. +class Waypoint(LatLon): + def __init__(self, name, lat, lon): + LatLon.__init__(self, lat, lon) + self.name = name + def __str__(self): + return "Name: " + self.name + "\tLat: " + str(self.lat) + "\tLon: " + str(self.lon) + # Make a class Geocache that can be passed parameters `name`, `difficulty`, # `size`, `lat`, and `lon` to the constructor. What should it inherit from? -# Make a new waypoint "Catacombs", 41.70505, -121.51521 +class Geocache(Waypoint): + def __init__(self, name, difficulty, size, lat, lon): + super().__init__(name, lat, lon) + self.difficulty = difficulty + self.size = size + def __str__(self): + return "Name: " + self.name + "\tDifficulty: " + str(self.difficulty) + "\tSize: " + str(self.size) +# Make a new waypoint "Catacombs", 41.70505, -121.51521 +w = Waypoint("Catacombs", 41.3939, -22222) # Print it # # Without changing the following line, how can you make it print into something @@ -16,6 +34,6 @@ print(w) # Make a new geocache "Newberry Views", diff 1.5, size 2, 44.052137, -121.41556 - +g = Geocache("Newberry Views", 1.5, 2, 33.333, -2222 ) # Print it--also make this print more nicely print(g) diff --git a/src/day-1-toy/printf.py b/src/day-1-toy/printf.py index d4bc9abb48..d694090f6d 100644 --- a/src/day-1-toy/printf.py +++ b/src/day-1-toy/printf.py @@ -5,6 +5,9 @@ # Using the printf operator (%), print the following feeding in the values of x, # y, and z: # x is 10, y is 2.25, z is "I like turtles!" +print('x is %d, y is %.2f, z is %s' % (x, y, z)) +# Use the 'format' string method to print the same thing +# print( 'x is {0}, y is {1}, z is "{2}"'.format(x, y, z)) -# Use the 'format' string method to print the same thing \ No newline at end of file +print("x is {}, y is {}, z is {}".format(x, round(y, 2), z)) \ No newline at end of file diff --git a/src/day-1-toy/scope.py b/src/day-1-toy/scope.py index 68ecc6c412..38348722f1 100644 --- a/src/day-1-toy/scope.py +++ b/src/day-1-toy/scope.py @@ -5,8 +5,9 @@ x = 12 def changeX(): + global x x = 99 - + changeX() # This prints 12. What do we have to modify in changeX() to get it to print 99? @@ -19,6 +20,7 @@ def outer(): y = 120 def inner(): + nonlocal y y = 999 inner() diff --git a/src/day-1-toy/slice.py b/src/day-1-toy/slice.py index 3c6cb38730..632a228091 100644 --- a/src/day-1-toy/slice.py +++ b/src/day-1-toy/slice.py @@ -1,26 +1,27 @@ a = [2, 4, 1, 7, 9, 6] # Output the second element: 4: -print() +print(a[1]) # Output the second-to-last element: 9 -print() +print(a[4]) # Output the last three elements in the array: [7, 9, 6] -print() +print(a[3: ]) # Output the two middle elements in the array: [1, 7] -print() +print(a[2:4]) # Output every element except the first one: [4, 1, 7, 9, 6] -print() + +print(a[1:]) # Output every element except the last one: [2, 4, 1, 7, 9] -print() +print(a[:-1]) # For string s... s = "Hello, world!" # Output just the 8th-12th characters: "world" -print() \ No newline at end of file +print(s[7:12]) \ No newline at end of file diff --git a/src/day-1-toy/tuples.py b/src/day-1-toy/tuples.py index ec42b0cdf8..3d86e23a43 100644 --- a/src/day-1-toy/tuples.py +++ b/src/day-1-toy/tuples.py @@ -23,10 +23,16 @@ def dist(a, b): # Write a function that prints all the values in a tuple # def print_tuple(... - t = (1, 2, 5, 7, 99) -print_tuple(t) # Prints 1 2 5 7 99, one per line +def print_tuple(t): + for i in t: + print(i) + # Prints 1 2 5 7 99, one per line + print(print_tuple(t)) # Declare a tuple of 1 element then print it -u = (1) # What needs to be added to make this work? + + +u = (1,) # What needs to be added to make this work? +# print(u) print_tuple(u) diff --git a/src/days-2-4-adv/adv.py b/src/days-2-4-adv/adv.py index c9e26b0f85..fa0b9a12d6 100644 --- a/src/days-2-4-adv/adv.py +++ b/src/days-2-4-adv/adv.py @@ -1,51 +1,192 @@ from room import Room +from player import Player +from item import Item, Treasure, LightSource +import crayons # Declare all the rooms room = { - 'outside': Room("Outside Cave Entrance", - "North of you, the cave mount beckons"), + 'village': Room("Village Hidden in the Spring", + "The noise of bustling streets warms your heart", [Treasure("Coin", "Starting money, how lucky!", 10)]), - 'foyer': Room("Foyer", """Dim light filters in from the south. Dusty -passages run north and east."""), + 'home': Room("Home Sweet Home", """Dim light filters in from the south. Dusty +passages run north and east.""", [Item("Meal", "This item restores your health.")]), - 'overlook': Room("Grand Overlook", """A steep cliff appears before you, falling + 'attic': Room("Attic Room", """A steep cliff appears before you, falling into the darkness. Ahead to the north, a light flickers in -the distance, but there is no way across the chasm."""), +the distance, but there is no way across the chasm.""", []), - 'narrow': Room("Narrow Passage", """The narrow passage bends here from west -to north. The smell of gold permeates the air."""), + 'forest': Room("Grand Forest", """The narrow passage bends here from west +to north. The smell of gold permeates the air.""", []), - 'treasure': Room("Treasure Chamber", """You've found the long-lost treasure + 'overlook': Room("Mountain Overlook", """A steep mountain appears before you. The forest expands in all directions. Perhaps a further look is needed...""", []), + + 'peak': Room("Mountain Peak", """The fresh air soothes your senses, the forest expanse looks peaceful. The village looks minute in the distance.""", []), + + 'cave': Room("North Cave", """Creaking sounds resonate throughout the cave.""", []), + + 'underground1': Room("Underground Passage", """The narrow passage bends here from west +to north. The smell of gold permeates the air.""", []), + + 'tunnels': Room("Dark Tunnels", """The narrow passage bends here from west +to north. The smell of gold permeates the air.""", []), + + 'secret': Room("Secret Passage", """The passage holds an air of mystery. The walls glimmer with something hidden beneath.""", []), + + 'epic': Room("Epic Treasure", """The room contains the most special of treasure chests. Open it to reveal your prize.""", []), + + 'underground2': Room("Damp Underground Passage", """Moist droplets of water fall from the passage's crevices.""", []), + + 'dragon': Room("Dragon Lair", """You've found the long-lost treasure chamber! Sadly, it has already been completely emptied by -earlier adventurers. The only exit is to the south."""), +earlier adventurers. The only exit is to the south.""", []), + + 'swamp': Room("Sinister Swamp", """The narrow passage bends here from west +to north. The smell of gold permeates the air.""", []), + + 'mangroves': Room("Mangrove Forest", """The narrow passage bends here from west +to north. The smell of gold permeates the air.""", []), } # Link rooms together -room['outside'].n_to = room['foyer'] -room['foyer'].s_to = room['outside'] -room['foyer'].n_to = room['overlook'] -room['foyer'].e_to = room['narrow'] -room['overlook'].s_to = room['foyer'] -room['narrow'].w_to = room['foyer'] -room['narrow'].n_to = room['treasure'] -room['treasure'].s_to = room['narrow'] - +room['village'].n_to = room['forest'] +room['forest'].s_to = room['village'] +room['village'].s_to = room['home'] +room['home'].n_to = room['village'] +room['home'].u_to = room['attic'] +room['attic'].d_to = room['home'] +room['forest'].w_to = room['overlook'] +room['overlook'].e_to = room['forest'] +room['overlook'].u_to = room['peak'] +room['peak'].d_to = room['overlook'] +room['forest'].e_to = room['mangroves'] +room['mangroves'].w_to = room['forest'] +room['forest'].n_to = room['cave'] +room['cave'].s_to = room['forest'] +room['cave'].d_to = room['underground1'] +room['underground1'].u_to = room['cave'] +room['underground1'].e_to = room['tunnels'] +room['tunnels'].w_to = room['underground1'] +room['tunnels'].e_to = room['dragon'] +room['dragon'].w_to = room['tunnels'] +room['tunnels'].n_to = room['secret'] +room['secret'].s_to = room['tunnels'] +room['tunnels'].s_to = room['underground2'] +room['underground2'].n_to = room['tunnels'] +room['underground2'].u_to = room['swamp'] +room['swamp'].d_to = room['underground2'] +room['swamp'].n_to = room['mangroves'] +room['mangroves'].s_to = room['swamp'] # # Main # # Make a new player object that is currently in the 'outside' room. +name = input('Enter your name: ') +newplayer = Player(name, room['village'], []) +cmd = "" +print(crayons.green(f'\n \t Welcome, {newplayer.name}!\n')) #crayons.green( + +# print_room_info() +# print() +# cmd = print_help() + # Write a loop that: # +while not cmd == "q": + print(newplayer.room.name) # * Prints the current room name + print(newplayer.room.description) # * Prints the current description (the textwrap module might be useful here). # * Waits for user input and decides what to do. + newplayer.room.view_items() + cmd = input("\n Please choose a direction...n, s, e, w, OR q to quit the game.\n ").lower() # + parsed_cmd = cmd.split() + if len(parsed_cmd) > 1: + action = parsed_cmd[0] + item = "" + for i in range(1, len(parsed_cmd)): + item += parsed_cmd[i] + " " + item = item.strip()# array of commands + + + if action == "g" or action == "grab": + for i in newplayer.room.items: + if i.name.lower() == parsed_cmd[1]: + i.grab_item(newplayer) + # print("\n...grabbing" +".") + # print(i) + # newplayer.room.items.remove(i) + # newplayer.items.append(i) + # newplayer.score += i.value + # print("player items", newplayer.items[0].name) + print("player items", newplayer.items[0]) + else: + print("\nitem not available to grab") + for i in newplayer.room.items: + print("after", i.name) + elif action == "d" or action == "drop": + print("checked", i, newplayer.items[0]) + for i in newplayer.items: + if i.name.lower() == parsed_cmd[1]: + print("\t...dropping .") + newplayer.items.remove(i) + newplayer.room.items.append(i) + else: + print("item not available to drop!") + + else: #parsed_cmd length =1 # If the user enters a cardinal direction, attempt to move to the room there. -# Print an error message if the movement isn't allowed. -# -# If the user enters "q", quit the game. + if cmd == "n": + if hasattr(newplayer.room, "n_to"): + newplayer.room = newplayer.room.n_to + else: + print("Sorry, you can't go that way") + elif cmd == "score": + # cmd = input( f'Score: {newplayer.score} \n') + print( f'Score: {newplayer.score} \n') + # elif cmd == "?" + # cmd = print_help() + elif cmd == "i" or cmd =="inventory": + if len(newplayer.items) == 0: + print("Inventory is empty") + else: + print("You are carrying: \n") + for item in newplayer.items: + print("\t" + str(item)) + elif cmd == "s": + if hasattr(newplayer.room, "s_to"): + newplayer.room = newplayer.room.s_to + else: + print("Sorry, you can't go that way") + elif cmd == "w": + if hasattr(newplayer.room, "w_to"): + newplayer.room = newplayer.room.w_to + else: + print("Sorry, you can't go that way") + elif cmd == "e": + if hasattr(newplayer.room, "e_to"): + newplayer.room = newplayer.room.e_to + else: + print("Sorry, you can't go that way") + elif cmd == "u": + if hasattr(newplayer.room, "u_to"): + newplayer.room = newplayer.room.u_to + else: + print("Sorry, you can't go that way") + elif cmd == "d": + if hasattr(newplayer.room, "d_to" ): + newplayer.room = newplayer.room.d_to + else: + print("Sorry, you can't go that way") + # Print an error message if the movement isn't allowed. + # + # If the user enters "q", quit the game. + elif cmd == "q": + print("Thank you for playing!") + else: + print("\nInvalid selection.") diff --git a/src/days-2-4-adv/item.py b/src/days-2-4-adv/item.py new file mode 100644 index 0000000000..2619448561 --- /dev/null +++ b/src/days-2-4-adv/item.py @@ -0,0 +1,26 @@ +import crayons + +class Item: + def __init__(self, name, description): + self.name = name + self.description = description + + def __str__(self): + return self.name + ": " + self.description + + def grab_item(self, newplayer): + print(crayons.blue("\n...grabbing" +".")) + newplayer.room.items.remove(self) + newplayer.items.append(self) + +class Treasure(Item): + def __init__( self, name, description, value): + super().__init__(name, description) + self.value = value + self.picked_up = False + def grab_item(self, newplayer): + super().grab_item(newplayer) + if self.picked_up == False: + newplayer.score += self.value + self.picked_up = True + diff --git a/src/days-2-4-adv/player.py b/src/days-2-4-adv/player.py index d79a175029..7a15b57c81 100644 --- a/src/days-2-4-adv/player.py +++ b/src/days-2-4-adv/player.py @@ -1,2 +1,9 @@ # Write a class to hold player information, e.g. what room they are in # currently. +class Player: + def __init__( self, name, room, items): + self.name = name + self.room = room + self.items = items + self.score = 0 + self.light = False \ No newline at end of file diff --git a/src/days-2-4-adv/room.py b/src/days-2-4-adv/room.py index 24c07ad4c8..c718f9c814 100644 --- a/src/days-2-4-adv/room.py +++ b/src/days-2-4-adv/room.py @@ -1,2 +1,15 @@ # Implement a class to hold room information. This should have name and -# description attributes. \ No newline at end of file +# description attributes. +class Room: + def __init__(self, name, description, items): + self.name = name + self.description = description + self.items = items + def view_items(self): + print("Items found in this room: ") + if len(self.items) == 0: + print( "\n \t none") + else: + for i in self.items: + # print("\t" + i.name) + print( "\t " + str(i)) \ No newline at end of file diff --git a/src/mini-challenge/hangman.py b/src/mini-challenge/hangman.py index 9b73b9249d..dbaf063089 100644 --- a/src/mini-challenge/hangman.py +++ b/src/mini-challenge/hangman.py @@ -5,69 +5,77 @@ # STRETCH GOAL: If you fix all the errors, can you find a way to improve # it? Add a cheat code, more error handling, chose randomly # from a set of win/loss messages...basically, make it better! - +import random # Initial setup bodies = [ " ------\n | |\n | O\n |\n |\n |\n |\n |\n---", " ------\n | |\n | O\n | |\n | |\n |\n |\n |\n---", " ------\n | |\n | O\n | |\n | |\n | / \n |\n |\n---", " ------\n | |\n | O\n | |\n | |\n | / \ \n |\n |\n---", " ------\n | |\n | O\n | \|\n | |\n | / \ \n |\n |\n---", -" ------\n | |\n | O\n | \|/\n | |\n | / \ \n |\n |\n---" ] +" ------\n | |\n | O\n | \|/\n | |\n | / \ \n |\n |\n---" ] strikes = 0 words = [None] -file = open("word.txt", "r") +file = open("words.txt", "r") for line in file: words.append(line) file.close() -targetWord = words[random.randint(0, 100)] -lettersLeft = len(targetWord)-1 -length = len(targetWord)-1 -curWord = "_" * length -alphabet = [chr(65+x) for x in range(1, 26) ] +target_word = words[random.randint(0, len(words))] +letters_left = len(target_word)-1 +length = len(target_word)-1 +cur_word = "_" * length +alphabet = [chr(65+x) for x in range(0, 26) ] # Draw body based on # of incorrect guesses -def drawBody() +def drawBody(): print(bodies[strikes]) # Replace blanks with correctly guessed letters def fillLetters( letter ): - for i in range(len(targetWord)-1): - if( targetWord[i : i+1]) == letter: - curWord = curWord[0: i] + letter + curWord[i: ] - global lettersLeft - lettersLeft -= 1 + for i in range(len(target_word)-1): + if( target_word[i : i+1]) == letter: + global cur_word + cur_word = cur_word[0: i] + letter + cur_word[i+1: ] + global letters_left + letters_left -= 1 # Add spaces when displaying letters / blanks for readability def printWord( word ): - prntWord = "" + prnt_word = "" for letter in word: - prntWord += letter + " " - print(prntWord) + prnt_word += letter + " " + print(prnt_word) # Begin game -print( "Welcome to Hangmn!" ) -printWord(curWord) +print( "Welcome to Hangman!" ) +printWord(cur_word) drawBody() print("Letters left:") printWord(alphabet) - +printWord(target_word) # Gameplay loop -while strikes < 5 and lettersLeft > 0: +while strikes < 5 and letters_left > 0: letter = input("\nPlease guess a letter...") - if letter in targetWord: + if not letter.isalpha(): + print("Please only enter letters") + elif len(letter) > 1: + print("Please guess only a single letter.") + elif not letter.upper() in alphabet: + print("Already guessed this letter!") + elif letter in target_word: print("Great!") fillLetters(letter) + alphabet.remove(letter.upper()) else: strikes += 1 - print( strikes + " / 5 strikes" ) - printWord(curWord) + print( str(strikes) + " / 5 strikes" ) + alphabet.remove(letter.upper()) + printWord(cur_word) drawBody() - alphabet.remove(letter.upper()) print("Letters left:") printWord(alphabet) # Game over, print outcome -if lettersLeft < 0: +if letters_left == 0: print("YOU WIN!!") else: - print("YOU LOSE...word was " + targetWord) \ No newline at end of file + print("YOU LOSE...word was " + target_word) \ No newline at end of file