Hi everyone
I have been given a python code to add some functionality in it. The problem am facing is that the original developer has hard coded 3 variables a,b,c in the code and these variables are before class definition in files: hers is the code snippet:

a = 9
b = 9
c = 8  #define the position of the falling objects

class fallObj(DirectObject):
    def __init__(self):
#rest of the code goes here

I want the user to input these rather than hard coding them. Please help me.

Thanks

Recommended Answers

All 3 Replies

Simply replace the numbers with raw_input(). Add a string between the parenthesis to also print a prompt.

a = raw_input("A = ")
b = raw_input("B = ")
c = raw_input("C = ")

class fallObj(DirectObject):
    def __init__(self):
#rest of the code goes here

yeah thats what I did but the problem is that these variables are used in two files and in every file its hard coded, so I need help to try and find a way in which these variables can be entered in one file but are available for use in the second file also, am attaching the code please help me with this, the variables I want the user to enter are Maxrocks, Maxstars and LIMIITS.

File 1:


#main file for the game
#all the functions are called in this file

from pandac.PandaModules import loadPrcFileData
loadPrcFileData('', 'win-size 1024 768') # bigger screen
loadPrcFileData('', 'background-color 0.5 0.5 0.8') # set background to white
loadPrcFileData("","audio-library-name p3fmod_audio")


import direct.directbase.DirectStart
from direct.showbase import DirectObject
from direct.gui.DirectGui import *
from pandac.PandaModules import *
import sys

from fogObj import *
from prFunc import *
from loadObj import *
from rollBuilding import *
from fallObj import *
from balObj import *
from ObjectLighting import *
from camMov import *
from wiifit import *
from rollBgi import *
from sceneObj import *
from movObj import *


