Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Name 'Actor' is not defined

Tags:

python

pgzero

I have a problem with python programming, when I'm trying to write a game (introduced by the book: Coding Games Python DK 3), it says: name 'Actor' is not defined.

here's my code:

import pgzrun

from random import randint

WIDTH = 400
HEIGHT = 400

dots = []
lines = []

next_dot = 0

for dot in range(0, 10):
    actor = Actor("dot")
    actor.pos = randint(20, WIDTH -20), randint (20, HEIGHT - 20)
    dots.append(actor)

def draw():
    screen.fill("black")
    number = 1
    for dot in dots:
        screen.draw.text(str(number), (dot.pos[0], dot.pos[1] + 12))
    dot.draw()
    number = number + 1

for line in lines:
    screen.draw.line(line[0], line[1], (100, 0, 0))

pgzrun.go()
like image 499
mhm Avatar asked Mar 04 '23 06:03

mhm


2 Answers

You are using the Python library pgzero (indirectly via importing pgzrun).

I had refactored my game code into multiple files (imported into the main file) and did also observe the same strange

NameError: name 'Actor' is not defined

error message.

The Actor class seems to be "private", but can be imported with this simple code line:

from pgzero.builtins import Actor, animate, keyboard

For background see:

https://github.com/lordmauve/pgzero/issues/61

Update Aug 18, 2019: The screen object cannot be imported since it is created as global variable during runtime (object = instance of the Screen class) and IDE-supported code completion is not possible then. See the source code: https://github.com/lordmauve/pgzero/blob/master/pgzero/game.py (esp. the def reinit_screen part)

like image 121
R Yoda Avatar answered Mar 16 '23 12:03

R Yoda


This page on the Pygame site will help you run it from your IDE: https://pygame-zero.readthedocs.io/en/stable/ide-mode.html

Essentially, you have to have these two lines of code:

import pgzrun
...
...
pgzrun.go()

But during coding, the IDE will still complain that objects and functions like screen and Actor are undefined. Pretty annoying. As far as I know, there's no way to fix it, you just have to ignore the complaints and hit Debug > Run. Provided you have no mistakes, the program will compile and run.

With regards to

import pgzrun
actor = pgzrun.Actor("dot")

Or

from pgzrun import *
dot=Actor("dot")

Neither of these help integrated development environments like Spyder or Visual Studio recognise objects and functions like screen and Actor

pgzrun doesn't seem to behave like a normal python library. Pygame relies on using pgzrun to run your python script from the command line:

pgzrun mygame.py
like image 27
Lindsay Fowler Avatar answered Mar 16 '23 11:03

Lindsay Fowler