![]() |
Exploring Python by Writing my First Text RPG - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: General (https://python-forum.io/forum-1.html) +--- Forum: Code sharing (https://python-forum.io/forum-5.html) +--- Thread: Exploring Python by Writing my First Text RPG (/thread-4266.html) |
Exploring Python by Writing my First Text RPG - Prrz - Aug-04-2017 Hello, Python Forum I am Prrz and this is my first post here in the interesting land of Python developers. I've decided recently to start teaching myself how to code, and naturally, I started with python. In my earlier years, I've dabbled with a ton of C, C++, SQL, PHP, HTML, blah blah. Of course, Python was very enticing to start with on my adventure towards learning to truly code. (In the past, I was very young and butchering other peoples works because I found it extremely interesting, copy and pasting code without ever understanding what was going on in the first place. Simply for fun.) Anyway, I've been writing a simple text based RPG based on a Homework assignment given to me in the book "Learn python the hard way". Here's what I have so far after about two days work, it's very incomplete but I'll post updates as time goes on. Feedback and suggestions are highly appreciated. (Please keep in mind the story is highly a work in progress, I've been more focused on functionality.) # A Game by Prrz in the year 2017 as a self-taught project. from sys import exit # Variables # Must be called using global name = " " gold = 0 player_health = 100 # Weapon Damage damage_base = 0 damage_punch = damage_base + 2 damage_kick = damage_base + 4 damage_bat = damage_base + 8 damage_golfclub = damage_base + 12 damage_knife = damage_base + 15 # Weapons... checks if player has any of them. bat = 0 golfclub = 0 knife = 0 weapons = ['BAT', '9 IRON', 'KNIFE'] # Enemies health_enemy1 = 25 dead_enemy1 = 0 # Items flashlight = 0 downstairs_bathroom_key = 0 # Room instances problem_solved = 0 light_on_downstairs = 0 def check_gold(): global gold print "My Gold = ",gold def check_health(): global health_player print "Current Health = ",health_player def help(): print """ COMMANDS: View (object) (Make sure you use the full name.) North, South, East, West Loot (item) Gold Health Location (Explains where you currently are.) """ print "Examples: View Shelf / Loot Lighter / North or N etc." print "Capitalization of commands doesn't matter.\n" print "Commands are unique to each room, you will be prompted when more become available." def start_room(): print "\n ~~ ENTRANCE ROOM ~~" global light_on_downstairs if light_on_downstairs == 1: print """ The room is much larger than you expected. You can see bookshelves on the southern wall next to the door, hanging chandeliers, a spiral staircase to the North, and doors leading out the East and the West. Despite the home being much plainer than you ever imagined, it makes up for it with spaciousness and perhaps most surprisingly, cleanliness. """ start_prompt() else: print "\nYou find yourself in a large room, it's dark and you can't see anything." print "I should try and find a light switch... Which direction should I go?" print "North, South, East or West." print "Type HELP for more details on commands." start_prompt() def start_prompt(): check_player_health() start_commands = raw_input("\nEntrance Room Command: ").upper() if start_commands == "N" or start_commands == "NORTH": spiral_staircase_up() elif start_commands == "S" or start_commands == "SOUTH": main_door() elif start_commands == "E" or start_commands == "EAST": kitchen() elif start_commands == "W" or start_commands == "WEST": downstairs_bathroom() elif start_commands == "H" or start_commands == "HELP": help() start_prompt() elif start_commands == "G" or start_commands == "GOLD": check_gold() start_prompt() elif start_commands == "HEALTH": check_health() start_prompt() elif start_commands == "VIEW": if light_on_downstairs == 0: print "It's too dark in here to see anything, not much to look at." start_prompt() else: print "Everything is well lit, what a beautiful home..." start_prompt() elif start_commands == "LOCATION": start_room() else: print "I don't think I'm doing this right." start_prompt() def main_door(): check_player_health() global light_on_downstairs if light_on_downstairs == 0: print """ When you examine the door more closely you notice it has no knob or hinges. However you notice a light switch and flick the lights on. """ light_on_downstairs = 1 start_prompt() else: print """ When you examine the door more closely you notice it has no knob or hinges. """ start_prompt() def kitchen(): check_player_health() global light_on_downstairs if light_on_downstairs == 0: print "It's way too dark, no way I'm going anywhere without light." start_prompt() else: kitchen_gateway() def kitchen_gateway(): global name global problem_solved if problem_solved == 0: print "You see a note on the door." print """ Ah, it seems like you've found the light switch %s! Way to go, you're probably wondering who I am and where YOU are by now... you'll find out in due time. At any rate, you'll need to solve this little problem I've given to you! Why? Well frankly it's quite boring in here being all alone...\n """ % name kitchen_problem() else: kitchen_solved() def kitchen_problem(): check_player_health() global problem_solved global player_health print "You're stuck until this is solved!" kitchen = raw_input("Solve: 6 / 2(1 + 2) = ") if kitchen == "9": problem_solved = 1 print "Well done %s, let me open this door for you. " % name print "The door mysteriously starts to open itself." kitchen_solved() elif kitchen == "1": player_health -= 100 kitchen_problem() else: print """ You feel like you've been burned from the inside out. Like someone lit a lighter inside of your stomach. (- 5 hp) """ player_health -= 5 kitchen_problem() def kitchen_solved(): if flashlight == 0: print """ The light creeps through the open doorway just enough for you to see that the kitchen looks impressively well maintained. It has beautiful marble counter-tops, tile floors, and oak cabinets. You don't feel comfortable going much further without a source of light... I really should find a flashlight. """ start_prompt() else: start_prompt() def downstairs_bathroom(): global downstairs_bathroom_key global name if downstairs_bathroom_key == 1: print "You enter the room." else: print """ For whatever reason you decide to knock on the door, from the inside you hear a voice 'Hello again %s, nice to see you mate. I'm a bit busy in here, comeback later.' """ % name print "You notice a keyhole, maybe there's a key somewhere?" start_prompt() def spiral_staircase_up(): check_player_health() global light_on_downstairs if light_on_downstairs == 1: upstairs() else: print """ You knock your shins against something solid and fall flat on your face. Falling down you quickly realize that these are stairs... """ print "It's way too dark, no way I'm going anywhere without light." start_prompt() def upstairs(): check_player_health() global flashlight if flashlight == 0: print """ Unfortunately, the lights are only on downstairs, it's still much too dark to see up here. Maybe I can find something to light the way? """ start_prompt() else: upstairs_prompt() def upstairs_prompt(): print "Blah" def check_player_health(): global player_health if player_health <= 0: dead() else: return def dead(): print "Filler text. You died.\n" restart = raw_input("Try Again? Y / N ").upper() if restart == "Y": start() else: exit(0) def start(): global name print """ ~~ March 23rd, 2171 ~~ The birds are chirping... oh what a beautiful morning. I rub my eyes as sit up in my bed, rubbing the sleepiness out of them with each motion. As my eyes adjust and the room comes into focus I realize immediately that something is wrong with this scene... Why am I outside? Everything around me is DARK, very dark actually. Is it still nighttime? Hmm.. my phone says 8:00AM, the sun should have very well risen by this time. My phone isn't working beyond telling the time, none of its functions are... functional. As I step off my bed it disappears like it was never real in the first place. All that I can see is a door and a small light illuminating the surrounding area. Everything else around me is utterly blank as if something is directing me straight to this door... As I approach the door I find a small note on it, it reads:\n Hello... uhm. What's your name? Just write it on the note, I'll be able to read it.""" name = raw_input("\n My name is: ") print "Great, thanks %s" % name print """The door opens automatically' and you feel drawn to it. \nThis is where it all began.""" start_room() start() RE: Exploring Python by Writing my First Text RPG - sparkz_alot - Aug-04-2017 At this point, since you are just beginning, I would suggest before you go any further that you switch to Python 3.x. If you are using Linux, you probably already have it (though perhaps not the latest version). If you are using Windows, I would go with the latest, 3.6.2. You should be able to convert your current program with the "2to3" module and you would most likely be able to continue using your current book with only some slight modifications, particularly input() and print(). RE: Exploring Python by Writing my First Text RPG - ichabod801 - Aug-05-2017 You have your program organized with an if/elif/else structure. While it's organized some with functions, you are still starting to see problems with repeated code, such as the constant check_player_health. That may not be a big deal, but if you want to grow your map, you are going to have to start repeating movement code all over the place. I would suggest putting as much of the game structure (the map, things in rooms, and so on) into a data structure like a dictionary. Then you can limit your code a lot more, and thereby limit your bugs a lot more. I you click the text adventures link in my signature below, it will take you to a tutorial to do exactly that. It may take a bit of work to convert what you have into the new structure, but if you are going to expand this game at all it will save you time in the long run. RE: Exploring Python by Writing my First Text RPG - Prrz - Aug-16-2017 (Aug-04-2017, 02:31 PM)sparkz_alot Wrote: At this point, since you are just beginning, I would suggest before you go any further that you switch to Python 3.x. If you are using Linux, you probably already have it (though perhaps not the latest version). If you are using Windows, I would go with the latest, 3.6.2. You should be able to convert your current program with the "2to3" module and you would most likely be able to continue using your current book with only some slight modifications, particularly input() and print(). Thanks for your reply sparkz_alot, it is much appreciated. As for the moment, I will be sticking to Python 2 because this book that I am working through explicitly states several times to stick with Python 2 for the time being and potentially move onto learning Python 3 in the future. The reasoning it gives is "When all the Python code on your computer is Python 3, then I’ll try to learn it.". Although the advice is much appreciated, and it is noted and will be taken into consideration with each step forward. Regards, Prrz (Aug-05-2017, 10:38 PM)ichabod801 Wrote: You have your program organized with an if/elif/else structure. While it's organized some with functions, you are still starting to see problems with repeated code, such as the constant check_player_health. That may not be a big deal, but if you want to grow your map, you are going to have to start repeating movement code all over the place. I would suggest putting as much of the game structure (the map, things in rooms, and so on) into a data structure like a dictionary. Then you can limit your code a lot more, and thereby limit your bugs a lot more. Hello ichabod801 thank you very much for your reply. I agree completely with what you have said, I've foreseen the repetitive code as well and re-structuring the game would be highly beneficial. (Running into coding bugs has started to become an issue the more it grows) I've opened up the link you've mentioned and am taking a look at it now, I think not only will it make the program more functional but also more enjoyable to code in the long run. Again thank you very much! Prrz RE: Exploring Python by Writing my First Text RPG - sparkz_alot - Aug-16-2017 (Aug-16-2017, 05:39 PM)Prrz Wrote: The reasoning it gives is "When all the Python code on your computer is Python 3, then I’ll try to learn it.". My guess is the book you are using is not that recent, perhaps when Python 3 was first introduced. The reasoning was that many of the 3rd party library's had not yet converted from v2 to v3. In my opinion, that was and still is, bad advice for new users, as new users are more apt to use the builtins than third party mod's. Now, most library's have made the transition fro v2 to v3 or are simply being created as v3 so the argument no longer has any merit. Though I can't force you to use v3, I still strongly urge you to do so. Btw, the book you are using wouldn't happen to be "Learning Python The Hard Way" would it? RE: Exploring Python by Writing my First Text RPG - Prrz - Aug-17-2017 (Aug-16-2017, 07:30 PM)sparkz_alot Wrote:(Aug-16-2017, 05:39 PM)Prrz Wrote: The reasoning it gives is "When all the Python code on your computer is Python 3, then I’ll try to learn it.". Thanks again for the reply sparkz_alot. You've raised some solid points, my plan is to move my current game project over to the "While True" loop format using a dictionary for reference, and when that has been completed I will convert everything I've got so far into Python 3 and then move forward from there. I believe that will minimize the work load so that I'll have my entire game so far in the format that Ichabod has recommended for me, before converting it all into Python 3. And yes indubitably "Learning Python The Hard Way" is the book I'm using! As a quick update, this is what has been done so far as per Ichabods advice (I used some of the code in your forum post as a solid guideline, it makes a lot of sense so thank you for that!) from sys import exit # Key: {KeyName,} {Name, North, South, East, West, Contents, Text, enemiess, # enemy_health, enemy_damage, enemy_gold} rooms = {'entrance': {'name': 'Entrance', 'north': 'stairs', 'south': 'door', 'east': 'kitchen', 'west': 'bathroom', 'contents': [], 'text': """ You find yourself in a large room, it's dark and you can't see anything. I should try and find a light switch... Which direction should I go? North, South, East or West.""", 'enemies': [], 'enemy_health': [], 'enemy_gold': []}, 'kitchen': {'name': 'Kitchen', 'north': 'window_sill', 'south': 'entrance', 'east': 'pantry', 'west': 'appliances', 'contents': ['flashlight'], 'text': """Kitchen""", 'enemies': 'goblin', 'enemy_health': 5, 'enemy_damage': 5.5, 'enemy_gold': 15}} directions = ['north', 'south', 'east', 'west'] current_room = rooms['entrance'] carrying = [] player_health = 100.00 player_gold = 0 player_name = " " damage_base = 1.25 damage_punch = damage_base * 2.0 damage_kick = damage_base * 3.0 damage_bat = damage_base * 8.0 damage_golfclub = damage_base * 12.0 damage_knife = damage_base * 15.0 def game_loop(): while True: # Global attributes... figure out how to move that to a seperate file? global current_room, player_health, player_gold, carrying, name # Check if you have died yet, hopefully not... if player_health <= 0: you_dead() # Check if enemies are in room or not... enemy = current_room['enemies'] if enemy in current_room['enemies'] and current_room['enemy_health'] > 0: fight_loop() # Display Current Location print "You're in the: %s" % (current_room['name']) print current_room['text'] # Display Items in Current_Room if current_room['contents']: print "You find: %s" % (' '.join(current_room['contents'])) # User Input command = raw_input("What to do? ").lower() # N/S/E/W if command in directions: if command in current_room: current_room = rooms[current_room[command]] else: # bad movement print "You can't go that way." # quit the game elif command in ('q', 'quit'): exit(0) # print your health elif command in ('health', 'h'): print "Current Health: %r" % player_health # print your gold elif command in ('gold', 'g'): print "Current Gold: %r" % player_gold # test dead feature elif command in ('die'): player_health -= 100.00 # gather objects elif command.split()[0] == 'get': item = command.split()[1] if item in current_room['contents']: current_room['contents'].remove(item) carrying.append(item) else: print "I don't see that here." # get rid of objects elif command.split()[0] == 'drop': item = command.split()[1] if item in carrying: current_room['contents'].append(item) carrying.remove(item) else: print "You aren't carrying that." # command error else: print """ Invalid Command %s Try Again """ % player_name def fight_loop(): global player_health, player_gold, dead_enemies, damage_base, damage_kick, \ damage_punch, current_room if current_room['enemy_health'] > 0: enemy_fight = raw_input("KICK, PUNCH, or RUN?: ").lower() elif current_room['enemy_health'] <= 0: game_loop() else: game_loop() if enemy_fight == "kick": print """ You kick the foe for %s damage and take 7.5 damage in return! """ % damage_kick current_room['enemy_health'] -= damage_kick player_health -= current_room['enemy_damage'] print """ Enemy's Health: %s """ % current_room['enemy_health'] fight_loop() elif enemy_fight == "punch": print """ You punch the foe for %s damage and take 7.5 damage in return! """ % damage_punch current_room['enemy_health'] -= damage_punch player_health -= current_room['enemy_damage'] print """ Enemy's Health: %s """ % current_room['enemy_health'] fight_loop() elif enemy_fight == "run": print """ You run away like a coward, the %s hits you for 15 damage! I guess he ran away too... or more or less vanished. Problem solved! """ player_health -= 15 current_room['enemy_health'] -= current_room['enemy_health'] fight_loop() else: print """ Invalid entry did you terribly mispell something? """ fight_loop() def you_dead(): global player_health print "You died!" tryAgain = raw_input("Try Again? Yes / No: ").upper() if tryAgain == "NO" or tryAgain == "N": print "GOODBYE!" exit(0) elif tryAgain == "YES" or tryAgain == "Y": player_health = 100.00 game_loop() else: print "This is infact a 'YES or NO' question." you_dead() def start_game(): global player_name print """ ~~ March 23rd ~~ The birds are chirping... oh what a beautiful morning. I blink my eyes as I sit up in my bed, rubbing the sleepiness out of them with each motion. As my eyes adjust and the room comes into focus I immediately realize that something is wrong with this scene... Why am I outside? Everything around me is DARK, very dark actually. Is it still nighttime? Hmm.. my phone says 8:00AM, the sun should have very well risen by this time. My phone isn't working beyond telling the time, none of its functions are... functional. As I step off my bed it disappears like it was never real in the first place. All that I can see is a door and a small light illuminating the surrounding area. Everything else around me is utterly blank as if something is directing me straight to this door... As I approach the door I find a small note on it, it reads:\n Hello... uhm. What's your name? Just write it on the note, I'll be able to read it.""" player_name = raw_input("\n What's Your Name?: ").upper() print """ Great thanks, %s 'The door opens automatically' and you feel drawn to it. This is where it all began. """ % player_name game_loop() start_game()Regards, Prrz RE: Exploring Python by Writing my First Text RPG - Kebap - Aug-18-2017 Hi Prrz, welcome to Python! You can replace system.exit(0) with simply return At the end of fight_loop and you_dead functions, you call the same function again. There is a limit to how often you can do that (it is called recursion), so a better way would be to simple use a real loop like the name suggests and you do in game_loop function already. Keep up the text-based role-play-gaming! ![]() |