0

I'm remaking a game in python and the menu file and the game file are separate. The menu imports the game file as a module and calls it when requested. However I want variables that determine the sound and difficulty to be passed through from the menu file to the game file, as these options are chosen by the user in the menu.

I'm not sure how to do this at all, so here is how i import and call the python game file:

import SpaceInvaders
SpaceInvaders.SpaceInvaders().mainLoop()

and I want to pass the arguments 'sound' and 'difficulty' through, whose values are strings.

also i call the main loop function but the variables need to be usable in the SpaceInvaders class so i can assign them to self.sound and self.difficulty, they aren't used in the main loop.

AntsOfTheSky
  • 195
  • 2
  • 3
  • 17

2 Answers2

1

If you want to pass sound and difficulty to the mainLoop of SpaceInvaders, then make it so that mainLoop takes them as arguments, and then you will be able to send them:

SpaceInvaders.SpaceInvaders().mainLoop(sound, difficulty)

To answer the additional question "That's the issue, I don't want them in main loop, I want them in the SpaceInvaders class :(" - do this:

SpaceInvaders.SpaceInvaders(sound, difficulty).mainLoop()
zvone
  • 18,045
  • 3
  • 49
  • 77
0

example usage:

python somegame.py hello args --difficulty medium

how to use sys.argv create an example:

echo 'import sys;print(sys.argv)' >> test.py
python test.py okay okay --diff med

output:

['1.py', 'okay', 'okay', '--diff', 'med']

very basic example using sys.argv:

import sys
import SpaceInvaders

print(sys.argv)
# step through using pdb
# see: https://docs.python.org/3/library/pdb.html
import pdb;pdb.set_trace() #print(dir(), dir(SpaceInvaders))
# 'n' enter, 'n' enter
# set self.stuff

# create the class
invade = SpaceInvaders.SpaceInvaders(sys.argv)

# pass argv to mainLoop
invade.mainLoop(sys.argv)

and in SpaceInvaders.py:

class SpaceInvaders(object):
    def __init__(self, args):
        print(args)
        self.difficulty = # some var from args
        import pdb;pdb.set_trace()

    def mainLoop(self, args):
        print(args)

if you want to get really fancy checkout:

jmunsch
  • 22,771
  • 11
  • 93
  • 114
  • Unfortunately I don't understand this at all and wouldn't be able to implement it. Do you think you could explain this a little please? Thanks for the help! – AntsOfTheSky Sep 01 '18 at 12:12
  • @AntsOfTheSky updated. also see: https://stackoverflow.com/questions/10004850/python-classes-and-oop-basics and https://stackoverflow.com/questions/7803493/how-do-python-modules-work – jmunsch Sep 01 '18 at 12:24