0

So I'm trying to learn making games with python using the pygame module and coming from a javascript background I want to be able to build a program using multiple scripts. So I try to load another script and use one of its functions as well as variables declared in that script. What I want to be able to do is call the 'update' funciton from the other script but use the variables declared in this one. Any suggestions?

Edit: Ok, so I clearly haven't clarified my question very well. Importing the script is not my problem, I can get it to import fine. The trouble I have is that after I import it I need to be able to call a function from this script from the main script that uses variables from this script.

What happens right now is that I call the update function in this script an it gives me an error that says that the variable 'animTimer' is being called before it is declared. That's what I need to fix.

import pygame, sys, time, random
from pygame.locals import *

# Create animation class
class animation2D:
    "a class for creating animations"
    frames = []
    speed = 3
    cFrame = 0

player = pygame.Rect(300, 100, 40, 40)
playerImg1 = pygame.image.load('player1.png')
playerImgS = pygame.transform.scale(playerImg1, (40,40))
playerImg2 = pygame.image.load('player2.png')
playerImg3 = pygame.image.load('player3.png')
playerImg4 = pygame.image.load('player4.png')
playerImg5 = pygame.image.load('player5.png')
playerImg6 = pygame.image.load('player6.png')
playerAnim = animation2D
playerAnim.frames = [playerImg1, playerImg2, playerImg3, playerImg4, playerImg5, playerImg6]
animTimer = 0
print(animTimer)

def Update():
     # Draw Player
    if animTimer < playerAnim.speed:
        animTimer += 1
    else:
        animTimer = 0
        playerImgS = pygame.transform.scale((playerAnim.frames[playerAnim.cFrame]), (40,40))
        if playerAnim.cFrame < len(playerAnim.frames)-1:
            playerAnim.cFrame += 1
        else:
            playerAnim.cFrame = 0

    windowSurface.blit(playerImgS, player)

import pygame, sys, time, random
from pygame.locals import *
import animationScript

# Set up pygame
pygame.init()
mainClock = pygame.time.Clock()

# Set up window
screenW = 400
screenH = 400
windowSurface = pygame.display.set_mode((screenW, screenH), 0, 32)
pygame.display.set_caption('Sprites and sound')


# Set up the colors
black = (0,0,200)

# Set up music
pygame.mixer.music.load('testmidi.mid')
#pygame.mixer.music.play(-1,0.0)





# Run the game loop
while True:
    # Check for the QUIT event
    for event in pygame.event.get():
        if event.type == QUIT:
                pygame.quit()
                sys.exit()
        if event.type == KEYUP:
            if event.key == K_ESCAPE:
                pygame.quit()
                sys.exit()

    # Draw the background onto the surface
    windowSurface.fill(black)

    # Draw Player
    animationScript.Update()



    # Draw the window onto the screen
    pygame.display.update()
    mainClock.tick(40)
1
  • 1
    This is just importing. Try import myotherscript and myotherscript.function(something) etc. Commented Sep 9, 2013 at 19:01

2 Answers 2

2

EDIT: It looks to me as though you're trying to do something like this:

>>> a = 4
>>> def inca():
...     a += 1
... 
>>> inca()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in inca
UnboundLocalError: local variable 'a' referenced before assignment

when you should be passing in parameters, like this:

>>> def inc(n):
...     return n + 1
... 
>>> a = 4
>>> a = inc(a)
>>> a
5

Python doesn't like to clutter up the global namespace. This is a good thing, I promise! Make sure you assign the variable to the result of the function, as I did on the line a = inc(a). Otherwise, you would have to muck around with global variables, which isn't very good practice.

In your case, Update() should take the parameters it wishes to modify, and return their new values.


You can import this module into the other script. This will allow you to access all module-level functions, variables, etc, using the syntax

mymodulename.functionname()

or

mymodulename.varname.

If you want to access something within a class within a module, the same syntax still works!

mymodulename.classname.classmember

For example:

####file_a.py####
import file_b
print file_b.message
c = file_b.myclass()
c.helloworld()


####file_b.py####
message = "This is from file b"
class myclass:
    def helloworld(self):
        print "hello, world!"
#################

$ python file_a.py
This is from file b
hello, world!

If your modules aren't in the same directory, you will need to add the directory from which you would like to import to your path. However, I would recommend leaving them in the same directory for now, as you seem to be learning Python.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! I should be able to figure it out based on this.
0

You can use import, but will need to either add the path to your script to your PYTHONPATH environment variable or a line of code before the import as follows:

sys.path.insert(0, path_to_your_script_here)

You can then either import the whole module using:

import module name

and reference the functions with module.function() or you can import specific functions, tehn ou just call the function name directly:

from module import function

4 Comments

Note that you need to import sys before calling sys functions. (A little meta, I guess.) Also, if both files are in the same directory, you don't need to modify your PYTHONPATH.
No, it imports fine, the trouble I have is that when I call the event 'Update' I am unable to use variables from that script, however for the program to work I need to be able to do that.
@user2762463 i see. If your update script returns multiple values, you can just list more than one variable to assign these to e.g. a, b, c = update(input_params).
@user2762463 just looked at your code for update. You need to add a line to the bottom of this to return the values that you want to pass into variables when you call it. you can just list any variables you want to return (separated by commas) after the return key word.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.