def __init__(self, xmlfile, datadir, spawnpos, world): super(XMLTruck, self).__init__(xmlfile, datadir, spawnpos, world) p = self.parser # For readability... self.hitchConstraint = None self.hitchedTrailer = None # ===== Sound ===== self.sound = SoundController(p.getEngineRpmIdle(), p.getEngineRpmMax() * 1./4., p.getEngineRpmMax() * 2./4., p.getEngineRpmMax() * 3./4.) # ===== Steering ===== self.physMaxAngle = p.getSteeringAngleMax() # The absolute maximum angle possible self.maxAngle = self.physMaxAngle # The maximum steering angle at the current speed (speed-sensitive) self.rate = p.getSteeringRate() self.curAngle = 0.0 self._steerDir = 0 # -1, 0, 1: Sets the direction of steering # ===== Select a drivetrain ===== if p.getDrivetrainType() == "automatic": #self.drivetrain = AutomaticDt(self.vehicle, self.parser) self.drivetrain = Drivetrain(self.vehicle, self.parser) else: print "[WRN] The selected drivetrain type is unknown, choosing automatic!" self.drivetrain = AutomaticDt(self.vehicle, self.parser)
def __init__(self): threading.Thread.__init__(self) self.running = False self.soundCtrlr = SoundController() self.initVideo() self.whereIsEveryoneFlag = False self.iSeeSomeoneFlag = False self.failure = False self.record = False
def __init__(self): self.currentProgram = 'menu' # Current main loop WIDTH, HEIGHT = 720,406 # Output video quality self.clock = pygame.time.Clock() self.timerController = TimerController() self.renderer = Renderer(WIDTH, HEIGHT) self.imageLoader = ImageLoader() self.soundController = SoundController('bgMusic.ogg',[('cutSpell',0.1),('lightingSpell',0.1),('explosionSpell',0.1)],0.05) self.mouseController = MouseController() self.menu = Menu(self.imageLoader.imageStorage['menu'],self) self.player = Player((WIDTH, HEIGHT),self.imageLoader.imageStorage["player"],[(0,2),(2,5),(5,8),(8,11),(11,14),(14,22),(22,37)]) self.spellController = SpellController(self.mouseController,self.imageLoader.imageStorage,self.renderer, self.player,self.soundController) self.amountBars = AmountBars(self.player, None, self.imageLoader.imageStorage['bars'],(WIDTH//2,HEIGHT//2)) self.boss = None self.level = None self.playerMovement = None
def iSeeSomeone(self): if(self.iSeeSomeoneFlag == False): SoundController.whistle(self.soundCtrlr) self.whereIsEveryoneFlag = False self.iSeeSomeoneFlag = True
import sys sys.path.append('./classes') from SoundController import SoundController from time import sleep sound = SoundController() sound.start(SoundController.FILES['MARCH']) sleep(5) sound.stop()
def initializeSoundController(self): self.soundCtrlr = SoundController() self.soundCtrlr.start()
class R2PY: def __init__(self): # if you want to switch to hardware PWM, remember: # GPIO12(Board 32) & GPIO18(Board 12) share a setting as do GPIO13(Board 33) & GPIO19(Board 35) # NOTE: all gpio pin numbers are BCM self.gpioPin_SabertoothS1 = 18 self.gpioPin_SabertoothS2 = 12 self.gpioPin_Syren10 = 13 # board pins 16 (BCM 23) and 18 (BCM 24) initialize to LOW at boot self.gpioPin_2_leg_mode = 23 self.gpioPin_3_leg_mode = 24 self.pi = pigpio.pi() self.pi.set_mode(self.gpioPin_2_leg_mode, pigpio.OUTPUT) self.pi.write(self.gpioPin_2_leg_mode, 0) self.pi.set_mode(self.gpioPin_3_leg_mode, pigpio.OUTPUT) self.pi.write(self.gpioPin_3_leg_mode, 0) self.pi.set_mode(self.gpioPin_Syren10, pigpio.OUTPUT) self.pi.set_PWM_frequency(self.gpioPin_Syren10, 50) self.pi.set_servo_pulsewidth(self.gpioPin_Syren10, 0) # to find the usb port of the sabertooth run this: cd /dev # and ls to see the list of usb ports, then plug in your usb to the sabertooth and ls again to see the new port self.saber = Sabertooth('/dev/ttyACM0', baudrate=115200, address=128, timeout=0.1) self.initializeXboxController() self.initializeSoundController() self.initializePeekabooController() self.running = True def initializePeekabooController(self): self.peekabooCtrlr = PeekabooController() self.peekabooCtrlr.start() def initializeSoundController(self): self.soundCtrlr = SoundController() self.soundCtrlr.start() def initializeXboxController(self): try: # setup controller values self.xValueLeft = 0 self.yValueLeft = 0 self.xValueRight = 0 self.yValueRight = 0 self.dpadValue = (0, 0) self.lbValue = 0 self.xboxCtrlr = XboxController(deadzone=0.3, scale=1, invertYAxis=True) # setup call backs self.xboxCtrlr.setupControlCallback( self.xboxCtrlr.XboxControls.LTHUMBX, self.leftThumbX) self.xboxCtrlr.setupControlCallback( self.xboxCtrlr.XboxControls.LTHUMBY, self.leftThumbY) self.xboxCtrlr.setupControlCallback( self.xboxCtrlr.XboxControls.RTHUMBX, self.rightThumbX) self.xboxCtrlr.setupControlCallback( self.xboxCtrlr.XboxControls.RTHUMBY, self.rightThumbY) # self.xboxCtrlr.setupControlCallback(self.xboxCtrlr.XboxControls.LTRIGGER, self.leftTrigger) #triggers don't work # self.xboxCtrlr.setupControlCallback(self.xboxCtrlr.XboxControls.RTRIGGER, self.rightTrigger) #triggers don't work self.xboxCtrlr.setupControlCallback( self.xboxCtrlr.XboxControls.DPAD, self.dpadButton) self.xboxCtrlr.setupControlCallback( self.xboxCtrlr.XboxControls.BACK, self.backButton) self.xboxCtrlr.setupControlCallback(self.xboxCtrlr.XboxControls.A, self.aButton) self.xboxCtrlr.setupControlCallback(self.xboxCtrlr.XboxControls.B, self.bButton) self.xboxCtrlr.setupControlCallback(self.xboxCtrlr.XboxControls.X, self.xButton) self.xboxCtrlr.setupControlCallback(self.xboxCtrlr.XboxControls.Y, self.yButton) self.xboxCtrlr.setupControlCallback(self.xboxCtrlr.XboxControls.LB, self.lbButton) # start the controller self.xboxCtrlr.start() except: print("ERROR: could not connect to Xbox controller") def steering(self, x, y): # assumes the initial (x,y) coordinates are in the -1.0/+1.0 range print("x = {}".format(x)) print("y = {}".format(y)) # convert to polar r = math.hypot(x, y) t = math.atan2(y, x) # rotate by 45 degrees t += math.pi / 4 # back to cartesian left = r * math.cos(t) right = r * math.sin(t) # rescale the new coords left = left * math.sqrt(2) right = right * math.sqrt(2) # clamp to -1/+1 left = max(-1, min(left, 1)) right = max(-1, min(right, 1)) print("left = {}".format(left)) print("right = {}".format(right)) # rotate 90 degrees counterclockwise back returnLeft = right * -1 returnRight = left print("returnLeft = {}".format(returnLeft)) print("returnRight = {}".format(returnRight)) return returnLeft, returnRight def translate(self, value, leftMin, leftMax, rightMin, rightMax): # figure out how 'wide' each range is leftSpan = leftMax - leftMin rightSpan = rightMax - rightMin # convert the left range into a 0-1 range (float) valueScaled = float(value - leftMin) / float(leftSpan) # convert the 0-1 range into a value in the right range. return rightMin + (valueScaled * rightSpan) # call back functions for left thumb stick def leftThumbX(self, xValue): self.xValueLeft = xValue self.updateFeet() def xValueLeftValue(self): return self.xValueLeft def leftThumbY(self, yValue): self.yValueLeft = yValue self.updateFeet() # call back functions for right thumb stick def rightThumbX(self, xValue): self.xValueRight = xValue self.updateDome() def xValueRightValue(self): return self.xValueRight def rightThumbY(self, yValue): self.yValueRight = yValue self.updateDome() def dpadButton(self, value): print("dpadButton = {}".format(value)) self.dpadValue = value self.transitionLegs() def lbButton(self, value): print("lbButton = {}".format(value)) self.lbValue = value def backButton(self, value): print("backButton = {}".format(value)) self.stop() def aButton(self, value): print("aButton = {}".format(value)) if ((value == 1) & (self.lbValue == 1)): PeekabooController.toggleRecord() if value == 1: self.annoyed() def xButton(self, value): print("xButton = {}".format(value)) if value == 1: self.worried() if (self.lbValue == 1): self.peekabooCtrlr.resume() def bButton(self, value): print("bButton = {}".format(value)) if value == 1: self.whistle() if (self.lbValue == 1): self.peekabooCtrlr.stop() def yButton(self, value): print("yButton = {}".format(value)) if value == 1: self.scream() # behavioral functions def annoyed(self): print("sound annoyed") SoundController.annoyed(self.soundCtrlr) def worried(self): print("sound worried") SoundController.worried(self.soundCtrlr) def whistle(self): print("sound whistle") SoundController.whistle(self.soundCtrlr) def scream(self): print("sound scream") SoundController.scream(self.soundCtrlr) def transitionLegs(self): # up if ((self.dpadValue == (0, -1)) & (self.lbValue == 1)): print("3 legged mode started") self.pi.write(self.gpioPin_3_leg_mode, 1) sleep(0.1) self.pi.write(self.gpioPin_3_leg_mode, 0) # down elif ((self.dpadValue == (0, 1)) & (self.lbValue == 1)): print("2 legged mode started") self.pi.write(self.gpioPin_2_leg_mode, 1) sleep(0.1) self.pi.write(self.gpioPin_2_leg_mode, 0) def updateDome(self): # debug print("xValueRight {}".format(self.xValueRight)) print("yValueRight {}".format(self.yValueRight)) # x,y values coming from XboxController are rotated 90 degrees, # so rotate 90 degrees counterclockwise back (x,y) = (-y, x) x1 = self.yValueRight * -1 y1 = self.xValueRight # debug print("x1 {}".format(x1)) print("y1 {}".format(x1)) # i.e. if i push left, motor should be spinning left # if i push right, motor should be spinning right # assuming RC, then you need to generate pulses about 50 times per second # where the actual width of the pulse controls the speed of the motors, # with a pulse width of about 1500 is stopped # and somewhere around 1000 is full reverse and 2000 is full forward. dutyCycleSyren10 = self.translate(x1, -1, 1, 1000, 2000) # debug print("---------------------") print("dutyCycleSyren10 {}".format(dutyCycleSyren10)) print("---------------------") self.pi.set_servo_pulsewidth(self.gpioPin_Syren10, dutyCycleSyren10) def updateFeet(self): # debug print("xValueLeft {}".format(self.xValueLeft)) print("yValueLeft {}".format(self.yValueLeft)) # i.e. if i push left, left motor should be spinning backwards, right motor forwards # if i push right, left motor should be spinning forwards, right motor backwards left, right = self.steering(self.xValueLeft, self.yValueLeft) dutyCycleS1 = self.translate(left, -1, 1, -100, 100) dutyCycleS2 = self.translate(right, -1, 1, -100, 100) # debug print("---------------------") print("dutyCycleS1 {}".format(dutyCycleS1)) print("dutyCycleS2 {}".format(dutyCycleS2)) print("---------------------") # drive(number, speed) # number: 1-2 # speed: -100 - 100 self.saber.drive(1, dutyCycleS1) self.saber.drive(2, dutyCycleS2) def stop(self): self.pi.set_servo_pulsewidth(self.gpioPin_Syren10, 0) saber.stop() self.xboxCtrlr.stop() self.peekabooCtrlr.stop() self.peekabooCtrlr.stopVideo() self.running = False
def scream(self): print("sound scream") SoundController.scream(self.soundCtrlr)
def whistle(self): print("sound whistle") SoundController.whistle(self.soundCtrlr)
def worried(self): print("sound worried") SoundController.worried(self.soundCtrlr)
def annoyed(self): print("sound annoyed") SoundController.annoyed(self.soundCtrlr)
class XMLTruck(XMLVehicle): def __init__(self, xmlfile, datadir, spawnpos, world): super(XMLTruck, self).__init__(xmlfile, datadir, spawnpos, world) p = self.parser # For readability... self.hitchConstraint = None self.hitchedTrailer = None # ===== Sound ===== self.sound = SoundController(p.getEngineRpmIdle(), p.getEngineRpmMax() * 1./4., p.getEngineRpmMax() * 2./4., p.getEngineRpmMax() * 3./4.) # ===== Steering ===== self.physMaxAngle = p.getSteeringAngleMax() # The absolute maximum angle possible self.maxAngle = self.physMaxAngle # The maximum steering angle at the current speed (speed-sensitive) self.rate = p.getSteeringRate() self.curAngle = 0.0 self._steerDir = 0 # -1, 0, 1: Sets the direction of steering # ===== Select a drivetrain ===== if p.getDrivetrainType() == "automatic": #self.drivetrain = AutomaticDt(self.vehicle, self.parser) self.drivetrain = Drivetrain(self.vehicle, self.parser) else: print "[WRN] The selected drivetrain type is unknown, choosing automatic!" self.drivetrain = AutomaticDt(self.vehicle, self.parser) def setGas(self, gas): if gas <= 1. and gas >= 0.: self.drivetrain.setGas(gas) else: print "Truck.py:setGas(gas) out of range! (0 < x < 1)" def setBrake(self, brake): if brake <= 1. and brake >= 0.: self.drivetrain.setBrake(brake) else: print "Truck.py:setBrake(brake) out of range! (0 < x < 1)" def getGbState(self): return self.drivetrain.getGbState() def shiftDrive(self): self.drivetrain.shiftDrive() def shiftNeutral(self): self.drivetrain.shiftNeutral() def shiftReverse(self): self.drivetrain.shiftReverse() def shiftPark(self): self.drivetrain.shiftPark() def steer(self, direction): if direction >= -1 and direction <= 1: self._steerDir = direction else: print "[WRN] XMLTruck:steer(): Invalid direction parameter." def _steer(self): # We are speed sensitive speed = self.vehicle.getCurrentSpeedKmHour() if speed > 0 and speed < 90: self.maxAngle = (-.5) * speed + 45 # Graph this on WolframAlpha to make it obvious :) elif speed > 90: self.maxAngle = 1.0 if self._steerDir == 1 and self.curAngle < self.maxAngle: if self.curAngle < 0: self.curAngle += 2.0 * self.rate else: self.curAngle += self.rate elif self._steerDir == -1 and self.curAngle > self.maxAngle * -1: if self.curAngle > 0: self.curAngle -= 2.0 * self.rate else: self.curAngle -= self.rate else: # self._steerDir == 0 # steer straight if self.curAngle > self.rate: self.curAngle -= 2.0 * self.rate elif self.curAngle < self.rate * -1.0: self.curAngle += 2.0 * self.rate else: self.curAngle = 0.0 def update(self, dt): super(XMLTruck, self).update(dt) self._steer() self.drivetrain.update(dt) self._applyAirDrag() self._makeSound() if not self.hitchedTrailer == None: self.hitchedTrailer.update(dt, self.curAngle) for axle in range(0, self.parser.getAxleCount()): if self.parser.isAxleSteerable(axle): self.vehicle.setSteeringValue(self.curAngle * self.parser.getAxleSteeringFactor(axle), 2 * axle) self.vehicle.setSteeringValue(self.curAngle * self.parser.getAxleSteeringFactor(axle), 2 * axle + 1) def _applyAirDrag(self): # air density 0.0012 g/cm3 (at sea level and 20 °C) # cw-Value: 0.8 for a "truck", 0.5 for a modern 40 ton "with aero-kit" (see wikipedia), choosing 0.4 for now. # force = (density * cw * A * vel) / 2 force = 0.0012 * 0.4 \ * (self.parser.getDimensions()[0] * self.parser.getDimensions()[1]) \ * (self.getSpeed() / 3.6) \ / 2 # Its a braking force, after all force *= -1. relFVector = self.components[0].getBodyNp().getRelativeVector(render, Point3(0, force, 0)) self.components[0].getBodyNp().node().applyCentralForce(relFVector); def _makeSound(self): self.sound.playEngineSound(self.getRpm(), self.drivetrain.getGasPedal()) def getRpm(self): return self.drivetrain.getRpm() def getGear(self): return self.drivetrain.getGear() def reset(self): for meshId in range(0, self.parser.getMeshCount()): self.components[meshId].setR(0) if meshId == 0: self.components[meshId].setPos(self.components[meshId].getPos() + Vec3(0, 0, 1.5)) else: parentComp = self.components[self.parser.getMeshParent(meshId)] self.components[meshId].getBodyNp().setPos(self.components[meshId].getBodyNp().getPos() + self.parser.getMeshOffset(meshId) + Vec3(0, 0, 1.5)) if not self.hitchedTrailer == None: self.hitchedTrailer.getChassis().setPos(self.hitchedTrailer.getChassis().getPos() + (0,0,1.5)) self.hitchedTrailer.getChassis().setR(0) def control(self, conIndex, direction): if not direction in [-1, 0, 1]: raise ValueError("direction is none of [-1, 0, 1]") if conIndex == 0: if direction in [-1, 1]: self.constraints[conIndex].getConstraint().enableAngularMotor(True, .4 * direction, 10000000.) elif direction == 0: self.constraints[conIndex].getConstraint().enableAngularMotor(True, .0, 1000000.) else: print "[WRN] XMLTruck:control0(direction): Direction is none of [1., 0., -1.]" def couple(self, vehicles): """ Checks if another vehicle is within 1 unit (meter) range of our hitch. If yes, it will be connected to us. """ if self.hitchConstraint == None: ourHitchAbsolute = Util.getAbsolutePos(self.getTrailerHitchPoint(), self.getChassis().getBodyNp()) for vehicle in vehicles: otherHitchAbsolute = Util.getAbsolutePos(vehicle.getTrailerHitchPoint(), vehicle.getChassis().getBodyNp()) if not self == vehicle and vehicle.getType() == "trailer" \ and Util.getDistance(ourHitchAbsolute, otherHitchAbsolute) <= 1: self.hitchConstraint = self.createCouplingJoint(self.getTrailerHitchPoint(), vehicle.getTrailerHitchPoint(), vehicle.getChassis().getBodyNp().node()) self.hitchedTrailer = vehicle else: self.world.removeConstraint(self.hitchConstraint) self.hitchConstraint = None self.hitchedTrailer = None def createCouplingJoint(self, ourHitch, otherHitch, otherChassisNode): #BulletConeTwistConstraint (BulletRigidBodyNode const node_a, BulletRigidBodyNode const node_b, # TransformState const frame_a, TransformState const frame_b) ourFrame = TransformState.makePosHpr(ourHitch, Vec3(0,0,0)) otherFrame = TransformState.makePosHpr(otherHitch, Vec3(0,0,0)) hitchConstraint = BulletConeTwistConstraint(self.getChassis().getBodyNp().node(), otherChassisNode, ourFrame, otherFrame) hitchConstraint.setLimit(170, 40, 30) self.world.attachConstraint(hitchConstraint) return hitchConstraint
sys.path.append('../') from sabines_utils import hsv2rgb from threading import Timer expander = SX1509(0x3E) expander.reset(False) engineLED = RGBLED(expander, [0, 1, 2, 3], False) engineLEDLeft = RGBLED(expander, [3, 4, 5, 6], False) engineLEDRight = RGBLED(expander, [6, 7, 8, 9], False) bridgeLED = RGBLED(expander, [9, 10, 11, 12], False) wiimote = WiiMote(None) wiimote.init() sound = SoundController() animating = False hue = 0 def engineRed(): engineLED.setColor([255, 0, 0]) engineLEDLeft.setColor([255, 0, 0]) engineLEDRight.setColor([255, 0, 0]) engineLEDRight.setColor([255, 0, 0]) sound.start(SoundController.FILES['RESISTANCE']) wiimote.on(wiimote.WIIMOTE_KEYS['A'], engineRed) def engineOff(): global animating