#Maxstar = 9		#No of Maximum initial stars, this value should always be equal to the Maxstar in fallObj.py
#Maxrock = 9		#No of Maximum initial rocks, this value should always be equal to the Maxrock in fallObj.py
class World(DirectObject):
	def __init__(self):
		Maxrock = raw_input("Enter number Maxrock: ")
		print "you entered ", Maxrock
		Maxstar = raw_input("Enter number Maxstar: ")
		print "you entered ", Maxstar
		self.keyval = 3		#this constant is used to move the baloon, 1 means move baloon to left, 2 means to right, 3 means to center.
		base.disableMouse()
		prScr("Use keys 'A & D' to move balloon",1) 	#prScr is a function to print onscreen, this has been inherited from prFunc.py
		prScr("Press C to activate the Wii Board",2)
		
		
		# Lighting control 
		light = lightSetting() #all lighting inherition is from Objectlighting.py , lighting gives the objects its 3D feel
		
		# load background
		self.background = loadObj("plane", "bg1", scale = 0.07)  #uncomment this line to use a static background
		#light.lightOff(self.background)
		#self.back2 = rollBgi()		#comment this line to stop the rolling backgroung, this function is inherited from rollBgi.py
		#self.background = loadObj("plane", "sky",scale = 0.04)
		#self.background = loadObj("plane", "back3",scale = 0.04)
		#self.background.setY(40)
		sceneObj()
		
		fog = worldFog()	#Initializing the fog object, inherited from fogObj.py
		#fog.fog()
		
		# load rolling building
		self.building = rollSky()			#initializing the buildings
		self.building.loadBuilding()		#loading the buildings
		
		# load balloon and load camera object focused at baloon
		self.bal = balObj()					#initialisation of balloon object, the balloon will not be loaded/visible at this stage.
		self.balloon = self.bal.loadBal()	#loading the balloon
		self.cam1 = cam()					#initializing the camera object
		self.cam1.camLook(self.balloon)		#passing the balloon object to camera, just for aligning the camera 
		light.directionL(self.balloon)		#lignting the balloon , to make it 3D appearance
		
		#print (balloon.getX()) 			#Debugging print
		

		# load obstacles and collectables
		self.fall = fallObj()							#initializing the falling stars and rocks
		#print (balloon.getX())
		self.obst = [None for i in range (Maxrock)]		
		self.coll = [None for i in range (Maxstar)]
		for i in range(Maxrock):
			self.obst[i] = self.fall.loadObst(1,i)		#loading the rocks, to a max of the value specified in Maxrock
		for i in range(Maxstar):
			self.coll[i] = self.fall.loadColl(1,i)		#loading the stars, to a max of the value specified in Maxstars
		
		
				
		#wiifit connectoin interface
		self.wiion = 0 					#this value says whether the wiifit is initialised or not 
		self.wiiconnect = 0				#this value says whether the wiifit is connected or not
		self.wii = None
		
		
		# load music
		self.music = loader.loadSfx("music/Level1.mp3")
		self.music.setLoop(True)
		self.music.play()
		
		
		self.accept('a',self.keybNav,[1])
		self.accept('d',self.keybNav,[2])
		self.accept('s',self.keybNav,[3])
		self.accept('c',self.wiiact)		
		self.accept('escape', sys.exit)
		# text field
		b = DirectEntry(text ="", scale=0.05,initialText="Sensitivity",command = self.sensitivity, numLines = 1 ,focus=0)
		b.setPos(-1.2,1,0.78)
		
		#movement commands
		self.movBal = move()
		self.accept('u',self.move,[1])
		self.accept('j',self.move,[2])
		self.accept('h',self.move,[3])
		self.accept('k',self.move,[4])
		self.gametask = taskMgr.add(self.gameloop,"gameloop")
	
	def gameloop(self,task):
		self.bal.movBal(self.keyval)
		self.cam1.camMov(self.balloon,self.keyval)
		#self.building.rollBuilding()
		self.fall.fall()
		self.fall.swap()
		self.fall.collision(self.balloon)
		self.fall.prScore()
		if self.wiion == 1:
			self.keyval = self.wii.getPos()
		#if globalClock.getFrameTime() > 30:
		#	self.back2.roll()
			#print(self.wii.X())
		self.movBal.move(self.balloon)
		
		#print(self.keyval)
		return task.cont
		
	def keybNav(self,val):
		self.keyval = int(val)
	
	def wiiact(self):
		if self.wiiconnect == 1:
			self.wiion = 1
			prScr("Wii Board Activated",6)
		else:
			self.wii = wiifit()
			prScr("Wii Board Client ON",5)
			self.wiiconnect = 1
			#self.wii.offsetAdj()
	
	def sensitivity(self,newVal):
		self.wii.threshold = int(newVal)
		print("New Threshold",self.wii.threshold)
		
	def move(self,movVal):
		self.movBal.setDirections(movVal)

w = World()
run()

File 2

#for the falling stars and rocks
#and their collision with the baloon.
#obstacle means a rock
#collectable means a star


import direct.directbase.DirectStart
from direct.showbase.DirectObject import DirectObject
from random import *
from prFunc import *
from ObjectLighting import *
from loadObj import *

#Maxstar = 9
#Maxroc11k = 9
#LIMITS = 8  #LIMITS define the position of the falling objects

