[Tutor] python game error

bob gailer bgailer at gmail.com
Sun Oct 14 19:04:28 EDT 2018

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 "<interactive input>", line 1, in <module>
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

<entry> CentralCorridor, The Gothons of Planet Percal #25 have invaded 
..., Do you shoot!, dodge!, or tell a joke?
<action> CentralCorridor, shoot!, Quick on the draw you yank out your 
...., Death
<action> CentralCorridor, dodge!, Like a world class boxer you dodge 
...., Death
<action> 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,))
         action = input(prompt + '>') # tell a joke!
         text, next_scene = sel("text, next_scene", "scene_action where 
scene = ? and action= ?", (next_scene, action))

conn = sq.connect("c:/games/game.db")
------ end program ------

More information about the Tutor mailing list