[Tutor] python game error

Peter Otten __peter__ at web.de
Sat Oct 13 10:08:14 EDT 2018

Mariam Haji wrote:

> Hi guys,
> I am still on the learn python the hard way.
> I built the below on python 2.7 and my OS is windows 7.
> I am getting this error:
> Traceback (most recent call last):
>   File "ex43.py", line 205, in <module>
>     a_game.play()
>   File "ex43.py", line 21, in play
>     next_scene_name = current_scene.enter()
> AttributeError: 'NoneType' object has no attribute 'enter'

The value of current_scene is None here. If you dig a bit in your code 
looking for places where that can happen you end up with

> class Map(object):
>     scenes = {
>     'central_corridor': CentralCorridor(),
>     'laser_weapon_armory': LaserWeaponArmory(),
>     'the_bridge': TheBridge(),
>     'escape_pod': EscapePod(),
>     'death': Death()
>     }
>     def __init__(self, start_scene):
>         self.start_scene = start_scene
>     def next_scene(self, scene_name):
>         return Map.scenes.get(scene_name)

Map.scenes is a dict, and its get() method returns None when the lookup for 
a key fails. If you pass an unknown scene name to the next_scene() method it 
returns None rather than a Scene instance.

As a first step to fix this I recommend that you use the item lookup 
operator instead of the method:

      def next_scene(self, scene_name):
          return Map.scenes[scene_name]

This will fail immediately, and the error message should be more 
informative. I got:

Traceback (most recent call last):
  File "./game_mariam.py", line 181, in <module>
  File "./game_mariam.py", line 20, in play
    current_scene = self.scene_map.next_scene(next_scene_name)
  File "./game_mariam.py", line 173, in next_scene
    return Map.scenes[scene_name]
KeyError: 'laser_weapon_armoury'

That is, you need to decide if you want British or American orthography.

More information about the Tutor mailing list