diff --git a/src/day-1-toy/args.py b/src/day-1-toy/args.py index 06a830e4c8..223f99c9dd 100644 --- a/src/day-1-toy/args.py +++ b/src/day-1-toy/args.py @@ -4,7 +4,8 @@ # Write a function f1 that takes two integer positional arguments and returns # the sum. This is what you'd consider to be a regular, normal function. -#def f1(... +def f1(num, num2): + return num + num2 print(f1(1, 2)) @@ -12,6 +13,11 @@ # sum. Google for "python arbitrary arguments" and look for "*args" # def f2(... +def f2(*args, **kwargs): + sum = 0 + for num in args: + sum += num + return sum print(f2(1)) # Should print 1 print(f2(1, 3)) # Should print 4 @@ -21,13 +27,16 @@ 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(arg, arg2=None): + if arg2 is None: + return arg + 1 + return arg + arg2 print(f3(1, 2)) # Should print 3 print(f3(8)) # Should print 9 @@ -41,7 +50,10 @@ # # Google "python keyword arguments". -#def f4(... +def f4(*args, **kwargs): + for key, val in kwargs.items(): + print(f"Key: {key}, Value: {val}") + # Should print # key: a, value: 12 @@ -60,4 +72,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..f0a7afd9c5 --- /dev/null +++ b/src/day-1-toy/bar.txt @@ -0,0 +1,3 @@ +Hello +This is easy +I am ready for Django \ No newline at end of file diff --git a/src/day-1-toy/bignum.py b/src/day-1-toy/bignum.py index 77e8d66ffa..84eddd1925 100644 --- a/src/day-1-toy/bignum.py +++ b/src/day-1-toy/bignum.py @@ -1 +1,2 @@ -# Print out 2 to the 65536 power \ No newline at end of file +# Print out 2 to the 65536 power +print(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..f5700838fa 100644 --- a/src/day-1-toy/cal.py +++ b/src/day-1-toy/cal.py @@ -14,3 +14,9 @@ # docs for the calendar module closely. import sys +import calendar +import datetime + +year, month = int(sys.argv[1]), int(sys.argv[2]) +print(calendar.monthcalendar(year, month)) + diff --git a/src/day-1-toy/comp.py b/src/day-1-toy/comp.py index 083e9b9140..fd22b54fa8 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 = [x for x in range(1, 6)] -print (y) +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 = [x**3 for x in range(10)] print(y) @@ -16,7 +16,7 @@ a = ["foo", "bar", "baz"] -y = [] +y = [x.upper() for x in a] print(y) @@ -26,7 +26,7 @@ x = input("Enter comma-separated numbers: ").split(',') # What do you need between the square brackets to make it work? -y = [] +y = [num for num in x if int(num) % 2 == 0] print(y) 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..dc05e1ad1f 100644 --- a/src/day-1-toy/dicts.py +++ b/src/day-1-toy/dicts.py @@ -11,12 +11,12 @@ "lat": 43, "lon": -121, "name": "a place" - }, + }, { "lat": 41, "lon": -123, "name": "another place" - }, + }, { "lat": 43, "lon": -122, @@ -25,5 +25,11 @@ ] # Write a loop that prints out all the field values for all the waypoints +for point in waypoints: + print(point.items()) # Add a new waypoint to the list +waypoints.append({"lat": 41, "lon": 20, "name": "a fourth place"}) + +for point in waypoints: + print(point.items()) diff --git a/src/day-1-toy/fileio.py b/src/day-1-toy/fileio.py index bc8e79b7cc..b2f92d1712 100644 --- a/src/day-1-toy/fileio.py +++ b/src/day-1-toy/fileio.py @@ -3,10 +3,15 @@ # Print all the lines in the file # Close the file - +with open('foo.txt', 'r') as f: + for line in f.readlines(): + print(line) # Use open to open file "bar.txt" for writing # Use the write() method to write three lines to the file -# Close the file \ No newline at end of file +# Close the file +with open('bar.txt', 'w') as f: + f.write('Hello\nThis is easy\nI am ready for Django') + diff --git a/src/day-1-toy/func.py b/src/day-1-toy/func.py index 2b7f435ffa..23f3ecc91f 100644 --- a/src/day-1-toy/func.py +++ b/src/day-1-toy/func.py @@ -1,6 +1,11 @@ # Write a function is_even that will return true if the passed in number is even. - +def is_even(num): + return int(num) % 2 == 0 # Read a number from the keyboard num = input("Enter a number: ") -# Print out "Even!" if the number is even. Otherwise print "Odd" \ No newline at end of file +# Print out "Even!" if the number is even. Otherwise print "Odd" +if is_even(num): + print('Even!') +else: + 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..2289831365 100644 --- a/src/day-1-toy/hello.py +++ b/src/day-1-toy/hello.py @@ -1 +1,2 @@ -# 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..97ec771f46 100644 --- a/src/day-1-toy/lists.py +++ b/src/day-1-toy/lists.py @@ -7,23 +7,24 @@ # For the following, DO NOT USE AN ASSIGNMENT (=). # 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+=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 num in x: + print(num*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..a473c920ae 100644 --- a/src/day-1-toy/modules.py +++ b/src/day-1-toy/modules.py @@ -6,13 +6,14 @@ # See docs for the sys module: https://docs.python.org/3.7/library/sys.html # Print out the command line arguments in sys.argv, one per line: +print(sys.argv[1:]) # Print out the plaform from sys: -print() +print(sys.platform) # Print out the Python version from sys: -print() +print(sys.version) @@ -21,11 +22,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..3026a6cb58 100644 --- a/src/day-1-toy/obj.py +++ b/src/day-1-toy/obj.py @@ -1,21 +1,42 @@ # 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): + super().__init__(lat, lon) + self.name = name + + def __repr__(self): + return f"Waypoint: {self.name}, {self.lat}, {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? +class Geocache(Waypoint): + def __init__(self, name, difficulty, size, lat, lon): + super().__init__(name, lat, lon) + self.difficulty = difficulty + self.size = size + + def __repr__(self): + return f'Geocache: {self.name}, diff {self.difficulty}, size {self.size}, {self.lat}, {self.lon}' + # Make a new waypoint "Catacombs", 41.70505, -121.51521 +cata = Waypoint('Catacombs', 41.70505, -121.51521) # Print it -# +print(cata) # Without changing the following line, how can you make it print into something # more human-readable? -print(w) # Make a new geocache "Newberry Views", diff 1.5, size 2, 44.052137, -121.41556 +geo = Geocache('Newberry Views', 1.5, 2, 44.052137, -121.41556) # Print it--also make this print more nicely -print(g) +print(geo) diff --git a/src/day-1-toy/printf.py b/src/day-1-toy/printf.py index d4bc9abb48..bdf11dd773 100644 --- a/src/day-1-toy/printf.py +++ b/src/day-1-toy/printf.py @@ -5,6 +5,8 @@ # 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(f"x is {x}, y is {y}, z is {z}") -# Use the 'format' string method to print the same thing \ No newline at end of file +# Use the 'format' string method to print the same thing +print("x is {}, y is {}, z is {}".format(x, y, 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..045393ce9a 100644 --- a/src/day-1-toy/scope.py +++ b/src/day-1-toy/scope.py @@ -5,6 +5,7 @@ x = 12 def changeX(): + global x x = 99 changeX() @@ -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..33412ef60c 100644 --- a/src/day-1-toy/slice.py +++ b/src/day-1-toy/slice.py @@ -1,26 +1,26 @@ 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[:5]) # For string s... s = "Hello, world!" # Output just the 8th-12th characters: "world" -print() \ No newline at end of file +print(s[7:]) \ No newline at end of file diff --git a/src/day-1-toy/tuples.py b/src/day-1-toy/tuples.py index ec42b0cdf8..d8775bd05f 100644 --- a/src/day-1-toy/tuples.py +++ b/src/day-1-toy/tuples.py @@ -9,7 +9,7 @@ def dist(a, b): """Compute the distance between two x,y points.""" x0, y0 = a # Destructuring assignment x1, y1 = b - + return math.sqrt((x1 - x0)**2 + (y1 - y0)**2) a = (2, 7) # <-- x,y coordinates stored in tuples @@ -22,11 +22,13 @@ def dist(a, b): # Write a function that prints all the values in a tuple -# def print_tuple(... +def print_tuple(tuple): + for t in tuple: + print(t) t = (1, 2, 5, 7, 99) print_tuple(t) # Prints 1 2 5 7 99, one per line # 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_tuple(u) diff --git a/src/days-2-4-adv/adv.py b/src/days-2-4-adv/adv.py index c9e26b0f85..d7251ac67f 100644 --- a/src/days-2-4-adv/adv.py +++ b/src/days-2-4-adv/adv.py @@ -1,51 +1,65 @@ -from room import Room - -# Declare all the rooms - -room = { - 'outside': Room("Outside Cave Entrance", - "North of you, the cave mount beckons"), - - 'foyer': Room("Foyer", """Dim light filters in from the south. Dusty -passages run north and east."""), +import random +from itertools import cycle, zip_longest - 'overlook': Room("Grand Overlook", """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."""), - - 'narrow': Room("Narrow Passage", """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 -chamber! Sadly, it has already been completely emptied by -earlier adventurers. The only exit is to the south."""), -} +from room import Room +from player import Player +from game import Game +from item import Item, Treasure +from utils import print_green +def start_game(): + rooms = generate_rooms() + name = input('Enter your name: ') + player = Player(name, rooms['outside']) + game = Game(player) + game.run() -# Link rooms together +def generate_rooms(): + rooms = {} + with open('rooms.txt', 'r') as file: + for line in file.readlines(): + name, description = line.split('|') + key = name.split()[0].lower() + rooms[key] = Room(name.rstrip(), description.rstrip()) + generate_map(rooms) + generate_items(rooms) + return rooms -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'] +def generate_map(rooms): + rooms['outside'].n_to = rooms['foyer'] + rooms['foyer'].s_to = rooms['outside'] + rooms['foyer'].n_to = rooms['grand'] + rooms['foyer'].e_to = rooms['narrow'] + rooms['grand'].s_to = rooms['foyer'] + rooms['narrow'].w_to = rooms['foyer'] + rooms['narrow'].n_to = rooms['treasure'] + rooms['treasure'].s_to = rooms['narrow'] -# -# Main -# +def generate_items(rooms): + room_names = list(rooms.keys()) + with open('items.txt', 'r') as file: + items = [ + Item(item.rstrip()) + for item in file.readlines() + ] + with open('treasure.txt', 'r') as file: + for line in file.readlines(): + name, description, value = line.split('|') + treasure = Treasure(name, description, value) + items.append(treasure) + for name in cycle(room_names): + rand = random.randint(0, len(items)) + try: + if items: + rooms[name].items = items.pop(rand) + else: + break + except IndexError: + continue -# Make a new player object that is currently in the 'outside' room. -# Write a loop that: -# -# * Prints the current room name -# * Prints the current description (the textwrap module might be useful here). -# * Waits for user input and decides what to do. -# -# 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 __name__ == "__main__": + try: + start_game() + except KeyboardInterrupt: + print_green("\nGoodbye!!", bold=True) diff --git a/src/days-2-4-adv/game.py b/src/days-2-4-adv/game.py new file mode 100644 index 0000000000..0b542cd99f --- /dev/null +++ b/src/days-2-4-adv/game.py @@ -0,0 +1,71 @@ +from utils import print_blue, print_white, print_green, print_red, print_magenta + +class Game: + def __init__(self, player): + self.player = player + self.attributes = {'n': 'n_to', 'e': 'e_to', 's': 's_to', 'w': 'w_to'} + self.input = None + self.command = None + self.actions = ['take', 'drop', 'score'] + + def run(self): + self._greet() + self._display_status() + self._get_input() + self._loop() + + def _greet(self): + print_white(f'\nWelcome {self.player.name}!', bold=True) + print('Use `take` or `drop` to interact with items') + print('Check inventory with command `i`') + + def _display_status(self): + self._display_current_room() + self._display_items() + + def _display_current_room(self): + print(f"\n{self.player.room}") + + def _display_items(self): + print_green("Items Available", f": {self.player.room.items}\n") + + def _get_input(self): + self.command = None + self.input = input('Enter a command: ').split() + try: + if len(self.input[0]) == 1: + self.input = self.input[0] + else: + self.command, self.input = self.input[0], self.input[1] + except IndexError: + self.command = self.input[0] + self.input = self.command + + def _loop(self): + while self.input.lower() != 'q': + input = self.input.lower() + room = self.player.room + try: + if input == 'i': + print_blue(f"Current Inventory: {self.player.items}", bold=True) + elif self.command in self.actions: + self._use_command(self.command) + elif hasattr(room, self.attributes[input]): + self.player.room = getattr(room, self.attributes[input]) + else: + print_red("Unable to move in that direction!") + except KeyError: + print_magenta('Input was not recognized\n') + finally: + self._display_status() + self._get_input() + + def _use_command(self, command): + func = getattr(self.player, command) + try: + func(self.input.lower()) + except TypeError: + func() + + def __repr__(self): + return f"Game: {self.player}" \ No newline at end of file diff --git a/src/days-2-4-adv/item.py b/src/days-2-4-adv/item.py new file mode 100644 index 0000000000..3c4aa0747c --- /dev/null +++ b/src/days-2-4-adv/item.py @@ -0,0 +1,26 @@ +class Item: + def __init__(self, name): + self.name = name + self.used = False + + def on_take(self): + self.used = True + + def on_drop(self): + pass + + def __repr__(self): + return f'{self.name}' + +class Treasure(Item): + def __init__(self, name, description, value): + super().__init__(name) + self._desc = description + self._value = int(value) + + @property + def value(self): + return self._value + + def __repr__(self): + return f"golden {self.name}" \ No newline at end of file diff --git a/src/days-2-4-adv/items.txt b/src/days-2-4-adv/items.txt new file mode 100644 index 0000000000..daa1d035f7 --- /dev/null +++ b/src/days-2-4-adv/items.txt @@ -0,0 +1,13 @@ +broom +wand +cup +hammer +taco +pot +knife +dirt +kite +rope +candy +wine +egg \ No newline at end of file diff --git a/src/days-2-4-adv/player.py b/src/days-2-4-adv/player.py index d79a175029..305cb12b71 100644 --- a/src/days-2-4-adv/player.py +++ b/src/days-2-4-adv/player.py @@ -1,2 +1,57 @@ # Write a class to hold player information, e.g. what room they are in # currently. +from item import Treasure +from utils import print_cyan, print_red, print_magenta, print_yellow, print_white + +class Player: + def __init__(self, name, room): + self._name = name + self._room = room + self._score = 0 + self._inventory = [] + + def __repr__(self): + return f"Player: {self._name}" + + @property + def name(self): + return self._name + + @property + def room(self): + return self._room + + @room.setter + def room(self, room): + self._room = room + + @property + def items(self): + return self._inventory + + def score(self): + print_white(f"Player Score: {self._score}", bold=True) + + def increment_score(self, item): + self._score += item.value + + def take(self, object): + for item in self.room.items: + if item.name == object: + if isinstance(item, Treasure) and not item.used: + item.on_take() + self.increment_score(item) + self.room.items.remove(item) + self.items.append(item) + print_cyan(f"The {item} was taken from {self.room.name}.") + return + print_red(f"{object} was not found in {self.room.name}") + + def drop(self, object): + for item in self.items: + if item.name == object: + self.items.remove(item) + self.room.items = item + print_magenta(f"The {item} was dropped in the {self.room.name}") + return + print_red(f"{object} was not found in player inventory!") diff --git a/src/days-2-4-adv/room.py b/src/days-2-4-adv/room.py index 24c07ad4c8..b86ff1f9f4 100644 --- a/src/days-2-4-adv/room.py +++ b/src/days-2-4-adv/room.py @@ -1,2 +1,20 @@ # Implement a class to hold room information. This should have name and -# description attributes. \ No newline at end of file +# description attributes. +import crayons + +class Room: + def __init__(self, name, desc): + self.name = name + self.desc = desc + self._items = [] + + @property + def items(self): + return self._items if self._items else None + + @items.setter + def items(self, item): + self._items.append(item) + + def __repr__(self): + return crayons.yellow(self.name, bold=True) + f": {self.desc}" diff --git a/src/days-2-4-adv/rooms.txt b/src/days-2-4-adv/rooms.txt new file mode 100644 index 0000000000..758b814a3d --- /dev/null +++ b/src/days-2-4-adv/rooms.txt @@ -0,0 +1,5 @@ +Outside Cave Entrance|North of you, the cave mount beckons. +Foyer|Dim light filters in from the south. Dusty passages run north and east. +Grand Overlook|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. +Narrow Passage|The narrow passage bends here from west to north. The smell of gold permeates the air. +Treasure Chamber|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. \ No newline at end of file diff --git a/src/days-2-4-adv/treasure.txt b/src/days-2-4-adv/treasure.txt new file mode 100644 index 0000000000..7a17cf728b --- /dev/null +++ b/src/days-2-4-adv/treasure.txt @@ -0,0 +1,3 @@ +crown|a sparkling, golden crown fit for a king|50 +bracelet|a braclet of immense value|30 +ring|a mighty ring of terrible power|100 \ No newline at end of file diff --git a/src/days-2-4-adv/utils.py b/src/days-2-4-adv/utils.py new file mode 100644 index 0000000000..71de990009 --- /dev/null +++ b/src/days-2-4-adv/utils.py @@ -0,0 +1,22 @@ +import crayons + +def print_blue(string, *args, bold=False): + print(crayons.blue(string, bold=bold), *args) + +def print_green(string, *args, bold=False): + print(crayons.green(string, bold=bold), *args) + +def print_red(string, *args, bold=False): + print(crayons.red(string, bold=bold), *args) + +def print_magenta(string, *args, bold=False): + print(crayons.magenta(string, bold=bold), *args) + +def print_white(string, *args, bold=False): + print(crayons.white(string, bold=bold), *args) + +def print_cyan(string, *args, bold=False): + print(crayons.cyan(string, bold=bold), *args) + +def print_yellow(string, *args, bold=False): + print(crayons.yellow(string, bold=bold), *args) diff --git a/src/mini-challenge/hangman.py b/src/mini-challenge/hangman.py index 9b73b9249d..72f47828cd 100644 --- a/src/mini-challenge/hangman.py +++ b/src/mini-challenge/hangman.py @@ -2,72 +2,74 @@ # These could include syntax errors, logical errors, spelling errors... # Find the mistakes and fix the game! # -# STRETCH GOAL: If you fix all the errors, can you find a way to improve +# 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! # 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---", +import random + +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---" ] strikes = 0 -words = [None] -file = open("word.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) ] + +with open('words.txt', 'r') as file: + words = [line for line in file] + +target_word = words[random.randint(0, 80)] +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 draw_body(): 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 +def fill_letters(letter): + global letters_left, cur_word + + for index, char in enumerate(target_word): + if char == letter: + cur_word = cur_word[0: index] + letter + cur_word[index+1: ] + letters_left -=1 # Add spaces when displaying letters / blanks for readability -def printWord( word ): +def print_word(word): prntWord = "" for letter in word: prntWord += letter + " " print(prntWord) # Begin game -print( "Welcome to Hangmn!" ) -printWord(curWord) -drawBody() +print( "Welcome to Hangman!" ) +print_word(cur_word) +draw_body() print("Letters left:") -printWord(alphabet) +print_word(alphabet) # 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 letter in target_word: print("Great!") - fillLetters(letter) + fill_letters(letter) else: strikes += 1 - print( strikes + " / 5 strikes" ) - printWord(curWord) - drawBody() + print( str(strikes) + " / 5 strikes" ) + print_word(cur_word) + draw_body() alphabet.remove(letter.upper()) - print("Letters left:") - printWord(alphabet) + print(f"Letters left: {letters_left}") + print_word(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