def __init__(self, massa = Undefined(), fuel_consumption = Undefined(),\ max_speed = Undefined(), number = Undefined(), charge = Undefined(), carrying = Undefined(),\ required_license_category = Undefined()): Vehicle.__init__(self, massa, fuel_consumption, max_speed, number) self.charge = charge self.carrying = carrying self._required_license_category = required_license_category
def create_vehicles(self): vehicles = [] for size, acc, distance, \ startVel, maxVel, react in zip(self.sizeVelCarDist, self.accCarDist, self.distanceVelCarDist, self.startVelCarDist, self.maxVelCarDist, self.reactCarDist): v = Vehicle(v_id=len(vehicles)+1, size=size, acceleration=acc, distance=distance, startVelocity=startVel, maxVelocity=maxVel, reaction=react, type="Car") # v.__class__ = Car vehicles.append(v) for size, acc, distance, \ startVel, maxVel, react in zip(self.sizeVelTruckDist, self.accTruckDist, self.distanceVelTruckDist, self.startVelTruckDist, self.maxVelTruckDist, self.reactTruckDist): v = Vehicle(v_id=len(vehicles)+1, size=size, acceleration=acc, distance=distance, startVelocity=startVel, maxVelocity=maxVel, reaction=react, type="Truck") # v.__class__ = Truck vehicles.append(v) return vehicles
def initVehicles(): global vehicleswithWeather vehicleswithWeather = list() bike = Vehicle(1, 'Bike', 10, ['Sunny', 'Windy'], 2) tuktuk = Vehicle(2, 'TukTuk', 12, ['Sunny', 'Rainy'], 1) car = Vehicle(3, 'Car', 20, ['Sunny', 'Rainy', 'Windy'], 3) vehicleswithWeather.extend([bike, tuktuk, car])
def __init__(self, model, manufacturer, horsepower, wheel_count, capacity): Vehicle.__init__(self, "Ram", "Dodge", 395, 4) GasPowered.__init__(self, 26) def drive(self): GasPowered.drive(self, 6)
def __init__(self, has_ac, has_strwheel, has_belt, has_audioplayer, name, wheels, speed, weight, mileage, color): self.has_ac = has_ac self.has_strwheel = has_strwheel self.has_belt = has_belt self.has_audioplayer = has_audioplayer Vehicle.__init__(self, name, wheels, speed, weight, mileage, color)
def get_truck_with_profile(slope, set_vel, mass, v_plus=0, v_minus=0, start_v=-1, start_i=-1): """Instantiates the truck from vehicle class Args: slope: The slope over the full road set_vel (int): Set velocity for the GPS-Cruise-Control mass (int): The total vehicle mass v_plus (int): The positive hysteresis for the GPS-Cruise-Control v_minus (int): The negative hysteresis for the GPS-Cruise-Control start_v: The start velocity of the truck start_i: The index of the road at which the truck starts Returns: truck: Instance of vehicle v_profile: Output of the trucks GPS-Cruise-Control""" state = VehicleState(0, set_vel / 3.6, v_plus / 3.6, v_minus / -3.6, mass * 1000) if start_v > -1 and start_i > -1: truck = Vehicle(state, slope[(start_i * 10) // 50:], start_v) else: truck = Vehicle(state, slope) v_profile = [e[0] for e in truck.velocity_profile.velocity_profile] return truck, v_profile
def check_crash(self, positions: List[List[Tuple]], player: Vehicle, player_num: int) -> bool: curr_location = player.get_x(), player.get_y() + player.get_width() / 2 for position in range(len(positions)): if position != player_num: if curr_location in positions[position]: return True return False
def __init__(self, make, model, year, category, displacement): Vehicle.__init__(self, "M", 2) self._make = make self._model = model self._year = year self._catetory = category self._displacement = displacement self._cost = self.getCost()
def __init__(self, massa = Undefined(), fuel_consumption = Undefined(),\ max_speed = Undefined(), number = Undefined(), charge = Undefined(), comfort_class = Undefined(),\ ABS_sistem = Undefined(), required_license_category = Undefined()): Vehicle.__init__(self, massa, fuel_consumption, max_speed, number) self.charge = charge; self.ABS_sistem = ABS_sistem; self.comfort_class = comfort_class; self._required_license_category = required_license_category;
def main(): car = Vehicle('Kirloskar', 6, 'No', '4S', 1) ritz = disel('DI Mahindra', 4, 'No', '1000cc', 'present', 5) sls = bmw('SLS Mc learn', 4, 'YES', 'Dx', '3D camera', 2) ballano = petrol('New ballano', 4, 4, 'V8', 'present', 4) car.Showinfo() ritz.Showinfo() sls.Showinfo() ballano.Showinfo()
def check_power_up(self, user: Vehicle, pup: PowerUp) -> bool: if (((pup.get_x() <= user.get_x() <= pup.get_x() + pup.get_height()) or (pup.get_x() <= user.get_x() + user.get_height() <= pup.get_x() + pup.get_height())) and ((pup.get_y() <= user.get_y() <= pup.get_y() + pup.get_width()) or (pup.get_y() <= user.get_y() + user.get_width() <= pup.get_y() + pup.get_width()))): return True return False
def createOtherVehicles(self, username, carType, carPaint, carTires): if username in self.vehiclelist.keys(): print "Player Already rendered" else: print "Creating main other player @ 100" self.otherPlayer = Vehicle(self.bulletWorld, (90, 10, 5, 0, 0, 0), username) self.characters.append(self.otherPlayer) self.vehiclelist[username] = self.otherPlayer
def test_Noisy_method(self): vehicle = Vehicle() vehicle2 = Vehicle() data = Data() data.saveRoute() list_of_solution_nodes = List_of_solutions_with_ConstructiveAlgorithm( data, vehicle, 1, 100) NewCost = NoisyMethod(data, vehicle2, 1, 100) self.assertLessEqual(vehicle2.acumulatePrice, vehicle.acumulatePrice)
def main(): minivan = Vehicle(7, 16, 21) range = minivan.get_range() print("Minivan passenger:", minivan.passengers) print("Minivan fuelcap:", minivan.fuelcap) print("Minivan mpg:", minivan.mpg) print("Minivan can carry " + str(minivan.passengers) + " with a range of " + str(range)) print(minivan.get_range.__doc__)
def getInitialTruckLocations(self): np.random.seed(47) vehicles = [] np.random.shuffle(self.v) for i, v in enumerate(self.v): if i % 3 == 0: newVehicle = Vehicle(i, v) newVehicle.type = "Truck" newVehicle.capacity = np.random.randint(3, 30) vehicles.append(newVehicle) return vehicles
def __init__(self, canvas, color, x=rand_on_screen('x'), y=rand_on_screen('y')): Vehicle.__init__(self, canvas, color, x=rand_on_screen('x'), y=rand_on_screen('y')) self.ranges_draw = {}
def init_vehicle(self): size = Sizes['vehicle'] i = 0 while (i < self.num_vehicles): x = np.random.randint(size, self.width - size) y = np.random.randint(size, self.height - size) r = Rect(x, y, x + size, y + size) if not r.intersects_any(self.pedestrians_rectangles): v = Vehicle(r, size=size, env=self) v.draw(self.drawing, color=Colors['vehicle']) self.vehicles.append(v) i += 1
def read_from_file(filename): try: cars = [] with open(filename, "r", encoding="utf-8") as file_handle: lines = file_handle.read().splitlines() for line in lines: car = Vehicle() #init empty car object car.read_from_file_line( line) #populate empty object with line data cars.append(car) return cars except IOError: return []
def __init__(self, max_load, speed_limit, name, wheels, speed, weight, mileage, color): self.max_load = max_load self.speed_limit = speed_limit Vehicle.__init__( self, name, wheels, speed, weight, mileage, color, )
def getInitialTruckLocations(self): np.random.seed(47) vehicles = [] np.random.shuffle(self.v) for i, v in enumerate(self.v): if i % 300 == 0: newVehicle = Vehicle( i, v ) #i is the truck number from 0-62, v is the actual truck number newVehicle.type = "Truck" newVehicle.capacity = np.random.randint(3, 30) vehicles.append(newVehicle) return vehicles
def accountMenu(current_user): choice = -1 while choice != '3': print('\n') print('1. New Vehicle Registration') print('2. Driver License Registration') print('3. User Menu') choice = input('Enter your choice: ') if(choice == '1'): user_id = input('User id (Case-Sensitive): ') vehicle_no = input('Vehicle No.: ').upper() vehicle_type = input('Vehicle Type (2/4 Wheeler): ').upper() vehicle_name = input('Vehicle Name: ').upper() vehicle_model = input('Vehicle Model: ').upper() vehicle_color = input('Vehicle Color: ').upper() vehicle_owner = input('Vehicle Owner Name: ').upper() vehicle_year = int(input('Vehicle Purchase Year: ')) new_vehicle = Vehicle(user_id, vehicle_no, vehicle_type, vehicle_name, vehicle_model, vehicle_color, vehicle_owner, vehicle_year) if((User.authenuser_id(user_id)) and (new_vehicle.save())): print("") print('Your New Vehicle Got Registred!') else: print("") print('Sorry Vehicle not Registred! Note: Check User ID') elif(choice == '2'): user_id = input('User id (Case-Sensitive): ') license_no = input('Enter your License no.: ').upper() driver_name = input('Enter Driver Name: ').upper() issue_year = int(input('Issued Year: ')) expire_year = int(input('Expire Year (Valid Upto): ')) issue_authority = input('Issue Authority: ').upper() vehicle_type = input('Vehicle Type (2/4 Wheeler): ').upper() new_license = License(user_id, license_no, driver_name, issue_year, expire_year, issue_authority, vehicle_type) if((User.authenuser_id(user_id)) and (new_license.save())): print("") print('Your License Got Registred!') else: print("") print('Sorry License not Registred! Note: Check User ID') elif choice == '3': print("") print("Note: User Menu pops up only after proper registration. Kindly Login Up incase Registred Already!") mainMenu() else: print('Invalid option !')
def __init__(self, file_name=None): """Creates a VehicleDict composed by vehicles objects, from a file with a list of vehicles. Requires: If given, file_name is str with the name of a .txt file containing a list of vehicles organized as in the examples provided in the general specification (omitted here for the sake of readability). Ensures: if file_name is given: a VehiclesDict, composed by objects of class Vehicle that correspond to the vehicles listed in file with name file_name. if file_name is none: a empty VehiclesList. """ UserDict.__init__(self) inFile = FileUtil(file_name) for line in inFile.getContent(): vehicleData = line.rstrip().split(", ") vehiclePlate = vehicleData.pop(VehiclesDict.INDEXVehiclePlate) vehicleModel, vehicleAutonomy, vehicleKms = vehicleData newVehicle = Vehicle(vehiclePlate, vehicleModel, vehicleAutonomy, vehicleKms) self[vehiclePlate] = newVehicle
def test_Braking_transitions_to_Idle_when_velocity_is_zero(self): subject = Braking() vehicle = Vehicle(vx=0, vy=0, state=Idle()) subject.update(vehicle) self.assertEqual(vehicle.state.__class__, Idle)
def test_Idle_activate_resets_velocity(self): subject = Idle() vehicle = Vehicle(vx=5, vy=10) subject.activate(vehicle) self.assertEqual(numpy.linalg.norm(vehicle.velocity), 0)
def createVehicle(self, x, y, car): if(self.occupiedCells < data.vehicleQuantity): if(self.vehicleList[0] == None): vehicle = Vehicle(0, 0, car, x, y, data.laneNames.index(self.name)) self.vehicleList[0] = vehicle self.add(vehicle) self.occupiedCells += 1
def createMapFromFile(filename): mydata = np.genfromtxt(filename, delimiter=" ", dtype=int) criticaldata = mydata[0] row = criticaldata[0] col = criticaldata[1] vehicles = criticaldata[2] rides = criticaldata[3] bonus = criticaldata[4] steps = criticaldata[5] # print("Row: "+str(row)+ " cols: "+str(col)+ " Vehicles: "+str(vehicles) + " rides: "+str(rides)+ " bonus: "+ str(bonus)+ " steps: " + str(steps)) #print(mydata) mydata = np.delete(mydata, (0), axis=0) #print(mydata.shape) rides = [] # print(mydata[2][0]) # print(mydata[2][1]) for i in range(0, mydata.shape[0]): test = Ride(i, (mydata[i][0], mydata[i][1]), (mydata[i][2], mydata[i][3]), mydata[i][4], mydata[i][5]) rides.append(test) #print(len(rides)) vehiclelist = [] for _ in range(vehicles): vehiclelist.append(Vehicle()) map = Map(row, col, rides, vehiclelist, steps, bonus) return map
def sumo_upload(file): outputFile = open(file, 'r') tree = ET.parse(outputFile) root = tree.getroot() TIME_STEPS = {} for timeStep in root: time = float(timeStep.attrib['time']) VEHICLES = {} if len(timeStep.findall('vehicle')) == 0: break for vehicle in timeStep.findall('vehicle'): id = vehicle.attrib['id'] new_vehicle = Vehicle( id, vehicle.attrib['x'], vehicle.attrib['y'], vehicle.attrib['speed'], vehicle.attrib['lane'].partition('#') [0], # delete '#' and everything after in_accident=False, angle=vehicle.attrib['angle']) VEHICLES[id] = new_vehicle TIME_STEPS[time] = VEHICLES return TIME_STEPS
def test_fithyPercentCharge(self): vehicle = Vehicle() data = Data() data.saveRoute() List_of_solution_nodes = List_of_solutions_with_ConstructiveAlgorithm( data, vehicle, 1, 400) fuel_at_fithy_percent(List_of_solution_nodes[4], vehicle) self.assertAlmostEqual(vehicle.currentFuel, 160)
def test_generate_charge_points_solutions(self): vehicle = Vehicle() data = Data() data.saveRoute() self.assertGreater( len( List_of_solutions_with_ConstructiveAlgorithm( data, vehicle, 1, 100)), 0)
def vehicleReset(self, v = Vehicle(), lane, fracIndex): p = Position(middle(fracIndex, lane)) h = Position(heading(fracIndex)) v.position_p.x = p.x v.position_p.z = p.z v.position_h.x = h.x v.position_h.x = h.x v.fracIndex = fracIndex
def createOtherVehicles(self, username, carType, carPaint, carTires): if username in self.vehiclelist.keys(): print "Player Already rendered" else: print "Creating main other player @ 100" self.otherPlayer = Vehicle(self.bulletWorld, (90, 10, 5,0,0,0), username) self.characters.append(self.otherPlayer) self.vehiclelist[username] = self.otherPlayer
class World(DirectObject): gameStateDict = {"Login" : 0,"CreateLobby":4, "EnterGame": 1, "BeginGame": 2, "InitializeGame":3} gameState = -1 # Login , EnterGame , BeginGame responseValue = -1 currentTime = 0 idleTime = 0 mySequence = None pandaPace = None jumpState = False isWalk = False previousPos = None # used to store the mainChar pos from one frame to another host = "" port = 0 vehiclelist = {} # Stores the list of all the others players characters characters = [] def __init__(self): self.login = "******" base.setFrameRateMeter(True) #input states inputState.watchWithModifiers('forward', 'w') inputState.watchWithModifiers('left', 'a') inputState.watchWithModifiers('brake', 's') inputState.watchWithModifiers('right', 'd') inputState.watchWithModifiers('turnLeft', 'q') inputState.watchWithModifiers('turnRight', 'e') self.keyMap = {"hello": 0, "left": 0, "right": 0, "forward": 0, "backward": 0, "cam-left": 0, "cam-right": 0, "chat0": 0, "powerup": 0, "reset": 0} base.win.setClearColor(Vec4(0, 0, 0, 1)) # Network Setup self.cManager = ConnectionManager(self) self.startConnection() #self.cManager.sendRequest(Constants.CMSG_LOGIN, ["username", "password"]) # chat box # self.chatbox = Chat(self.cManager, self) # Set up the environment # self.initializeBulletWorld(False) #self.createEnvironment() Track(self.bulletWorld) # Create the main character, Ralph self.mainCharRef = Vehicle(self.bulletWorld, (100, 10, 5, 0, 0, 0), self.login) #self.mainCharRef = Character(self, self.bulletWorld, 0, "Me") self.mainChar = self.mainCharRef.chassisNP #self.mainChar.setPos(0, 25, 16) # self.characters.append(self.mainCharRef) # self.TestChar = Character(self, self.bulletWorld, 0, "test") # self.TestChar.actor.setPos(0, 0, 0) self.previousPos = self.mainChar.getPos() taskMgr.doMethodLater(.1, self.updateMove, 'updateMove') # Set Dashboard self.dashboard = Dashboard(self.mainCharRef, taskMgr) self.floater = NodePath(PandaNode("floater")) self.floater.reparentTo(render) # Accept the control keys for movement and rotation self.accept("escape", self.doExit) self.accept("a", self.setKey, ["left", 1]) self.accept("d", self.setKey, ["right", 1]) self.accept("w", self.setKey, ["forward", 1]) self.accept("s", self.setKey, ["backward", 1]) self.accept("arrow_left", self.setKey, ["cam-left", 1]) self.accept("arrow_right", self.setKey, ["cam-right", 1]) self.accept("a-up", self.setKey, ["left", 0]) self.accept("d-up", self.setKey, ["right", 0]) self.accept("w-up", self.setKey, ["forward", 0]) self.accept("s-up", self.setKey, ["backward", 0]) self.accept("arrow_left-up", self.setKey, ["cam-left", 0]) self.accept("arrow_right-up", self.setKey, ["cam-right", 0]) self.accept("h", self.setKey, ["hello", 1]) self.accept("h-up", self.setKey, ["hello", 0]) self.accept("0", self.setKey, ["chat0", 1]) self.accept("0-up", self.setKey, ["chat0", 0]) self.accept("1", self.setKey,["powerup", 1]) self.accept("1-up", self.setKey,["powerup", 0]) self.accept("2", self.setKey,["powerup", 2]) self.accept("2-up", self.setKey,["powerup", 0]) self.accept("3", self.setKey,["powerup", 3]) self.accept("3-up", self.setKey,["powerup", 0]) self.accept("r", self.doReset) self.accept("p", self.setTime) #taskMgr.add(self.move, "moveTask") # Game state variables self.isMoving = False # Sky Dome self.sky = SkyDome() # Set up the camera self.camera = Camera(self.mainChar) #base.disableMouse() #base.camera.setPos(self.mainChar.getX(), self.mainChar.getY() + 10, self.mainChar.getZ() + 2) # Create some lighting ambientLight = AmbientLight("ambientLight") ambientLight.setColor(Vec4(.3, .3, .3, 1)) directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection(Vec3(-5, -5, -5)) directionalLight.setColor(Vec4(1, 1, 1, 1)) directionalLight.setSpecularColor(Vec4(1, 1, 1, 1)) directionalLight2 = DirectionalLight("directionalLight2") directionalLight2.setDirection(Vec3(5, 5, -5)) directionalLight2.setColor(Vec4(1, 1, 1, 1)) directionalLight2.setSpecularColor(Vec4(1, 1, 1, 1)) render.setLight(render.attachNewNode(ambientLight)) render.setLight(render.attachNewNode(directionalLight)) render.setLight(render.attachNewNode(directionalLight2)) # Game initialisation self.gameState = self.gameStateDict["Login"] self.responseValue = -1 self.cManager.sendRequest(Constants.CMSG_LOGIN,[self.login,"1234"]) taskMgr.add(self.enterGame,"EnterGame") # Create Powerups self.createPowerups() taskMgr.add(self.powerups.checkPowerPickup, "checkPowerupTask") taskMgr.add(self.usePowerup, "usePowerUp") def createOtherVehicles(self, username, carType, carPaint, carTires): if username in self.vehiclelist.keys(): print "Player Already rendered" else: print "Creating copie other player @ 60" char = Vehicle(self.bulletWorld, (100, 10, 5,0,0,0), username) self.characters.append(char) self.vehiclelist[username] = char def usePowerup(self, task): if self.keyMap["powerup"] == 1: self.mainCharRef.usePowerup(0) elif self.keyMap["powerup"] == 2: self.mainCharRef.usePowerup(1) elif self.keyMap["powerup"] == 3: self.mainCharRef.usePowerup(2) return task.cont def createPowerups(self): self.powerups = PowerupManager(self.cManager, self.characters) def use_powerup3(self): self.use_powerup(3) def setTime(self): self.cManager.sendRequest(Constants.CMSG_TIME) def use_powerup(self, num): if self.mainCharRef.power_ups[num - 1] == 0: print "power-up slot empty" else: print "power-up", num, "used" def doExit(self): self.cleanup() sys.exit(1) def cleanup(self): self.cManager.sendRequest(Constants.CMSG_DISCONNECT) self.cManager.closeConnection() self.world = None self.outsideWorldRender.removeNode() def doReset(self): self.mainCharRef.reset() def enterGame(self, task): self.startGameNow() return task.done if self.gameState == self.gameStateDict["Login"]: #responseValue = 1 indicates that this state has been finished if self.responseValue == 1: # Authentication succeeded #self.cManager.sendRequest(Constants.CMSG_CREATE_LOBBY, ["raceroyal","0","1"]) self.gameState = self.gameStateDict["CreateLobby"] #self.responseValue = -1 elif self.gameState == self.gameStateDict["CreateLobby"]: if self.responseValue == 1: print "Lobby Created and we are already in" # Lobby Created and we are already in self.gameState = self.gameStateDict["EnterGame"] self.responseValue = -1 elif self.responseValue == 0: print "Game already created, let's join it" #Game already created, let's join it self.cManager.sendRequest(Constants.CMSG_ENTER_GAME_NAME, "raceroyal") self.gameState = self.gameStateDict["EnterGame"] self.responseValue = -1 self.startGameNow() #self.gameState = self.gameStateDict["InitializeGame"] # Everyone is in the game, we send ReqReady, and the server will send positions when every client did #self.cManager.sendRequest(Constants.CMSG_READY) elif self.gameState == self.gameStateDict["EnterGame"]: if self.responseValue == 1: # When the positions are sent, an acknowledgment is sent and we begin the InitializeGame self.responseValue = -1 self.gameState = self.gameStateDict["InitializeGame"] # Everyone is in the game, we send ReqReady, and the server will send positions when every client did self.cManager.sendRequest(Constants.CMSG_READY) elif self.gameState == self.gameStateDict["InitializeGame"]: if self.responseValue == 1: # Set up the camera self.camera = Camera(self.mainChar) self.gameState = self.gameStateDict["BeginGame"] self.cManager.sendRequest(Constants.CMSG_READY) self.responseValue = -1 elif self.gameState == self.gameStateDict["BeginGame"]: if self.responseValue == 1: taskMgr.add(self.move, "moveTask") return task.done return task.cont #return task.done def startGameNow(self): self.camera = Camera(self.mainChar) taskMgr.doMethodLater(.1, self.updateMove, 'updateMove') taskMgr.add(self.move, "moveTask") def createEnvironment(self): self.environ = loader.loadModel("models/square") self.environ.reparentTo(render) #self.environ.setPos(0, 0, 10) self.environ.setScale(500, 500, 1) self.moon_tex = loader.loadTexture("models/moon_1k_tex.jpg") self.environ.setTexture(self.moon_tex, 1) shape = BulletPlaneShape(Vec3(0, 0, 1), 0) node = BulletRigidBodyNode('Ground') node.addShape(shape) np = render.attachNewNode(node) #np.setPos(0, 0, 0) self.bulletWorld.attachRigidBody(node) self.visNP = loader.loadModel('models/track.egg') self.tex = loader.loadTexture("models/tex/Main.png") self.visNP.setTexture(self.tex) geom = self.visNP.findAllMatches('**/+GeomNode').getPath(0).node().getGeom(0) mesh = BulletTriangleMesh() mesh.addGeom(geom) trackShape = BulletTriangleMeshShape(mesh, dynamic=False) body = BulletRigidBodyNode('Bowl') self.visNP.node().getChild(0).addChild(body) bodyNP = render.anyPath(body) bodyNP.node().addShape(trackShape) bodyNP.node().setMass(0.0) bodyNP.setTexture(self.tex) self.bulletWorld.attachRigidBody(bodyNP.node()) self.visNP.reparentTo(render) self.bowlNP = bodyNP self.visNP.setScale(70) def initializeBulletWorld(self, debug=False): self.outsideWorldRender = render.attachNewNode('world') self.bulletWorld = BulletWorld() self.bulletWorld.setGravity(Vec3(0, 0, -9.81)) if debug: self.debugNP = self.outsideWorldRender.attachNewNode(BulletDebugNode('Debug')) self.debugNP.show() self.debugNP.node().showWireframe(True) self.debugNP.node().showConstraints(True) self.debugNP.node().showBoundingBoxes(True) self.debugNP.node().showNormals(False) self.bulletWorld.setDebugNode(self.debugNP.node()) def makeCollisionNodePath(self, nodepath, solid): ''' Creates a collision node and attaches the collision solid to the supplied NodePath. Returns the nodepath of the collision node. ''' # Creates a collision node named after the name of the NodePath. collNode = CollisionNode("%s c_node" % nodepath.getName()) collNode.addSolid(solid) collisionNodepath = nodepath.attachNewNode(collNode) return collisionNodepath # Records the state of the arrow keys def setKey(self, key, value): self.keyMap[key] = value # Accepts arrow keys to move either the player or the menu cursor, # Also deals with grid checking and collision detection def getDist(self): mainCharX = self.mainChar.getPos().x mainCharY = self.mainChar.getPos().y pandaX = self.pandaActor2.getPos().x pandaY = self.pandaActor2.getPos().y dist = math.sqrt(abs(mainCharX - pandaX) ** 2 + abs(mainCharY - pandaY) ** 2) return dist def move(self, task): self.camera.update(self.mainChar) dt = globalClock.getDt() forces = self.mainCharRef.processInput(inputState, dt) moving = self.mainCharRef.chassisNP.getPos() print "Forces received& sending: ", moving[0], moving[1], moving[2] self.cManager.sendRequest(Constants.CMSG_MOVE, [forces[0], forces[1], forces[2], moving.getX(), moving.getY(), moving.getZ(), self.mainCharRef.chassisNP.getH(), self.mainCharRef.chassisNP.getP(), self.mainCharRef.chassisNP.getR()]) self.bulletWorld.doPhysics(dt, 10, 0.02) self.bulletWorld.doPhysics(dt) return task.cont def startConnection(self): """Create a connection to the remote host. If a connection cannot be created, it will ask the user to perform additional retries. """ if self.cManager.connection == None: if not self.cManager.startConnection(): return False return True def listFromInputState(self, inputState): # index 0 == forward # index 1 == brake # index 2 == right # index 3 == left result = [0, 0, 0, 0] if inputState.isSet('forward'): result[0] = 1 if inputState.isSet('brake'): result[1] = 1 if inputState.isSet('right'): result[2] = 1 if inputState.isSet('left'): result[3] = 1 return result def updateMove(self, task): if self.isMoving == True: moving = self.mainChar.getPos() - self.previousPos self.cManager.sendRequest(Constants.CMSG_MOVE, [moving.getX(), moving.getY(), moving.getZ(), self.mainCharRef.actor.getH(), self.mainCharRef.actor.getP(), self.mainCharRef.actor.getR(), self.listFromInputState(inputState)]) # self.cManager.sendRequest(Constants.RAND_FLOAT, 1.0) self.previousPos = self.mainChar.getPos() return task.again
def __init__(self): self.loading = LoadingScreen() base.setFrameRateMeter(True) #input states inputState.watchWithModifiers('forward', 'w') inputState.watchWithModifiers('left', 'a') inputState.watchWithModifiers('brake', 's') inputState.watchWithModifiers('right', 'd') inputState.watchWithModifiers('turnLeft', 'q') inputState.watchWithModifiers('turnRight', 'e') self.keyMap = {"hello": 0, "left": 0, "right": 0, "forward": 0, "backward": 0, "cam-left": 0, "cam-right": 0, "chat0": 0, "powerup": 0, "reset": 0} base.win.setClearColor(Vec4(0, 0, 0, 1)) # Network Setup self.cManager = ConnectionManager(self) self.startConnection() #self.cManager.sendRequest(Constants.CMSG_LOGIN, ["username", "password"]) # chat box # self.chatbox = Chat(self.cManager, self) # Set up the environment # self.initializeBulletWorld(False) #self.createEnvironment() Track(self.bulletWorld) # Create the main character, Ralph self.mainCharRef = Vehicle(self.bulletWorld, (0, 25, 16, 0, 0, 0), self.login) #self.mainCharRef = Character(self, self.bulletWorld, 0, "Me") self.mainChar = self.mainCharRef.chassisNP #self.mainChar.setPos(0, 25, 16) # self.characters.append(self.mainCharRef) # self.TestChar = Character(self, self.bulletWorld, 0, "test") # self.TestChar.actor.setPos(0, 0, 0) self.previousPos = self.mainChar.getPos() taskMgr.doMethodLater(.1, self.updateMove, 'updateMove') # Set Dashboard self.dashboard = Dashboard(self.mainCharRef, taskMgr) self.floater = NodePath(PandaNode("floater")) self.floater.reparentTo(render) # Accept the control keys for movement and rotation self.accept("escape", self.doExit) self.accept("a", self.setKey, ["left", 1]) self.accept("d", self.setKey, ["right", 1]) self.accept("w", self.setKey, ["forward", 1]) self.accept("s", self.setKey, ["backward", 1]) self.accept("arrow_left", self.setKey, ["cam-left", 1]) self.accept("arrow_right", self.setKey, ["cam-right", 1]) self.accept("a-up", self.setKey, ["left", 0]) self.accept("d-up", self.setKey, ["right", 0]) self.accept("w-up", self.setKey, ["forward", 0]) self.accept("s-up", self.setKey, ["backward", 0]) self.accept("arrow_left-up", self.setKey, ["cam-left", 0]) self.accept("arrow_right-up", self.setKey, ["cam-right", 0]) self.accept("h", self.setKey, ["hello", 1]) self.accept("h-up", self.setKey, ["hello", 0]) self.accept("0", self.setKey, ["chat0", 1]) self.accept("0-up", self.setKey, ["chat0", 0]) self.accept("1", self.setKey,["powerup", 1]) self.accept("1-up", self.setKey,["powerup", 0]) self.accept("2", self.setKey,["powerup", 2]) self.accept("2-up", self.setKey,["powerup", 0]) self.accept("3", self.setKey,["powerup", 3]) self.accept("3-up", self.setKey,["powerup", 0]) self.accept("r", self.doReset) self.accept("p", self.setTime) #self.loading.finish() #taskMgr.doMethodLater(5, self.move, "moveTask") # Game state variables self.isMoving = False # Sky Dome self.sky = SkyDome() # Set up the camera self.camera = Camera(self.mainChar, self.bulletWorld) #base.disableMouse() #base.camera.setPos(self.mainChar.getX(), self.mainChar.getY() + 10, self.mainChar.getZ() + 2) # Create some lighting ambientLight = AmbientLight("ambientLight") ambientLight.setColor(Vec4(.3, .3, .3, 1)) directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection(Vec3(-5, -5, -5)) directionalLight.setColor(Vec4(1, 1, 1, 1)) directionalLight.setSpecularColor(Vec4(1, 1, 1, 1)) directionalLight2 = DirectionalLight("directionalLight2") directionalLight2.setDirection(Vec3(5, 5, -5)) directionalLight2.setColor(Vec4(1, 1, 1, 1)) directionalLight2.setSpecularColor(Vec4(1, 1, 1, 1)) render.setLight(render.attachNewNode(ambientLight)) render.setLight(render.attachNewNode(directionalLight)) render.setLight(render.attachNewNode(directionalLight2)) # Game initialisation self.gameState = self.gameStateDict["Login"] self.responseValue = -1 self.cManager.sendRequest(Constants.CMSG_LOGIN,[self.login,"1234"]) taskMgr.add(self.enterGame,"EnterGame") # Create Powerups self.createPowerups() taskMgr.add(self.powerups.checkPowerPickup, "checkPowerupTask") taskMgr.add(self.usePowerup, "usePowerUp")
class World(DirectObject): gameStateDict = {"Login" : 0,"CreateLobby":4, "EnterGame": 1, "BeginGame": 2, "InitializeGame":3} gameState = -1 # Login , EnterGame , BeginGame responseValue = -1 currentTime = 0 idleTime = 0 mySequence = None pandaPace = None jumpState = False isWalk = False previousPos = None # used to store the mainChar pos from one frame to another host = "" port = 0 vehiclelist = {} # Stores the list of all the others players characters characters = [] login = "******" def __init__(self): self.loading = LoadingScreen() base.setFrameRateMeter(True) #input states inputState.watchWithModifiers('forward', 'w') inputState.watchWithModifiers('left', 'a') inputState.watchWithModifiers('brake', 's') inputState.watchWithModifiers('right', 'd') inputState.watchWithModifiers('turnLeft', 'q') inputState.watchWithModifiers('turnRight', 'e') self.keyMap = {"hello": 0, "left": 0, "right": 0, "forward": 0, "backward": 0, "cam-left": 0, "cam-right": 0, "chat0": 0, "powerup": 0, "reset": 0} base.win.setClearColor(Vec4(0, 0, 0, 1)) # Network Setup self.cManager = ConnectionManager(self) self.startConnection() #self.cManager.sendRequest(Constants.CMSG_LOGIN, ["username", "password"]) # chat box # self.chatbox = Chat(self.cManager, self) # Set up the environment # self.initializeBulletWorld(False) #self.createEnvironment() Track(self.bulletWorld) # Create the main character, Ralph self.mainCharRef = Vehicle(self.bulletWorld, (0, 25, 16, 0, 0, 0), self.login) #self.mainCharRef = Character(self, self.bulletWorld, 0, "Me") self.mainChar = self.mainCharRef.chassisNP #self.mainChar.setPos(0, 25, 16) # self.characters.append(self.mainCharRef) # self.TestChar = Character(self, self.bulletWorld, 0, "test") # self.TestChar.actor.setPos(0, 0, 0) self.previousPos = self.mainChar.getPos() taskMgr.doMethodLater(.1, self.updateMove, 'updateMove') # Set Dashboard self.dashboard = Dashboard(self.mainCharRef, taskMgr) self.floater = NodePath(PandaNode("floater")) self.floater.reparentTo(render) # Accept the control keys for movement and rotation self.accept("escape", self.doExit) self.accept("a", self.setKey, ["left", 1]) self.accept("d", self.setKey, ["right", 1]) self.accept("w", self.setKey, ["forward", 1]) self.accept("s", self.setKey, ["backward", 1]) self.accept("arrow_left", self.setKey, ["cam-left", 1]) self.accept("arrow_right", self.setKey, ["cam-right", 1]) self.accept("a-up", self.setKey, ["left", 0]) self.accept("d-up", self.setKey, ["right", 0]) self.accept("w-up", self.setKey, ["forward", 0]) self.accept("s-up", self.setKey, ["backward", 0]) self.accept("arrow_left-up", self.setKey, ["cam-left", 0]) self.accept("arrow_right-up", self.setKey, ["cam-right", 0]) self.accept("h", self.setKey, ["hello", 1]) self.accept("h-up", self.setKey, ["hello", 0]) self.accept("0", self.setKey, ["chat0", 1]) self.accept("0-up", self.setKey, ["chat0", 0]) self.accept("1", self.setKey,["powerup", 1]) self.accept("1-up", self.setKey,["powerup", 0]) self.accept("2", self.setKey,["powerup", 2]) self.accept("2-up", self.setKey,["powerup", 0]) self.accept("3", self.setKey,["powerup", 3]) self.accept("3-up", self.setKey,["powerup", 0]) self.accept("r", self.doReset) self.accept("p", self.setTime) #self.loading.finish() #taskMgr.doMethodLater(5, self.move, "moveTask") # Game state variables self.isMoving = False # Sky Dome self.sky = SkyDome() # Set up the camera self.camera = Camera(self.mainChar, self.bulletWorld) #base.disableMouse() #base.camera.setPos(self.mainChar.getX(), self.mainChar.getY() + 10, self.mainChar.getZ() + 2) # Create some lighting ambientLight = AmbientLight("ambientLight") ambientLight.setColor(Vec4(.3, .3, .3, 1)) directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection(Vec3(-5, -5, -5)) directionalLight.setColor(Vec4(1, 1, 1, 1)) directionalLight.setSpecularColor(Vec4(1, 1, 1, 1)) directionalLight2 = DirectionalLight("directionalLight2") directionalLight2.setDirection(Vec3(5, 5, -5)) directionalLight2.setColor(Vec4(1, 1, 1, 1)) directionalLight2.setSpecularColor(Vec4(1, 1, 1, 1)) render.setLight(render.attachNewNode(ambientLight)) render.setLight(render.attachNewNode(directionalLight)) render.setLight(render.attachNewNode(directionalLight2)) # Game initialisation self.gameState = self.gameStateDict["Login"] self.responseValue = -1 self.cManager.sendRequest(Constants.CMSG_LOGIN,[self.login,"1234"]) taskMgr.add(self.enterGame,"EnterGame") # Create Powerups self.createPowerups() taskMgr.add(self.powerups.checkPowerPickup, "checkPowerupTask") taskMgr.add(self.usePowerup, "usePowerUp") def usePowerup(self, task): if self.keyMap["powerup"] == 1: self.mainCharRef.usePowerup(0) elif self.keyMap["powerup"] == 2: self.mainCharRef.usePowerup(1) elif self.keyMap["powerup"] == 3: self.mainCharRef.usePowerup(2) return task.cont def createPowerups(self): self.powerups = PowerupManager(self.cManager, self.characters) def use_powerup3(self): self.use_powerup(3) def setTime(self): self.cManager.sendRequest(Constants.CMSG_TIME) def use_powerup(self, num): if self.mainCharRef.power_ups[num - 1] == 0: print "power-up slot empty" else: print "power-up", num, "used" def doExit(self): self.cleanup() sys.exit(1) def cleanup(self): self.cManager.sendRequest(Constants.CMSG_DISCONNECT) self.cManager.closeConnection() self.world = None self.outsideWorldRender.removeNode() def doReset(self): self.mainCharRef.reset() def enterGame(self, task): if self.gameState == self.gameStateDict["Login"]: #responseValue = 1 indicates that this state has been finished if self.responseValue == 1: # Authentication succeeded self.cManager.sendRequest(Constants.CMSG_CREATE_LOBBY, ["raceroyal","0","1"]) self.gameState = self.gameStateDict["CreateLobby"] self.responseValue = -1 elif self.gameState == self.gameStateDict["CreateLobby"]: if self.responseValue == 1: # Lobby Created and we are already in self.gameState = self.gameStateDict["EnterGame"] self.responseValue = -1 elif self.responseValue == 0: #Game already created, let's join it self.cManager.sendRequest(Constants.CMSG_ENTER_GAME_NAME, "raceroyal") self.gameState = self.gameStateDict["EnterGame"] self.responseValue = -1 elif self.gameState == self.gameStateDict["EnterGame"]: if self.responseValue == 1: # When the positions are sent, an acknowledgment is sent and we begin the InitializeGame self.responseValue = -1 self.gameState = self.gameStateDict["InitializeGame"] # Everyone is in the game, we send ReqReady, and the server will send positions when every client did self.cManager.sendRequest(Constants.CMSG_READY) elif self.gameState == self.gameStateDict["InitializeGame"]: if self.responseValue == 1: # Set up the camera self.camera = Camera(self.mainChar, self.bulletWorld) self.gameState = self.gameStateDict["BeginGame"] self.cManager.sendRequest(Constants.CMSG_READY) self.responseValue = -1 elif self.gameState == self.gameStateDict["BeginGame"]: if self.responseValue == 1: self.loading.finish() taskMgr.doMethodLater(5, self.move, "moveTask") return task.done return task.cont def createEnvironment(self): self.environ = loader.loadModel("models/square") self.environ.reparentTo(render) self.environ.setPos(0, 0, 0) self.environ.setScale(500, 500, 1) self.moon_tex = loader.loadTexture("models/moon_1k_tex.jpg") self.environ.setTexture(self.moon_tex, 1) shape = BulletPlaneShape(Vec3(0, 0, 1), 0) node = BulletRigidBodyNode('Ground') node.addShape(shape) np = render.attachNewNode(node) np.setPos(0, 0, 0) self.bulletWorld.attachRigidBody(node) self.visNP = loader.loadModel('models/track.egg') self.tex = loader.loadTexture("models/tex/Main.png") self.visNP.setTexture(self.tex) geom = self.visNP.findAllMatches('**/+GeomNode').getPath(0).node().getGeom(0) mesh = BulletTriangleMesh() mesh.addGeom(geom) trackShape = BulletTriangleMeshShape(mesh, dynamic=False) body = BulletRigidBodyNode('Bowl') self.visNP.node().getChild(0).addChild(body) bodyNP = render.anyPath(body) bodyNP.node().addShape(trackShape) bodyNP.node().setMass(0.0) bodyNP.setTexture(self.tex) self.bulletWorld.attachRigidBody(bodyNP.node()) self.visNP.reparentTo(render) self.bowlNP = bodyNP self.visNP.setScale(70) def initializeBulletWorld(self, debug=False): self.outsideWorldRender = render.attachNewNode('world') self.bulletWorld = BulletWorld() self.bulletWorld.setGravity(Vec3(0, 0, -9.81)) if debug: self.debugNP = self.outsideWorldRender.attachNewNode(BulletDebugNode('Debug')) self.debugNP.show() self.debugNP.node().showWireframe(True) self.debugNP.node().showConstraints(True) self.debugNP.node().showBoundingBoxes(True) self.debugNP.node().showNormals(False) self.bulletWorld.setDebugNode(self.debugNP.node()) def makeCollisionNodePath(self, nodepath, solid): ''' Creates a collision node and attaches the collision solid to the supplied NodePath. Returns the nodepath of the collision node. ''' # Creates a collision node named after the name of the NodePath. collNode = CollisionNode("%s c_node" % nodepath.getName()) collNode.addSolid(solid) collisionNodepath = nodepath.attachNewNode(collNode) return collisionNodepath # Records the state of the arrow keys def setKey(self, key, value): self.keyMap[key] = value # Accepts arrow keys to move either the player or the menu cursor, # Also deals with grid checking and collision detection def getDist(self): mainCharX = self.mainChar.getPos().x mainCharY = self.mainChar.getPos().y pandaX = self.pandaActor2.getPos().x pandaY = self.pandaActor2.getPos().y dist = math.sqrt(abs(mainCharX - pandaX) ** 2 + abs(mainCharY - pandaY) ** 2) return dist def move(self, task): # If the camera-left key is pressed, move camera left. # If the camera-right key is pressed, move camera right. #dt = globalClock.getDt() #update camera self.camera.update(self.mainChar) #base.camera.lookAt(self.mainChar) #if (self.keyMap["cam-left"] != 0): # base.camera.setX(base.camera, -20 * dt) #if (self.keyMap["cam-right"] != 0): # base.camera.setX(base.camera, +20 * dt) # save mainChar's initial position so that we can restore it, # in case he falls off the map or runs into something. # #startpos = self.mainChar.getPos() # # If a move-key is pressed, move ralph in the specified direction. # If a move-key is pressed, move ralph in the specified direction. # Steering info #steering = 0.0 # degree #steeringClamp = 70.0 # degree #steeringIncrement = 180.0 # degree per second # # Process input #engineForce = 0.0 #brakeForce = 0.0 #if (self.keyMap["forward"] != 0): # # checks for vehicle's max speed # if self.mainCharRef.vehicle.getCurrentSpeedKmHour() <= self.mainCharRef.max_speed: # engineForce = 2000.0 # brakeForce = 0.0 # #if (self.keyMap["backward"] != 0): # if self.mainCharRef.vehicle.getCurrentSpeedKmHour() <= 0: # engineForce = -500.0 # brakeForce = 0.0 # else: # engineForce = 0.0 # brakeForce = 100.0 # #if (self.keyMap["left"] != 0): # steering += dt * steeringIncrement # steering = min(steering, steeringClamp) # #if (self.keyMap["right"] != 0): # steering -= dt * steeringIncrement # steering = max(steering, -steeringClamp) # # Apply steering to front wheels #self.mainCharRef.vehicle.setSteeringValue(steering, 0) #self.mainCharRef.vehicle.setSteeringValue(steering, 1) # # Apply engine and brake to rear wheels #self.mainCharRef.vehicle.applyEngineForce(engineForce, 2) #self.mainCharRef.vehicle.applyEngineForce(engineForce, 3) #self.mainCharRef.vehicle.setBrake(brakeForce, 2) #self.mainCharRef.vehicle.setBrake(brakeForce, 3) # If ralph is moving, loop the run animation. # If he is standing still, stop the animation. #if (self.keyMap["forward"] != 0) or (self.keyMap["backward"] != 0) or (self.keyMap["left"] != 0) or ( # self.keyMap["right"] != 0): # if self.isMoving is False: # self.mainCharRef.run() # self.isMoving = True # #else: # if self.isMoving: # self.mainCharRef.walk() # self.isMoving = False dt = globalClock.getDt() self.mainCharRef.processInput(inputState, dt) self.bulletWorld.doPhysics(dt, 10, 0.02) # If the camera is too far from ralph, move it closer. # If the camera is too close to ralph, move it farther. #camvec = self.mainChar.getPos() - base.camera.getPos() #camvec.setZ(0) #camdist = camvec.length() #camvec.normalize() #if (camdist > 10.0): # base.camera.setPos(base.camera.getPos() + camvec * (camdist - 10)) # camdist = 10.0 #if (camdist < 5.0): # base.camera.setPos(base.camera.getPos() - camvec * (5 - camdist)) # camdist = 5.0 # The camera should look in ralph's direction, # but it should also try to stay horizontal, so look at # a floater which hovers above ralph's head. #self.floater.setPos(self.mainChar.getPos()) #self.floater.setZ(self.mainChar.getZ() + 2.0) #base.camera.lookAt(self.floater) self.bulletWorld.doPhysics(dt) return task.cont def startConnection(self): """Create a connection to the remote host. If a connection cannot be created, it will ask the user to perform additional retries. """ if self.cManager.connection == None: if not self.cManager.startConnection(): return False return True # Chat # def message(self, task): # # hide all chatboxes # if self.keyMap["chat0"] != 0: # if self.chatbox.getVisible() is False: # self.chatbox.setVisible(True) # self.chatbox.show(0) # else: # self.chatbox.setVisible(False) # self.chatbox.hide() # self.keyMap["chat0"] = 0 # if self.keyMap["chat1"] != 0: # if self.chatbox.getVisible() is False: # self.chatbox.setVisible(True) # self.chatbox.show(1) # else: # self.chatbox.setVisible(False) # self.chatbox.hide() # self.keyMap["chat1"] = 0 # elif self.keyMap["chat2"] != 0: # if self.chatbox.getVisible() is False: # self.chatbox.setVisible(True) # self.chatbox.show(2) # else: # self.chatbox.setVisible(False) # self.chatbox.hide() # self.keyMap["chat2"] = 0 # elif self.keyMap["chat3"] != 0: # if self.chatbox.getVisible() is False: # self.chatbox.setVisible(True) # self.chatbox.show(3) # else: # self.chatbox.setVisible(False) # self.chatbox.hide() # self.keyMap["chat3"] = 0 # elif self.keyMap["chat4"] != 0: # if self.chatbox.getVisible() is False: # self.chatbox.setVisible(True) # self.chatbox.show(4) # else: # self.chatbox.setVisible(False) # self.chatbox.hide() # self.keyMap["chat4"] = 0 # elif self.keyMap["chat5"] != 0: # if self.chatbox.getVisible() is False: # self.chatbox.setVisible(True) # self.chatbox.show(5) # else: # self.chatbox.setVisible(False) # self.chatbox.hide() # self.keyMap["chat5"] = 0 # return task.cont def listFromInputState(self, inputState): # index 0 == forward # index 1 == brake # index 2 == right # index 3 == left result = [0, 0, 0, 0] if inputState.isSet('forward'): result[0] = 1 if inputState.isSet('brake'): result[1] = 1 if inputState.isSet('right'): result[2] = 1 if inputState.isSet('left'): result[3] = 1 return result def updateMove(self, task): if self.isMoving == True: moving = self.mainChar.getPos() - self.previousPos self.cManager.sendRequest(Constants.CMSG_MOVE, [moving.getX(), moving.getY(), moving.getZ(), self.mainCharRef.actor.getH(), self.mainCharRef.actor.getP(), self.mainCharRef.actor.getR(), self.listFromInputState(inputState)]) # self.cManager.sendRequest(Constants.RAND_FLOAT, 1.0) self.previousPos = self.mainChar.getPos() return task.again