class fallObj(DirectObject):
	def __init__(self):
		LIMITS = raw_input("Enter number Limits: ")
		print "you entered ", Limits
		# intialized values list
		self.nextz = 14
		self.limitz = -15
		self.size = 0.04
		self.xpos = 1
		self.obstz = [9 for i in range(Maxrock)]
		self.collz = [9 for i in range(Maxstar)]
		self.lowerlimit = -18
		self.crash = 0
		self.collects = 0
		self.collcrash = 0
		self.oktoloadC = 0
		self.oktoloadO = 0
		# obstacles list
		self.obst = [None for i in range(Maxrock)]
		
		# collectables list
		self.coll = [None for i in range(Maxstar)]
		
		# counter
		self.countobst = 0
		self.countcoll = 0
		
		#lighting
		self.light = lightSetting()
		
		self.scr1 = prScr("Crashes #"+str(self.crash),7)
		self.scr2 = prScr("Collects #"+str(self.collects),8)
		
		self.hitsfx= loader.loadSfx("music/hitsfx2.mp3")			#load sound effect
		
		
		

		#self.prScore()

		
		
	def loadObst(self,i,j):
		# load initial obstacles
		if i == 0:
			self.obstx = -LIMITS
		else:
			self.obstx =  LIMITS
		self.obstz[j] = j*3+9
		self.obst[j] = loadObj("Obstacle", pos=Point2(self.obstx, self.obstz[j]), scale=self.size*1.5)
		self.light.directionL(self.obst[j])
		self.obst[j].setY(75)
		return self.obst[j]

	def loadColl(self,i,j):
		# load initial Collector object
		if i == 0:
			self.obstx = LIMITS
		else:
			self.obstx =  -LIMITS
		self.collz[j] = j*3+12
		self.coll[j] = loadObj("Star", pos=Point2(self.obstx, self.collz[j]), scale=self.size*0.4)
		self.light.directionL(self.coll[j])
		self.coll[j].setY(75)
		return self.coll[j]	
		
	

	def fall(self):
		
		for i in range(Maxrock):
			print("aa")
			self.obstz[i] = self.obstz[i]-0.2 #this 0.2 controls the speed of falling object 
			if self.obst[i]:
				self.obst[i].setZ(self.obstz[i])
			if self.obstz[i] < self.lowerlimit:
				self.obst[i].remove()
				if i == Maxrock - 1:
					self.oktoloadO = 1
					
				
		for k in range(Maxstar):
			self.collz[k] = self.collz[k] - 0.2 #this 0.2 controls the speed of falling object 
			if self.coll[k]:
				self.coll[k].setZ(self.collz[k])
			if self.collz[k] < self.lowerlimit:
				self.coll[k].remove()
				if k == Maxstar-1:
					self.oktoloadC = 1
				
		if self.oktoloadC ==1 and self.oktoloadO ==1 :
			for m in range(Maxstar):
				self.loadColl(self.xpos,m)
			for m in range(Maxrock):
				self.loadObst(self.xpos,m)
			self.oktoloadC = 0
			self.oktoloadO = 0
			
		
		#print(self.countobst)
		#print(self.countcoll)
		
	def swap(self):
		frameTime = (globalClock.getFrameTime())
		if self.xpos ==0 and frameTime % 20 < 0.1 :
			self.xpos = 1
		if self.xpos == 1 and frameTime % 40 < 0.1:
			self.xpos = 0
			
			
		#print(self.xpos)
		
	def collision(self,bal):
		
		for i in range(Maxrock):
			
			if self.obst[i]:
				if (bal.getX() - self.obst[i].getX()) > -1.5 and (bal.getX() - self.obst[i].getX()) < 1.5 and (bal.getZ() - self.obst[i].getZ()) > 2.5:
					self.crash = self.crash + 1
					print("Collision happened with obst 1")
					print((bal.getX() - self.obst[i].getX()))
					print((bal.getZ() - self.obst[i].getZ()))
					
					self.obst[i].remove()
					self.countobst = self.countobst + 1
					
				
		for j in range(Maxstar):	
			if self.coll[j]:
				if (bal.getX() - self.coll[j].getX()) > -1.5 and (bal.getX() - self.coll[j].getX()) < 1 and (bal.getZ() - self.coll[j].getZ()) > -1:
					
					self.collects = self.collects + 1	
					print("Collision happened with coll 1")
					print((bal.getX() - self.coll[j].getX()))
					print((bal.getZ() - self.coll[j].getZ()))
					self.hitsfx.play()
					self.coll[j].remove()
					self.countcoll = self.countcoll + 1
					self.collcrash = 0
					
				
		
		self.prScore()
		
	def prScore(self):
		self.scr1.setText("Crashes #"+str(self.crash))
		self.scr2.setText("Collects #"+str(self.collects))

You could save the following module as uservars.py

# module uservars

class UserVars(object):
    __slots__ = ('LIMITS','Maxrock','Maxstar')
    
    def __getattr__(self, attr):
        if not attr in self.__slots__:
            raise AttributeError(attr)
        value = raw_input("Enter variable %s: " % attr)
        setattr(self, attr, value)
        return value
    
uservars = UserVars()

Then in every other file, you can use

from uservars import uservars

foo = uservars.Maxstar

This will prompt the user only once for the value of Maxstar if needed.
Notice that you may have to convert user input with the int() function, and you should add support for input validation.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.