Re: [Tutor] python game error
On 10/13/2018 4:25 AM, Mariam Haji wrote: ... Your problem intrigued me enough to spend some time "fixing" your program so it will compile with no errors and run at least the initial case where I entered "shoot!" Here are the problems I found: (line numbers refer to your original code) - spelling error return 'laser_weapon_armoury' - fixed - line 122 there is no if preceding the elif - I added one - line 160 returns 'finished'. There is no corresponding entry in Map.scenes - I added one and a corresponding class Finished. - the logic for allowing 10 guesses of the code is flawed. It only allows 2 guesses. I will leave it up to you to figure out why. In addition I - used """ for all multi line prints; a personal preference - it makes entry and reading easier. - updated code so it will run under python 3. This involves: - changing print statements to print function calls - assigning input to raw_input for version 3 - added raise to Map.next_scene to handle undefined scenes Try it out. > how do I create a keyword to exit the game mid way? You don't create keywords. To support mid-game exiting I added an abort method to Finished. Use: Finished.abort('reason') -- program -- from sys import exit, version from random import randint if versison[0] == '3': raw_input = input class Scene(object): def enter(self): print("This scene is not yet configured. Subclass it and implement enter().") exit(1) class Engine(object): def __init__(self, scene_map): self.scene_map = scene_map def play(self): current_scene = self.scene_map.opening_scene() while True: print("\n") next_scene_name = current_scene.enter() current_scene = self.scene_map.next_scene(next_scene_name) class Death(Scene): quips = [ "You died. You Kinda suck at this.", "Your mum would be proud if she were smarter.", "Such a looser.", "I have a small puppy that's better at this." ] def enter(self): print(Death.quips[randint(0, len(self.quips)-1)]) exit(1) class CentralCorridor(Scene): def enter(self): print("""The Gothons of Planet Percal #25 have invaded your ship and destroyed Your entire crew, you are the only surviving memeber and your last Mission is to get the neutron destruct a bomb from the weapons Armory Put it in the bridge and blow the ship up after getting into an escape pod You're running down the central corridor to the Weapons Armory when a Gothon jumps out, red scaly skin, dark grimy teeth, and evil clow costume flowing around his hate filled body. He's blocking the door to the Armoury and about to pull a weapon to blast you. Do you shoot!, dodge!, or tell a joke? enter below.""") action = raw_input("> ") if action == "shoot!": print("""Quick on the draw you yank out your blaster and fire it at the Gothon. His clown costume is flowing and moving around his body, which throws off your aim. Your laser hits his costume but misses him entirely. This completely ruins his brand new costume his mother bought him, which makes him fly into a rage and blast ou repeatedly in the face until you are dead. Then he eats you""") return 'death' elif action == "dodge!": print("""Like a world class boxer you dodge, weave, slip and slide right as the Gothon's blaster cranks a laser past your head In the middle of your artful dodge your foot slips and you bang your head on the metal wall and you pass out You wake up shortly after, only to die as the Gothon stomps on your head and eats you""") return 'death' elif action == "tell a joke": print("""Lucky for you they made you learn Gothon insults in the academy you tell the one Gothon joke you know Lbhe zbgure vf fb sng, jura fur fvgf nebhaq gur ubhfr, fur fvgf nebhaq gur ubhfr. The Gothon stops, tries not to laugh, he busts out laughing and can't move. While he is laughing you run up and shoot him square in the head putting him down, then jump through the Weapon Armory door.""") return 'laser_weapon_armory' else: print("DOES NOT COMPUTE!") return 'central_corridor' class LaserWeaponArmory(Scene): def enter(self): print("""You do a drive roll into the weapon Armory, crouch and scan the room for more Gothons that might be hiding. It's dead quiet, too quiet You stand up and run to the far side of the room and find the neutron bomb in it's container. There's a keypad lock on the box Wrong 10 times then the lock closes forever and you can't get the bomb. The code is 3 digits""") code = "%d%d%d" % (randint(1,9), randint(1,9), randint(1,9)) guess = raw_input("[keypad]> ") guesses = 0 while guess != code and guesses < 10: print("BZZZEE!") guesses += 1 guess = raw_input("[keypad]> ") if guess == code
Re: [Tutor] python game error
More comments: User Friendly? I hope this game is not intended for actual use. No one will be able to guess the correct actions in a reasonable time. or 3 digit random code given 10 tries for any one code. I for one would give up pretty quickly. The original colossal cave game is an excellent example of a user-friendly text adventure game. If you are using a Windows computer you can get a version from the Microsoft Store It - gives explicit directions - keeps responses to a few words most chosen from a limited list or names of visible objects. Python coding "trick"1 when I build a map I omit the () after the class e.g. 'death' = Death, ... and apply them to the item retrieved from the map. use a decorator to build the map dictionary: # the decorator function: def add_to_map(cls, map={}): # map is initialized to a {} when function is "compiled" if cls: map[cls.__name__] = cls # add entry to dictionary return cls else: return map # apply decorator to class definitions # this will add 'Death': @add_to_map class Death(Scene): class_definition # ditto for all other classes based on Scene - then class Map: scenes = add_to_map() # note when map is called with no arguments it returns the dictionary Python coding "trick" 2 instead of: print(Death.quips[randint(0, len(self.quips)-1)]) try: print(random.choice(Death.quips) Python coding "trick" 3 action = raw_input('>').title() # to make user input agree with class names Python coding "trick" 4 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] python game error
On 10/14/2018 10:08 AM, bob gailer wrote: > Python coding "trick"1 > when I build a map I omit the () after the class e.g. 'death' = Death, > ... and apply them to the item retrieved from the map. > > use a decorator to build the map dictionary: > > # the decorator function: > def add_to_map(cls, map={}): # map is initialized to a {} when function > is "compiled" > if cls: > map[cls.__name__] = cls # add entry to dictionary > return cls > else: return map Hint here: don't use 'map' as your own variable name, since it's a built-in function. It's not that it won't work, but is likely to cause confusion someday. Most "code inspection" systems will complain that you are shadowing or redefining a builtin (terminology may vary). The list of builtins - thus names to avoid - is here: https://docs.python.org/3/library/functions.html ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Statistics with python
I'm replying back to the tutor list. Can you reply there rather than directly to me please? Also I've moved your response below mine as that is the preferred style on this list. My answer is below. On Sun, 14 Oct 2018 at 16:05, Mariam Haji wrote: > > On Sat, Oct 13, 2018 at 10:24 PM Oscar Benjamin > wrote: >> >> On Sat, 13 Oct 2018 at 11:23, Mariam Haji wrote: >> > >> > Hi guys, >> >> Hi Mariam >> >> > the question is as: >> > If a sample of 50 patients is taken from a dataset what is the probability >> > that we will get a patient above the age of 56? >> >> I can think of several ways of interpreting this: >> >> (a): You have a dataset consisting of 50 patients. You want to know >> the probability that a patient chosen from that sample will be above >> the age of 56. >> >> (b): You have a dataset consisting of 50 patients. You consider it to >> be representative of a larger population of people. You would like to >> use your dataset to estimate the probability that a patient chosen >> from the larger population will be above the age of 56. >> >> (c): You have a larger dataset consisting of more than 50 patients. >> You want to know that probability that a sample of 50 patients chosen >> from the larger dataset will contain at least (or exactly?) one person >> above the age of 56. >> >> (d): You have a larger dataset, but you will only analyse a sample of >> 50 patients from it. You want to use statistics on that sample to >> estimate the probability that a patient chosen from the larger dataset >> will be above the age of 56. >> >> I can list more interpretations but I think it would be better to wait >> for you to clarify. > > My dataset consists of 300+ patients and I want to analyze analyse a sample > of 50 patients from it. > Yto know the probability that a patient chosen from the larger dataset > will be above the age of 56. Is this a homework problem or an actual problem? If I had 300+ patients I would think that the best way to work out the probability that a patient chosen from those 300+ was over the age of 56 would be to count how many are over the age of 56. Likewise if I wanted to estimate how many would be over the age of 56 using a smaller sample of 50 patients then I would also just count how many are over the age of 56 in that smaller sample. I'm going to guess that this is a homework problem and that you have been asked to assume that the ages are normally distributed (which they would not be in reality). Your calculation for the standard deviation given in your earlier email doesn't make any sense. You should calculate this using a function that calculates the standard deviation. There is one in the numpy module: >>> import numpy >>> ages = [35, 45, 55, 70] >>> numpy.mean(ages) 51.25 >>> numpy.std(ages) 12.93010054098575 -- Oscar ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] python game error
On 10/14/2018 1:42 PM, Mats Wichmann wrote: Hint here: don't use 'map' as your own variable name, since it's a built-in function. Absolutely, I am always warning others about this gotcha. In this case map is local to add_to_map so it does not affect then global namespace. The reason I used it here was because the OP was using map (actually Map). Duh! Bob ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] python game error
More comments on code: guess = raw_input("[pod #]> ") if int(guess) != good_pod: If user enters something that will not convert to integer an exception will be raised. For example >>> int('a') Traceback (most recent call last): File "", line 1, in ValueError: invalid literal for int() with base 10: 'a' Either use try - except - or good_pod = str(randint(1,5)) guess = raw_input("[pod #]> ") if guess != good_pod: - or if you import choice from random good_pod = choice('12345') Migrating to a database (separating data from logic). Why? - it keeps the code simple. - makes adding / editing scenes easier. Given a database (game.db) with 2 tables: table columns scene_entry scene, text, prompt scene_action scene, action, text, next_scene Example: CentralCorridor, The Gothons of Planet Percal #25 have invaded ..., Do you shoot!, dodge!, or tell a joke? CentralCorridor, shoot!, Quick on the draw you yank out your , Death CentralCorridor, dodge!, Like a world class boxer you dodge , Death CentralCorridor, tell a joke!, Lucky for you they made you,, Laser_weapon_armory The generic structure of a game program: next_scene = 'CentralCorridor' while next_scene != 'Finished': get text, prompt from scene_entry print entry text prompt user for action get text, next_scene from scene_action print text A simple python game program utilizing the game database follows. You would first create c:/games/game.db using a tool like SQLite Studio, or request a copy from me. It is up to you to fill in the rest of the various table rows. What's missing? Code to handle the code and good_pod guesses. That will come later. -- program -- import sqlite3 as sq def sel(cols, rest, vals=(,)): # construct, execute a sql select statement from the arguments # get and return one row (there should be at most one) sql = "select " + cols + " from " + rest + ";" curs = conn.execute(sql, vals) x = curs.fetchone() if x: return x raise ValueError(sql, vals) def game(next_scene): while next_scene != 'finished': text, prompt = sel("text, prompt", "scene_entry where scene = ?", (next_scene,)) print(text) action = input(prompt + '>') # tell a joke! text, next_scene = sel("text, next_scene", "scene_action where scene = ? and action= ?", (next_scene, action)) print(text) conn = sq.connect("c:/games/game.db") game('CentralCorridor') -- end program -- ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor