0

I'm trying to get a little bit better organized in my programming, so I've decided to use multiple python files to organize my game. For some reason, I cannot use functions from another script. My main script in which I run the game is called main.py and the script I'm trying to use functions from is gamemap.py . Here is the code which I use to do this

import pygame,sys,time
import gamemap as g

pygame.init()
pygame.mixer.init()
screen = pygame.display.set_mode((800,600))
#Pictures


enemy = pygame.image.load("enemy_reg.png")
player = pygame.image.load("player_reg.png")
player_shot = pygame.image.load("playershot.png")
enemy_shot = pygame.image.load("shot.png")
g.loadmapstuff()
9
  • 1
    What's the error you got? Commented Jul 4, 2016 at 4:52
  • Did you try 'sudo touch _init_.py' or if on windows create new file _init_.py in the directory your files are located? Commented Jul 4, 2016 at 4:55
  • If you want to import a module, then you need name your file __init__.py, and put it under a folder with the name of your module. Then, from another file which is located next to that folder, you can import that module using import followed by the name of the folder. Commented Jul 4, 2016 at 4:55
  • The error is : Traceback (most recent call last): File "C:\Users\ihiouh\Desktop\game\main.py", line 2, in <module> import gamemap as g File "C:\Users\ihiouh\Desktop\game\gamemap.py", line 1, in <module> from main import * File "C:\Users\ihiouh\Desktop\game\main.py", line 20, in <module> g.loadmapstuff() AttributeError: 'module' object has no attribute 'loadmapstuff' [Finished in 0.8s] Commented Jul 4, 2016 at 4:57
  • Create file "C:\Users\ihiouh\Desktop\game\__init__.py" Commented Jul 4, 2016 at 5:00

2 Answers 2

1

When you create your own module (in your case gamemap.py) you must create and empty file call __init__.py inside the folder that contains your module.

With this file (__init__.py) python understood that this folder is a package, and then you can import the modules that are inside of it.

I recommend you read the official docs about this matter -> Modules and Packages

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

Comments

0

Please check whether the two file are in the same directory.

You can also use

from gamemap import loadmapstuff

loadmapstuff()

Comments

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.