Example #1
0
def rotate(contr):
    """ Read the movements of the mouse and apply them
        as a rotation to the camera. """
    # get the object this script is attached to
    camera = contr.owner

    # Get sensor named Mouse
    mouse = contr.sensors['Mouse']

    if mouse.positive:
        # get width and height of game window
        width = Rasterizer.getWindowWidth()
        height = Rasterizer.getWindowHeight()

        # get mouse movement from function
        move = mouse_move(camera, mouse, width, height)

        # set mouse sensitivity
        sensitivity = camera['Sensitivity']

        # Amount, direction and sensitivity
        leftRight = move[0] * sensitivity
        upDown = move[1] * sensitivity

        # set the values
        camera.applyRotation( [0.0, 0.0, leftRight], 0 )
        camera.applyRotation( [upDown, 0.0, 0.0], 1 )

        # Center mouse in game window
        # Using the '//' operator (floor division) to produce an integer result
        Rasterizer.setMousePosition(width//2, height//2)
Example #2
0
def centerCursor(controller, gameScreen, Rasterizer):

    # extract width and height from gameScreen
    width = gameScreen[0]
    height = gameScreen[1]

    # Get sensor named MouseLook
    mouse = controller.sensors["MouseLook"]

    # get cursor position
    pos = mouse.position

    # if cursor needs to be centered
    if pos != [width / 2, height / 2]:

        # Center mouse in game window
        Rasterizer.setMousePosition(width / 2, height / 2)

    # already centered.  Turn off actuators
    else:
        # Get the actuators
        act_LeftRight = controller.actuators["LeftRight"]
        act_UpDown = controller.actuators["UpDown"]

        # turn off the actuators
        controller.deactivate(act_LeftRight)
        controller.deactivate(act_UpDown)
def mouse_input() :
	"""mouse_input() gere les entrées de la souris et déplace la camera et le joueur en fonction.
	Cette fonction est parametrée par les champs du fichier config.py dans le meme repertoire
	Ce callback est appele par le spawn du premier joueur
	"""
	cont = bge.logic.getCurrentController()
	own = cont.owner
	sens = cont.sensors[0]

	if _click(sens, config.interact.take) and first_player.getInteractor() : # l'utilisateur doit cliquer pour ramasser l'objet
		obj = first_player.getInteractor()
		if "interact" in obj:
			first_player.click()
		elif "item" in obj:
			first_player.take()

	if _click(sens, config.interact.itemaction1):
		first_player.actionItem(1)
	if _click(sens, config.interact.itemaction2):
		first_player.actionItem(2)
	if _click(sens, config.interact.itemaction3):
		first_player.actionItem(3)
	
	global mx, my, first_player, headcam, boxrotz
	mx += sens.position[0] - WIN_MIDDLE_X
	my += sens.position[1] - WIN_MIDDLE_Y
	x = (mx)*config.mouse.sensibility
	y = (my)*config.mouse.sensibility

	first_player.lookAt(mathutils.Euler((0, y, -x)))

	Rasterizer.setMousePosition(WIN_MIDDLE_X, WIN_MIDDLE_Y)
def mouse_input():
    """mouse_input() gere les entrées de la souris et déplace la camera et le joueur en fonction.
	Cette fonction est parametrée par les champs du fichier config.py dans le meme repertoire
	Ce callback est appele par le spawn du premier joueur
	"""
    cont = bge.logic.getCurrentController()
    own = cont.owner
    sens = cont.sensors[0]

    if _click(sens, config.interact.take) and first_player.getInteractor(
    ):  # l'utilisateur doit cliquer pour ramasser l'objet
        obj = first_player.getInteractor()
        if "interact" in obj:
            first_player.click()
        elif "item" in obj:
            first_player.take()

    if _click(sens, config.interact.itemaction1):
        first_player.actionItem(1)
    if _click(sens, config.interact.itemaction2):
        first_player.actionItem(2)
    if _click(sens, config.interact.itemaction3):
        first_player.actionItem(3)

    global mx, my, first_player, headcam, boxrotz
    mx += sens.position[0] - WIN_MIDDLE_X
    my += sens.position[1] - WIN_MIDDLE_Y
    x = (mx) * config.mouse.sensibility
    y = (my) * config.mouse.sensibility

    first_player.lookAt(mathutils.Euler((0, y, -x)))

    Rasterizer.setMousePosition(WIN_MIDDLE_X, WIN_MIDDLE_Y)
Example #5
0
def init():
    loadCursorObjs()
    defaultCursor = Cursor(ARROW_POINTER)
    defaultCursor.setAsDefault()
    defaultCursor.use()

    R.setMousePosition(int(R.getWindowWidth() / 2),
                       int(R.getWindowHeight() / 2))
Example #6
0
def enable(c):
    """ Enable the mouse pointer and at the same time sets the mouse to the our
		center of the screen. Does not require any properties.
	"""
    print("client.mouse.enable")
    # Set the mouse to the default position
    try:
        Rasterizer.setMousePosition(Rasterizer.getWindowWidth() / 2, Rasterizer.getWindowHeight() / 2)
    except:
        pass

        # Enable the mouse
    Rasterizer.showMouse(True)
Example #7
0
def hand_control(contr):
    """ Move the hand following the mouse

    Use the movement of the mouse to determine the rotation
    for the IK arm (right arm) """
    # get the object this script is attached to
    human = contr.owner
    scene = GameLogic.getCurrentScene()
    target = scene.objects['IK_Target_Empty.R']

    # set mouse sensitivity
    sensitivity = human['Sensitivity']

    # If the manipulation mode is inactive, do nothing
    if not human['Manipulate']:
        return
 
    # Get sensor named Mouse
    mouse = contr.sensors['Mouse']

    if mouse.positive:
        # get width and height of game window
        width = Rasterizer.getWindowWidth()
        height = Rasterizer.getWindowHeight()

        # get mouse movement from function
        move = mouse_move(human, mouse, width, height)

        # Amount, direction and sensitivity
        left_right = move[0] * sensitivity
        up_down = move[1] * sensitivity

        target.applyMovement([0.0, left_right, 0.0], True)
        target.applyMovement([0.0, 0.0, up_down], True)

        # Reset mouse position to the centre of the screen
        # Using the '//' operator (floor division) to produce an integer result
        Rasterizer.setMousePosition(width//2, height//2)

    # Get sensors for mouse wheel
    wheel_up = contr.sensors['Wheel_Up']
    wheel_down = contr.sensors['Wheel_Down']

    if wheel_up.positive:
        front = 50.0 * sensitivity
        target.applyMovement([front, 0.0, 0.0], True)

    if wheel_down.positive:
        back = -50.0 * sensitivity
        target.applyMovement([back, 0.0, 0.0], True)
Example #8
0
def centerCursor(controller, gameScreen, Rasterizer):
    # just centre the cursor
    width = gameScreen[0]
    height = gameScreen[1]
    mouse = controller.sensors["MouseLook"]
    pos = mouse.position
    if pos != [width / 2, height / 2]:
        Rasterizer.setMousePosition(math.floor(width / 2),
                                    math.floor(height / 2))
    else:
        # I deactivate the actuators. I am not sure why I have to do this....
        act_LeftRight = controller.actuators["LeftRight"]
        controller.deactivate(act_LeftRight)
        act_GoBack = controller.actuators["GoBack"]
        controller.deactivate(act_GoBack)
Example #9
0
    def look(self):
        cont = bge.logic.getCurrentController()
        mouse = cont.sensors['playerMouse']

        if 'x' not in self.playerCamera:
            self.playerCamera['x'] = math.pi / 2
            self.playerCamera['y'] = math.pi / 6
            x = R.getWindowWidth() // 2
            y = R.getWindowHeight() // 2
            self.playerCamera['size'] = (x, y)

        xpos = self.playerCamera['size'][0]
        ypos = self.playerCamera['size'][1]
        x = (xpos - mouse.position[0]) * self.SENSITIVITY
        y = (ypos - mouse.position[1]) * self.SENSITIVITY

        R.setMousePosition(xpos, ypos)

        self.playerCamera['x'] += x
        self.playerCamera['y'] += y

        #corelation of x(z) angle
        if self.playerCamera['x'] > 2 * math.pi:
            self.playerCamera['x'] -= 2 * math.pi
        if self.playerCamera['x'] < 0:
            self.playerCamera['x'] += 2 * math.pi
        #corelation of y(x) angle
        if self.playerCamera['y'] > math.pi / 2:
            self.playerCamera['y'] = math.pi / 2
        if self.playerCamera['y'] < -math.pi / 2:
            self.playerCamera['y'] = -math.pi / 2

        x = -self.playerCamera['y'] + math.pi / 2
        y = self.playerCamera['x'] + math.pi / 2

        v = mathu.Vector((-x, -math.pi, y))
        w = mathu.Vector((0, 0, (y - math.pi)))

        self.playerCamera.localOrientation = v
        x = self.playerBody.position[0]
        y = self.playerBody.position[1]
        z = self.playerBody.position[2] + 0.7
        self.playerCamera.worldPosition = [x, y, z]
        #print(self.playerCamera.localOrientation)
        self.playerBody.localOrientation = w
Example #10
0
	def look(self):
		cont = bge.logic.getCurrentController()
		mouse = cont.sensors['playerMouse']

		if 'x' not in self.playerCamera:
			self.playerCamera['x'] = math.pi / 2
			self.playerCamera['y'] = math.pi / 6
			x = R.getWindowWidth() // 2
			y = R.getWindowHeight() // 2
			self.playerCamera['size'] = (x,y)

		xpos = self.playerCamera['size'][0]
		ypos = self.playerCamera['size'][1]
		x = (xpos - mouse.position[0])*self.SENSITIVITY
		y = (ypos - mouse.position[1])*self.SENSITIVITY

		R.setMousePosition(xpos,ypos)

		self.playerCamera['x'] += x
		self.playerCamera['y'] += y

		#corelation of x(z) angle
		if self.playerCamera['x'] > 2 * math.pi:
			self.playerCamera['x'] -= 2*math.pi
		if self.playerCamera['x'] < 0:
			self.playerCamera['x'] += 2*math.pi
		#corelation of y(x) angle
		if self.playerCamera['y'] > math.pi / 2:
			self.playerCamera['y'] = math.pi / 2
		if self.playerCamera['y'] < -math.pi / 2:
			self.playerCamera['y'] = -math.pi / 2

		x = -self.playerCamera['y'] + math.pi / 2
		y = self.playerCamera['x'] + math.pi / 2

		v = mathu.Vector((-x,-math.pi,y))
		w = mathu.Vector((0,0,(y-math.pi)))

		self.playerCamera.localOrientation = v
		x = self.playerBody.position[0]
		y = self.playerBody.position[1]
		z = self.playerBody.position[2]+0.7
		self.playerCamera.worldPosition = [x,y,z]
		#print(self.playerCamera.localOrientation)
		self.playerBody.localOrientation = w
Example #11
0
def set(c):
    """ Sets the mouse position using the Rasterizer library. Requires that the
		calling object has the properties: mouse_x and mouse_y set to enable the
		position setting.
	"""
    print("client.mouse.set")

    # Make sure the mouse_x and mouse_y properties are set and are int's
    o = c.owner
    try:
        # Get the coordinates
        mouse_x = o.get("mouse_x")
        mouse_y = o.get("mouse_y")

        # Set the pointer to these coords
        Rasterizer.setMousePosition(mouse_x, mouse_y)
    except:
        return
Example #12
0
    def shifter(self):
        mouse = self.cont.sensors['mouse']
        if 'x' not in self.camera:
            self.camera['x'] = 0.0
            x = R.getWindowWidth() // 2
            y = R.getWindowHeight() // 2
            self.camera['size'] = (x, y)

        xpos = self.camera['size'][0]
        ypos = self.camera['size'][1]

        R.setMousePosition(xpos, ypos)
        x = float(xpos - mouse.position[0]) * self.SENSITIVITY

        self.camera['x'] += x
        if self.camera['x'] > 8.5:
            self.camera['x'] = 8.5
        if self.camera['x'] < -8.5:
            self.camera['x'] = -8.5

        z = self.camera.position[2]
        self.camera.position[0] = -self.camera['x']
	def shifter(self):
		mouse = self.cont.sensors['mouse']
		if 'x' not in self.camera:
			self.camera['x'] = 0.0
			x = R.getWindowWidth() // 2
			y = R.getWindowHeight() // 2
			self.camera['size'] = (x,y)

		xpos = self.camera['size'][0]
		ypos = self.camera['size'][1]

		R.setMousePosition(xpos,ypos)
		x = float(xpos - mouse.position[0])*self.SENSITIVITY
		
		self.camera['x'] += x
		if self.camera['x'] > 8.5:
			self.camera['x'] = 8.5
		if self.camera['x'] < -8.5:
			self.camera['x'] = -8.5

		
		z = self.camera.position[2]
		self.camera.position[0] = -self.camera['x']
Example #14
0
def main():
    print("------------ Player script start :p")

    cont = bge.logic.getCurrentController()
    scene = bge.logic.getCurrentScene()
    player = cont.owner
    
    keyboard = bge.logic.keyboard
    mouse = bge.logic.mouse
    cam = scene.objects.get("Camera") 
    
    ground_sensor = cont.sensors["touch_ground"]
    #print(bge.types.KX_TouchSensor(ground_sensor).hitObject)
    #print(ground_sensor.status == bge.logic.KX_SENSOR_ACTIVE)

    # mouse look
    # apply rotation and reset mouse position
    mouseX = mouse.position[0] * -1
    mouseY = mouse.position[1] * -1
    w = bge.render.getWindowWidth()
    h = bge.render.getWindowHeight()
    w2 = math.ceil(w/2)
    h2 = math.ceil(h/2)

    moveX = mouseX + 0.5
    moveY = mouseY + 0.5

    moveY *= MOUSE_SENS
    moveX *= MOUSE_SENS
    
    print("mouse.position[0]: ", mouseX)
    print("w2: ", w2)
    print("moveX: ",moveX, " moveY: ", moveY)

    cam.applyRotation([moveY, 0, 0], True)
    player.applyRotation([0, 0, moveX], True)
    Rasterizer.setMousePosition(w2, h2)
    
    player_vel = player.getLinearVelocity(True)

    # controls
    k = bge.logic.KX_INPUT_ACTIVE
    
    # crouching
    if k == keyboard.events[bge.events.LEFTCTRLKEY]:
        player.localScale.z = 0.9
    else:
        player.localScale.z = 1.8
        
    # if touching ground
    if ground_sensor.hitObject != None:
        if keyboard.events[bge.events.COMMAKEY] == k:
            if player_vel[1] < PLAYER_MAX_SPEED:
                player.applyForce([0,80,0], True)
        if keyboard.events[bge.events.OKEY] == k:
            if player_vel[1] > -PLAYER_MAX_SPEED:
                player.applyForce([0,-80,0], True)
        if keyboard.events[bge.events.AKEY] == k:
            if player_vel[0] > -PLAYER_MAX_SPEED:
                player.applyForce([-80,0,0], True)
        if keyboard.events[bge.events.EKEY] == k:
            if player_vel[0] < PLAYER_MAX_SPEED:
                player.applyForce([80,0,0], True)
        if keyboard.events[bge.events.SPACEKEY] == k:
            if player_vel[0] < PLAYER_MAX_SPEED:
                player.applyForce([0,0,160], True)
Example #15
0

######## Figure out how much to rotate camera and player ########

# Mouse sensitivity
sensitivity = 0.0005

# Amount, direction and sensitivity
leftRight = pos[0] * sensitivity
upDown = pos[1] * sensitivity

# invert upDown
#upDown = -upDown


######### Use actuators to rotate camera and player #############

# Set the rotation values
rotLeftRight.setDRot( 0.0, 0.0, leftRight, False)
rotUpDown.setDRot( upDown, 0.0, 0.0, True)

# Use them
GameLogic.addActiveActuator(rotLeftRight, True)
GameLogic.addActiveActuator(rotUpDown, True)


############# Center mouse pointer in game window ###############

# Center mouse in game window
Rasterizer.setMousePosition(width/2, height/2)
	if sensor.getKeyStatus(key) in (bge.logic.KX_INPUT_JUST_ACTIVATED, bge.logic.KX_INPUT_ACTIVE):
		return True
	else: return False

def _click(sensor, key) :
	status = sensor.getButtonStatus(key)
	if status == bge.logic.KX_INPUT_JUST_ACTIVATED or status == bge.logic.KX_INPUT_ACTIVE:
		return True
	else: return False



WIN_MIDDLE_X = int(Rasterizer.getWindowWidth()/2)
WIN_MIDDLE_Y = int(Rasterizer.getWindowHeight()/2)
mx, my = (WIN_MIDDLE_X, WIN_MIDDLE_Y)
Rasterizer.setMousePosition(WIN_MIDDLE_X, WIN_MIDDLE_Y)
change = False
boxrotz = 0;

def keyboard_input() :
	"""
	keyboard_input() est le callback du clavier, il est appelé par le spawn du premier joueur
	"""
	global last_action, first_player, change, mx, boxrotz;
	cont = bge.logic.getCurrentController();
	own = cont.owner;
	sens = cont.sensors[0];

	change = False; # doit etre placé à vrai si l'utilisateur effectue un déplacement
	x = (mx)*config.mouse.sensibility; # réorientation de la camera (utilisation des variables de mouse_input() )
	y = (my)*config.mouse.sensibility;
Example #17
0
import Rasterizer
cont = GameLogic.getCurrentController()
player = cont.getOwner()
mousemove = cont.getSensor('mousemove')

Rasterizer.showMouse(0)

player.mouseX = mousemove.getXPosition()
player.mouseY = mousemove.getYPosition()
player.moveX = 0.0
player.moveY = 0.0

shoulderipo = cont.getActuator('shoulderipo')
playerrot = cont.getActuator('playerrot')
shoulder = shoulderipo.getOwner()
player.deltaMouseX =  player.mouseX - (Rasterizer.getWindowWidth() / 2)
player.deltaMouseY = player.mouseY - (Rasterizer.getWindowHeight() / 2)
player.moveX= (player.deltaMouseX - player.moveX) * player.mousefilter
player.moveY= (player.deltaMouseY - player.moveY) * player.mousefilter

player.rot -= (player.moveX * player.sensitivity)
shoulder.pitch -= (player.moveY * player.sensitivity)
GameLogic.addActiveActuator(playerrot, 1)
GameLogic.addActiveActuator(shoulderipo, 1)
	
Rasterizer.setMousePosition(Rasterizer.getWindowWidth() / 2, Rasterizer.getWindowHeight() / 2)
Example #18
0
def initialize(own, starting_ori, scene):
    GameLogic.globalDict.clear()
    #get parameters ofr experiment
    aux = open(own['folder'] + own['mouse_id'] + '\\VRparams.txt', 'r')
    GameLogic.globalDict['params'] = aux.read()

    # Iniziation label
    own['init'] = 1
    GameLogic.globalDict['num_trials'] = float(
        ops.get_data_from_VRparams('num_trials'))
    print(GameLogic.globalDict['num_trials'])
    print('#####################################################')
    print('Mouse:')
    print(own['mouse_id'])
    print('Number of trials:')
    print(GameLogic.globalDict['num_trials'])

    #Rasterizer.showMouse(True)
    #put the pointer in the center of the screen
    width = Rasterizer.getWindowWidth()
    height = Rasterizer.getWindowHeight()
    Rasterizer.setMousePosition(math.floor(width / 2), math.floor(height / 2))

    #save the starting orientation and position
    starting_ori.orientation = own.orientation
    starting_ori.position = own.position
    #control if the user wants to send commands to the PUMP
    GameLogic.globalDict['pump_control'] = own['pump']
    #control if the user wants to send data through a second port
    GameLogic.globalDict['send'] = own['send_info']
    #control if the user wants to send commands to the airpuff device
    GameLogic.globalDict['airpuff_control'] = own['airpuff']
    #counting trials
    GameLogic.globalDict['contadorTrials'] = 0
    # Starting point of the last trial.
    GameLogic.globalDict['tiempoLastTrial'] = -100
    # Starting point of the last trial.
    GameLogic.globalDict['trial_duration'] = float(
        ops.get_data_from_VRparams('trial_duration'))
    # distance between the mouse and the object
    GameLogic.globalDict['distance_mouse_obj'] = float(
        ops.get_data_from_VRparams('distance_mouse_obj'))
    #different walls
    invariance_exp = float(ops.get_data_from_VRparams('invariance'))
    if invariance_exp:
        GameLogic.globalDict['background_walls'] = [
            'backgroundObject', 'backgroundObject_dots',
            'backgroundObject_stripes'
        ]
        GameLogic.globalDict['triangleWalls'] = [
            'wallTriangles', 'wallTriangles_dots', 'wallTriangles_stripes'
        ]
        GameLogic.globalDict['circleWalls'] = [
            'wallCircles', 'wallCircles_dots', 'wallCircles_stripes'
        ]
    else:
        GameLogic.globalDict['background_walls'] = ['backgroundObject']
        GameLogic.globalDict['triangleWalls'] = ['wallTriangles']
        GameLogic.globalDict['circleWalls'] = ['wallCircles']

    #the object to be rewarded can be changed
    rewardedObject = ops.get_data_from_VRparams('rewardedObject')
    if rewardedObject == 'triangle':
        GameLogic.globalDict['rewarded_objectList'] = GameLogic.globalDict[
            'triangleWalls']
        GameLogic.globalDict['punished_objectList'] = GameLogic.globalDict[
            'circleWalls']
        GameLogic.globalDict['reinforcementWall'] = 'reinforcementWallTriangle'
        GameLogic.globalDict['refferenceRewardLeft'] = 0
    elif rewardedObject == 'circle':
        GameLogic.globalDict['rewarded_objectList'] = GameLogic.globalDict[
            'circleWalls']
        GameLogic.globalDict['punished_objectList'] = GameLogic.globalDict[
            'triangleWalls']
        GameLogic.globalDict['reinforcementWall'] = 'reinforcementWallCircle'
        GameLogic.globalDict['refferenceRewardLeft'] = math.pi

    #position of the side white walls
    GameLogic.globalDict['sideWhiteWalls_pos'] = float(
        ops.get_data_from_VRparams('sideWhiteWalls_pos'))
    right_whiteWall = scene.objects['WhiteWallRight']
    left_whiteWall = scene.objects['WhiteWallLeft']
    right_whiteWall.position[1] = starting_ori.position[
        1] + GameLogic.globalDict['sideWhiteWalls_pos'] * GameLogic.globalDict[
            'distance_mouse_obj'] - 85
    left_whiteWall.position[1] = starting_ori.position[
        1] + GameLogic.globalDict['sideWhiteWalls_pos'] * GameLogic.globalDict[
            'distance_mouse_obj'] - 85

    #place the reinforcement walls
    reinforcementWall = scene.objects[
        GameLogic.globalDict['reinforcementWall']]
    reinforcementWall.position[0] = -70
    reinforcementWall.position[1] = 124.06228
    reinforcementWall.position[2] = 17
    GameLogic.globalDict['background_object_margin'] = 6
    reinforcementWallBackground = scene.objects['reinforcementWallBackground']
    reinforcementWallBackground.position[0] = -53.84418
    reinforcementWallBackground.position[1] = reinforcementWall.position[
        1] + GameLogic.globalDict['background_object_margin']
    reinforcementWallBackground.position[2] = reinforcementWall.position[2]

    # this controls how far I put the white walls
    GameLogic.globalDict['walls_margin'] = 6
    # front wall margin
    GameLogic.globalDict['background_object_Z'] = -4
    GameLogic.globalDict['wall_Z_component'] = 10
    #this controls how much to the sides the (invisible) reward objects is placed
    GameLogic.globalDict['sideDisplacementWalls'] = float(
        ops.get_data_from_VRparams('sideDisplacementWalls'))
    #this controls how much to the sides the background walls objects is placed
    GameLogic.globalDict['sideDisplacementbackgroundWalls'] = 19
    # threshold for ending the trial as a fraction of the initial distance between the mouse and the front wall
    #y-threhold
    y_th = float(ops.get_data_from_VRparams('zone.depth_hit'))
    GameLogic.globalDict['y_th_hit'] = GameLogic.globalDict[
        'distance_mouse_obj'] * (1 - y_th) + starting_ori.position[1]
    y_th = float(ops.get_data_from_VRparams('zone.depth_fail'))
    GameLogic.globalDict['y_th_fail'] = GameLogic.globalDict[
        'distance_mouse_obj'] * (1 - y_th) + starting_ori.position[1]
    #x-threhold
    x_th = float(ops.get_data_from_VRparams('zone.width'))
    GameLogic.globalDict[
        'x_th'] = x_th * GameLogic.globalDict['sideDisplacementWalls']
    #this is used to project the mouse's position along its orientation (0 means that we will just use the original position)
    GameLogic.globalDict['length_effective_position'] = 0
    #this controls how close the mouse needs to be to the front wall for the trial to be considered fail
    GameLogic.globalDict['marginFail'] = 10
    #this is to control that we don't present to many times in a row one side
    GameLogic.globalDict['sides_mat'] = []
    GameLogic.globalDict['numb_data_pseudoRandom'] = 3
    #this will keep the measure perfomance. I will take as right trial any in which the mouse finish on the reward side, even if he doesn't get the water.
    GameLogic.globalDict['performance_history'] = []

    #object list
    GameLogic.globalDict['objects_list'] = ['TriangleSphereWall']
    #flip list (every object can be presented as it is or twisted 180 degrees)
    GameLogic.globalDict['flip_list'] = [0, math.pi]
    #Control the presentation of reward
    GameLogic.globalDict['manualControlPresentation'] = 0
    GameLogic.globalDict['LeftRight'] = 0

    #pump veolcity
    GameLogic.globalDict['pump_velocity'] = float(
        ops.get_data_from_VRparams('pump_rate'))
    # Time 0
    GameLogic.globalDict['tiempo0'] = time.clock()
    #experiment duration
    GameLogic.globalDict['expDuration'] = float(
        ops.get_data_from_VRparams('expDuration'))
    # Last reward time. Moment in which the last reward was given
    GameLogic.globalDict['tiempoLastReward'] = -100
    # Last reward time. Moment in which the last reward was given
    GameLogic.globalDict['tiempoLastPunishment'] = -100
    # last reinforcement-presentation time. Moment in which the rewarded object was presented to help association with the water.
    GameLogic.globalDict['tiempoLastReinforcement'] = -100
    # expectation presentation time.
    GameLogic.globalDict['tiempoLastExpectation'] = -100
    #duration of the expectation period
    GameLogic.globalDict['durationExpectationPeriod'] = float(
        ops.get_data_from_VRparams('expectationDur'))
    #probability of expectation trial
    GameLogic.globalDict['expectactionProb'] = float(
        ops.get_data_from_VRparams('expectationProb'))
    #this controls whether we use a spatial threshold to trigger the end of the expectation trial
    GameLogic.globalDict['spatial_threshold'] = float(
        ops.get_data_from_VRparams('spatial_threshold'))
    #the spatial threhold
    GameLogic.globalDict[
        'exp_th'] = GameLogic.globalDict['distance_mouse_obj'] * (1 - float(
            ops.get_data_from_VRparams('exp_th'))) + starting_ori.position[1]
    # Reward time. Duration of the reward.
    GameLogic.globalDict['tiempoReward'] = float(
        ops.get_data_from_VRparams('tiempoReward'))
    # Reward time. Duration of the reward.
    GameLogic.globalDict['afterReward_blackWall_duration'] = float(
        ops.get_data_from_VRparams('afterReward_blackWall_duration'))
    # Duration of the punishment.
    GameLogic.globalDict['punishment_duration'] = float(
        ops.get_data_from_VRparams('punishment_duration'))
    #time spent in the reinforcement corridor
    GameLogic.globalDict['time_reinforcement'] = float(
        ops.get_data_from_VRparams('time_reinforcement'))
    #
    GameLogic.globalDict['endOfTrialDuration'] = 1000
    #threshold for turning
    GameLogic.globalDict['turning_angle'] = float(
        ops.get_data_from_VRparams('turning_angle'))
    # sensitiviy for turning
    GameLogic.globalDict['turnSensitivity'] = float(
        ops.get_data_from_VRparams('turnSensitivity'))
    # sensitivity for moving back and forward
    GameLogic.globalDict['backForwardSensitivity'] = float(
        ops.get_data_from_VRparams('backForwardSensitivity'))
    # This variable controls if I have given reward and I need to stop the PUMP. No reward at the begining
    GameLogic.globalDict['reward'] = 0
    # This variable controls if the game is on timeout
    GameLogic.globalDict['timeOut'] = 0
    #this variable controls if the game is on timeout during the reinforcement
    GameLogic.globalDict['timeOutReinforcement'] = 0
    #this variable controls if the game is on timeout during the expectation control
    GameLogic.globalDict['timeOutExpectation'] = 0
    #Window to average turning
    GameLogic.globalDict['turn_history'] = [0]
    GameLogic.globalDict['backForward_history'] = [0]
    #length of the average window
    GameLogic.globalDict['average_window'] = 60
    #this is to control that we didn't close the program yet
    GameLogic.globalDict['still_open'] = 1
    now = datetime.datetime.now()
    GameLogic.globalDict['now'] = now
    #here I will save the position of the mouse at every moment. And, when close it, I will save it.
    GameLogic.globalDict['file'] = open(
        own['folder'] + own['mouse_id'] + '\\' + str(now.year) + '_' +
        str(now.month) + '_' + str(now.day) + '_' + str(now.hour) + '.txt',
        'w')
    GameLogic.globalDict['summary'] = open(
        own['folder'] + own['mouse_id'] + '\\' + str(now.year) + '_' +
        str(now.month) + '_' + str(now.day) + '_' + str(now.hour) +
        'summary.txt', 'w')
    GameLogic.globalDict['raw_velocity'] = open(
        own['folder'] + own['mouse_id'] + '\\' + str(now.year) + '_' +
        str(now.month) + '_' + str(now.day) + '_' + str(now.hour) +
        'raw_velocity.txt', 'w')
    GameLogic.globalDict['passive_stim_seq'] = open(
        own['folder'] + own['mouse_id'] + '\\' + str(now.year) + '_' +
        str(now.month) + '_' + str(now.day) + '_' + str(now.hour) +
        'passive_stim.txt', 'w')
    GameLogic.globalDict['log'] = open(
        own['folder'] + own['mouse_id'] + '\\' + own['mouse_id'] + '_log.txt',
        'a+')

    #PASSIVE STIM parameters
    GameLogic.globalDict['passive_trials'] = 0
    GameLogic.globalDict['circle_counter'] = 0
    GameLogic.globalDict['triangle_counter'] = 0
    GameLogic.globalDict['passive_stim'] = 0
    GameLogic.globalDict['tiempoLastStim'] = -100
    GameLogic.globalDict['tiempoLastBlackWall'] = -100
    GameLogic.globalDict['stimDuration'] = float(
        ops.get_data_from_VRparams('stimDuration'))
    GameLogic.globalDict['blackWallDuration'] = float(
        ops.get_data_from_VRparams('blackWallDuration'))
    GameLogic.globalDict['numPassiveTrials'] = float(
        ops.get_data_from_VRparams('numPassiveTrials'))
    GameLogic.globalDict['blackWallDurJitter'] = float(
        ops.get_data_from_VRparams('blackWallDurJitter'))
    aux = float(ops.get_data_from_VRparams('mousePosPassiveStim'))
    GameLogic.globalDict['mousePosPassiveStim'] = GameLogic.globalDict[
        'distance_mouse_obj'] * (1 - aux) + starting_ori.position[1]
    GameLogic.globalDict['stims_mat'] = []
    GameLogic.globalDict['numb_data_pseudoRandom_passStim'] = int(
        ops.get_data_from_VRparams('numb_data_pseudoRandom_passStim'))

    # create my serial ports: ser communicates with simulink and PUMP does with the PUMP
    if GameLogic.globalDict['send']:
        GameLogic.globalDict['ser'] = serial.Serial(port='\\.\COM5',
                                                    baudrate=115200)

    if GameLogic.globalDict['pump_control']:
        GameLogic.globalDict['PUMP'] = serial.Serial(port='\\.\COM3',
                                                     baudrate=19200)
        word = 'rat ' + str(GameLogic.globalDict['pump_velocity']) + '\r\n'
        GameLogic.globalDict['PUMP'].write(word)
        #save commands sent to the pump
        GameLogic.globalDict['PUMP_commands'] = open(
            own['folder'] + own['mouse_id'] + '\\' + str(now.year) + '_' +
            str(now.month) + '_' + str(now.day) + '_' + str(now.hour) +
            'PUMP_commands.txt', 'w')
        word = "".join(
            ['RAT', str(GameLogic.globalDict['pump_velocity']), '\n'])
        GameLogic.globalDict['PUMP_commands'].write(word)
        word = 'dir_inf \n'
        GameLogic.globalDict['PUMP_commands'].write(word)
        word = '----------------------\n'
        GameLogic.globalDict['PUMP_commands'].write(word)
    if GameLogic.globalDict['airpuff_control']:
        GameLogic.globalDict['airPuff'] = serial.Serial(port='\\.\COM6',
                                                        baudrate=9600)
    # I am going to send the environment properties: maze and goal.
    # First, I get the time (see 'goal')
    tiempo = time.clock() - GameLogic.globalDict['tiempo0']
    GameLogic.globalDict['tiempoLastTrial'] = tiempo
    # I write on the file all the data about the experiment
    word = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
    GameLogic.globalDict['log'].write(word + '\n')
    word = 'date' + ' ' + str(now.day) + '_' + str(now.month) + '_' + str(
        now.year) + ' ' + str(now.hour)
    GameLogic.globalDict['log'].write(word + '\n')
    word = 'rewarded_obj' + ' ' + rewardedObject
    GameLogic.globalDict['log'].write(word + '\n')
    word = 'num_trials' + ' ' + str(GameLogic.globalDict['num_trials'])
    GameLogic.globalDict['log'].write(word + '\n')
    word = 'trial_dur' + ' ' + str(GameLogic.globalDict['trial_duration'])
    GameLogic.globalDict['log'].write(word + '\n')
    word = 'rew_duration' + ' ' + str(GameLogic.globalDict['tiempoReward'])
    GameLogic.globalDict['log'].write(word + '\n')
    word = 'punishment_duration' + ' ' + str(
        GameLogic.globalDict['punishment_duration'])
    GameLogic.globalDict['log'].write(word + '\n')
    word = 'turn_sens' + ' ' + str(GameLogic.globalDict['turnSensitivity'])
    GameLogic.globalDict['log'].write(word + '\n')
    word = 'BF_sens' + ' ' + str(
        GameLogic.globalDict['backForwardSensitivity'])
    GameLogic.globalDict['log'].write(word + '\n')
    GameLogic.globalDict['log'].write(word + '\n')
    word = 'protocolo' + ' ' + '170312'
    GameLogic.globalDict['log'].write(word + '\n')

    first_time = 1
    [reward_position, background] = ops.next_reward_position()
    ops.new_trial(reward_position, own, scene, starting_ori, first_time,
                  GameLogic.globalDict['refferenceRewardLeft'], background)
Example #19
0
def main():
    print("------------ Player script start :p")

    cont = bge.logic.getCurrentController()
    scene = bge.logic.getCurrentScene()
    player = cont.owner

    keyboard = bge.logic.keyboard
    mouse = bge.logic.mouse
    cam = scene.objects.get("Camera")

    ground_sensor = cont.sensors["touch_ground"]
    #print(bge.types.KX_TouchSensor(ground_sensor).hitObject)
    #print(ground_sensor.status == bge.logic.KX_SENSOR_ACTIVE)

    # mouse look
    # apply rotation and reset mouse position
    mouseX = mouse.position[0] * -1
    mouseY = mouse.position[1] * -1
    w = bge.render.getWindowWidth()
    h = bge.render.getWindowHeight()
    w2 = math.ceil(w / 2)
    h2 = math.ceil(h / 2)

    moveX = mouseX + 0.5
    moveY = mouseY + 0.5

    moveY *= MOUSE_SENS
    moveX *= MOUSE_SENS

    print("mouse.position[0]: ", mouseX)
    print("w2: ", w2)
    print("moveX: ", moveX, " moveY: ", moveY)

    cam.applyRotation([moveY, 0, 0], True)
    player.applyRotation([0, 0, moveX], True)
    Rasterizer.setMousePosition(w2, h2)

    player_vel = player.getLinearVelocity(True)

    # controls
    k = bge.logic.KX_INPUT_ACTIVE

    # crouching
    if k == keyboard.events[bge.events.LEFTCTRLKEY]:
        player.localScale.z = 0.9
    else:
        player.localScale.z = 1.8

    # if touching ground
    if ground_sensor.hitObject != None:
        if keyboard.events[bge.events.COMMAKEY] == k:
            if player_vel[1] < PLAYER_MAX_SPEED:
                player.applyForce([0, 80, 0], True)
        if keyboard.events[bge.events.OKEY] == k:
            if player_vel[1] > -PLAYER_MAX_SPEED:
                player.applyForce([0, -80, 0], True)
        if keyboard.events[bge.events.AKEY] == k:
            if player_vel[0] > -PLAYER_MAX_SPEED:
                player.applyForce([-80, 0, 0], True)
        if keyboard.events[bge.events.EKEY] == k:
            if player_vel[0] < PLAYER_MAX_SPEED:
                player.applyForce([80, 0, 0], True)
        if keyboard.events[bge.events.SPACEKEY] == k:
            if player_vel[0] < PLAYER_MAX_SPEED:
                player.applyForce([0, 0, 160], True)
Example #20
0
import bge
import GameLogic
import Rasterizer

gameWidth = Rasterizer.getWindowWidth()
gameHeight = Rasterizer.getWindowHeight()

directionXAxis = -1
directionYAxis = -1

controller = bge.logic.getCurrentController()
owner = controller.owner
parent = owner.parent
mouse = controller.sensors['Mouse']

Rasterizer.setMousePosition(int(gameWidth/2), int(gameHeight/2))

sensitivity = 0.0020

mousePositionX = mouse.position[0] - gameWidth/2
mousePositionY = mouse.position[1] - gameHeight/2

# fix mouse drift on subpixel positions
if mousePositionX == -0.5:
    mousePositionX = 0
if mousePositionY == -0.5:
    mousePositionY = 0

rotXAxis = (mousePositionX * directionXAxis) * sensitivity
rotYAxis = (mousePositionY * directionYAxis) * sensitivity
    else:
        return False


def _click(sensor, key):
    status = sensor.getButtonStatus(key)
    if status == bge.logic.KX_INPUT_JUST_ACTIVATED or status == bge.logic.KX_INPUT_ACTIVE:
        return True
    else:
        return False


WIN_MIDDLE_X = int(Rasterizer.getWindowWidth() / 2)
WIN_MIDDLE_Y = int(Rasterizer.getWindowHeight() / 2)
mx, my = (WIN_MIDDLE_X, WIN_MIDDLE_Y)
Rasterizer.setMousePosition(WIN_MIDDLE_X, WIN_MIDDLE_Y)
change = False
boxrotz = 0


def keyboard_input():
    """
	keyboard_input() est le callback du clavier, il est appelé par le spawn du premier joueur
	"""
    global last_action, first_player, change, mx, boxrotz
    cont = bge.logic.getCurrentController()
    own = cont.owner
    sens = cont.sensors[0]

    change = False
    # doit etre placé à vrai si l'utilisateur effectue un déplacement