def update(task): if s.mouseWatcherNode.is_button_down(KeyboardButton.up()): pingPong("accelerate", -1) elif s.mouseWatcherNode.is_button_down(KeyboardButton.down()): pingPong("accelerate", 1) else: pingPong("accelerate", 0) if s.mouseWatcherNode.is_button_down(KeyboardButton.right()): pingPong("turn", -1) elif s.mouseWatcherNode.is_button_down(KeyboardButton.left()): pingPong("turn", 1) else: pingPong("turn", 0) if s.mouseWatcherNode.is_button_down(KeyboardButton.ascii_key(b'd')): pingPong("strafe", -1) elif s.mouseWatcherNode.is_button_down(KeyboardButton.ascii_key(b'a')): pingPong("strafe", 1) else: pingPong("strafe", 0) if s.mouseWatcherNode.is_button_down(KeyboardButton.ascii_key(b's')): pingPong("hover", 1, 0, 0, 20) else: pingPong("hover", 0, 0, 0, 20) return task.cont
def poll_keyboard(self, velocity): # under normal circumstances, use median of joytick output x_speed = 0.5 y_speed = 0.5 # checks keyboard, not mouse, in this case is_down = self.base.mouseWatcherNode.is_button_down # Instead of usual movement, exactly counteract joystick, # if using joystick and currently moving if self.joystick: if abs(velocity.x) > self.threshold: if velocity.x > 0: x_speed = velocity.x else: x_speed = -velocity.x if abs(velocity.y) > self.threshold: if velocity.y > 0: y_speed = velocity.y else: y_speed = -velocity.y else: velocity.x = 0 velocity.y = 0 if is_down(KeyboardButton.up()): velocity.y += y_speed if is_down(KeyboardButton.down()): velocity.y -= y_speed if is_down(KeyboardButton.left()): velocity.x -= x_speed # print 'keyboard' if is_down(KeyboardButton.right()): velocity.x += x_speed return velocity
def read_keys(self): self.upArrowIsPressed = base.mouseWatcherNode.isButtonDown( KeyboardButton.up()) self.downArrowIsPressed = base.mouseWatcherNode.isButtonDown( KeyboardButton.down()) self.rightArrowIsPressed = base.mouseWatcherNode.isButtonDown( KeyboardButton.right()) self.leftArrowIsPressed = base.mouseWatcherNode.isButtonDown( KeyboardButton.left())
def poll_keyboard(self): x_speed = 0.5 y_speed = 0.5 velocity = LVector3(0) # poorly named, checks keyboard, not mouse, in this case is_down = base.mouseWatcherNode.is_button_down if is_down(KeyboardButton.up()): velocity.y += y_speed if is_down(KeyboardButton.down()): velocity.y -= y_speed if is_down(KeyboardButton.left()): velocity.x -= x_speed if is_down(KeyboardButton.right()): velocity.x += x_speed return velocity
def defineKeys(self): for k in self.keyState.keys(): self.keyState[k] = False if self.isKeyDown(KeyboardButton.up()): self.keyState["WalkFw"] = True if self.isKeyDown(KeyboardButton.down()): self.keyState["WalkBw"] = True if self.isKeyDown(KeyboardButton.left()): self.keyState["RotateL"] = True if self.isKeyDown(KeyboardButton.right()): self.keyState["RotateR"] = True if self.isKeyDown(KeyboardButton.shift()): self.keyState["Run"] = True if self.isKeyDown(KeyboardButton.space()): self.keyState["Jump"] = True if self.isKeyDown(KeyboardButton.asciiKey("d")): self.keyState["Duck"] = True
def poll_keyboard(self): # under normal circumstances, use median of joytick output x_speed = 0.5 y_speed = 0.5 # checks keyboard, not mouse, in this case is_down = self.base.mouseWatcherNode.is_button_down if not self.joystick: self.velocity.x = 0 self.velocity.y = 0 if is_down(KeyboardButton.up()): self.velocity.y += y_speed if is_down(KeyboardButton.down()): self.velocity.y -= y_speed if is_down(KeyboardButton.left()): self.velocity.x -= x_speed # print 'keyboard' if is_down(KeyboardButton.right()): self.velocity.x += x_speed
def update(self, entities_by_filter): left = 0 if base.mouseWatcherNode.is_button_down( KeyboardButton.ascii_key(b'w')): left += 1 if base.mouseWatcherNode.is_button_down( KeyboardButton.ascii_key(b's')): left -= 1 right = 0 if base.mouseWatcherNode.is_button_down(KeyboardButton.up()): right += 1 if base.mouseWatcherNode.is_button_down(KeyboardButton.down()): right -= 1 for entity in entities_by_filter['paddle']: if entity.get_component(Paddle).player == 0: entity.get_component(Movement).value.z = left elif entity.get_component(Paddle).player == 1: entity.get_component(Movement).value.z = right
def update(task): forward, turn, strafe, hover = 0, 0, 0, 0 if s.mouseWatcherNode.is_button_down(KeyboardButton.up()): forward += 1 if s.mouseWatcherNode.is_button_down(KeyboardButton.down()): forward -= 1 if s.mouseWatcherNode.is_button_down(KeyboardButton.left()): turn -= 1 if s.mouseWatcherNode.is_button_down(KeyboardButton.right()): turn += 1 if s.mouseWatcherNode.is_button_down(KeyboardButton.ascii_key(b'a')): strafe -= 1 if s.mouseWatcherNode.is_button_down(KeyboardButton.ascii_key(b'd')): strafe += 1 if s.mouseWatcherNode.is_button_down(KeyboardButton.ascii_key(b's')): hover += 1 animate(forward, turn, strafe, hover) #if s.mouseWatcherNode.is_button_down(KeyboardButton.space()): # control("hover") return task.cont
def update(self, entities_by_filter): for entity in entities_by_filter['paddle']: paddle = entity[Paddle] movement = entity[Movement] # What keys does the player use? if paddle.player == Players.LEFT: up_key = KeyboardButton.ascii_key(b'w') down_key = KeyboardButton.ascii_key(b's') elif paddle.player == Players.RIGHT: up_key = KeyboardButton.up() down_key = KeyboardButton.down() # Read player input delta = 0 if base.mouseWatcherNode.is_button_down(up_key): delta += 1 if base.mouseWatcherNode.is_button_down(down_key): delta -= 1 # Store movement movement.value.z = delta
def move_camera(self, task): rot = globalClock.get_dt() * 360.0 / 3.0 up_down = 0 left_right = 0 if base.mouseWatcherNode.is_button_down(KeyboardButton.up()): up_down -= 1 if base.mouseWatcherNode.is_button_down(KeyboardButton.down()): up_down += 1 if base.mouseWatcherNode.is_button_down(KeyboardButton.left()): left_right -= 1 if base.mouseWatcherNode.is_button_down(KeyboardButton.right()): left_right += 1 if self.rotation_mode and base.mouseWatcherNode.has_mouse(): mouse_pos = base.mouseWatcherNode.get_mouse() mouse_delta = mouse_pos - self.mouse_pos self.mouse_pos = Point2(mouse_pos) up_down += mouse_delta.get_y() * 50 left_right += mouse_delta.get_x() * -50 self.camera_orbit.set_h(self.camera_orbit, left_right * rot) new_pitch = self.camera_pitch.get_p() + up_down * rot self.camera_pitch.set_p(min(max(new_pitch, -89), 89)) return Task.cont
def move_camera(self, task): rot = globalClock.get_dt() * 360.0 / 3.0 up_down = 0 left_right = 0 if base.mouseWatcherNode.is_button_down(KeyboardButton.up()): up_down -= 1 if base.mouseWatcherNode.is_button_down(KeyboardButton.down()): up_down += 1 if base.mouseWatcherNode.is_button_down(KeyboardButton.left()): left_right -=1 if base.mouseWatcherNode.is_button_down(KeyboardButton.right()): left_right +=1 if self.rotation_mode and base.mouseWatcherNode.has_mouse(): mouse_pos = base.mouseWatcherNode.get_mouse() mouse_delta = mouse_pos - self.mouse_pos self.mouse_pos = Point2(mouse_pos) up_down += mouse_delta.get_y() * 50 left_right += mouse_delta.get_x() * -50 self.camera_orbit.set_h(self.camera_orbit, left_right * rot) new_pitch = self.camera_pitch.get_p() + up_down * rot self.camera_pitch.set_p(min(max(new_pitch, -89), 89)) return Task.cont
def __init__(self): # Initialize the ShowBase class from which we inherit, which will # create a window and set up everything we need for rendering into it. ShowBase.__init__(self) self.stimtype='image_sequence' #session_start self.session_start_time = datetime.datetime.now() # self.accept("escape", sys.exit, [0])#don't let the user do this, because then the data isn't saved. self.accept('q', self.close) self.accept('Q', self.close) self.upArrowIsPressed = base.mouseWatcherNode.isButtonDown(KeyboardButton.up()) self.downArrowIsPressed = base.mouseWatcherNode.isButtonDown(KeyboardButton.down()) self.AUTO_REWARD = AUTO_REWARD # disable mouse control so that we can place the camera base.disableMouse() camera.setPosHpr(0, 0, 10, 0, -90, 0) mat=Mat4(camera.getMat()) mat.invertInPlace() base.mouseInterfaceNode.setMat(mat) # base.enableMouse() props = WindowProperties() props.setOrigin(0,0) props.setFullscreen(True) props.setCursorHidden(True) props.setMouseMode(WindowProperties.M_relative) base.win.requestProperties(props) base.setBackgroundColor(0, 0, 0) # set the background color to black #set up the textures # we now get buffer thats going to hold the texture of our new scene altBuffer = self.win.makeTextureBuffer("hello", 1524, 1024) # altBuffer.getDisplayRegion(0).setDimensions(0.5,0.9,0.5,0.8) # altBuffer = base.win.makeDisplayRegion() # altBuffer.makeDisplayRegion(0,1,0,1) # now we have to setup a new scene graph to make this scene self.dr2 = base.win.makeDisplayRegion(0,0.1,0,0.1) altRender = NodePath("new render") # this takes care of setting up ther camera properly self.altCam = self.makeCamera(altBuffer) self.dr2.setCamera(self.altCam) self.altCam.reparentTo(altRender) self.altCam.setPos(0, -10, 0) self.bufferViewer.setPosition("llcorner") # self.bufferViewer.position = (.1,.4,.1,.4) self.bufferViewer.setCardSize(1.0, 0.0) print(self.bufferViewer.position) self.imagesTexture=MovieTexture("image_sequence") # success = self.imagesTexture.read("models/natural_images.avi") success = self.imagesTexture.read("models/movie_5hz.mpg") self.imagesTexture.setPlayRate(1.0) self.imagesTexture.setLoopCount(10) # self.imageTexture =loader.loadTexture("models/NaturalImages/BSDs_8143.tiff") # self.imagesTexture.reparentTo(altRender) cm = CardMaker("stimwindow") cm.setFrame(-4,4,-3,3) # cm.setUvRange(self.imagesTexture) self.card = NodePath(cm.generate()) self.card.reparentTo(altRender) if self.stimtype=='image_sequence': self.card.setTexture(self.imagesTexture,1) # self.imagesTexture.play() # self.bufferViewer.setPosition("lrcorner") # self.bufferViewer.setCardSize(1.0, 0.0) self.accept("v", self.bufferViewer.toggleEnable) self.accept("V", self.bufferViewer.toggleEnable) # Load the tunnel self.initTunnel() #initialize some things # for the tunnel construction: self.boundary_to_add_next_segment = -1 * TUNNEL_SEGMENT_LENGTH self.current_number_of_segments = 8 #task flow booleans self.in_waiting_period = False self.stim_started = False self.looking_for_a_cue_zone = True self.in_reward_window=False self.show_stimulus=False #for task control self.interval=0 self.time_waiting_in_cue_zone=0 self.wait_time=1.83 self.stim_duration= 4.0 # in seconds self.max_stim_duration = 6.0 # in seconds self.stim_elapsed= 0.0 # in seconds self.last_position = base.camera.getZ() self.position_on_track = base.camera.getZ() #for reward control self.reward_window = REWARD_WINDOW # in seconds self.reward_elapsed = 0.0 # self.reward_volume = 0.008 # in mL. this is for the hardcoded 0.1 seconds of reward time self.reward_volume = int(REWARD_VOLUME) # in uL, for the stepper motor self.reward_time = 0.1 # in sec, based on volume. hard coded right now but should be modified by the (1) calibration and (2) optionally by the main loop for dynamic reward scheduling # self.lick_buffer = [] #INITIALIZE NIDAQ self.nidevice = 'Dev2' self.encodervinchannel = 1 self.encodervsigchannel = 0 self.invertdo = False self.diport = 1 self.lickline = 1 self.doport = 0 self.rewardline = 0 self.rewardlines = [0] self.encoder_position_diff = 0 if have_nidaq: self._setupDAQ() self.do.WriteBit(1,1) self.do.WriteBit(3,1)#set reward high, because the logic is flipped somehow. possibly by haphazard wiring of the circuit (12/24/2018 djd) self.previous_encoder_position = self.ai.data[0][self.encodervsigchannel] else: self.previous_encoder_position = 0 self.encoder_gain = -10 #INITIALIZE LICK SENSOR self._lickSensorSetup() #INITIALIZE output data self.lickData = [] self.x = [] self.t = [] self.trialData = [] self.rewardData = [] #INITIALIZE KEY SENSOR, for backup inputs and other user controls self.keys = key.KeyStateHandler() self.accept('r', self._give_reward, [self.reward_volume]) self.accept('l', self._toggle_reward) img_list = glob.glob('models/NaturalImages/*.tiff')[:10] print(img_list) self.imageTextures =[loader.loadTexture(img) for img in img_list] self._setupEyetracking() self._startEyetracking() if AUTO_MODE: self.gameTask = taskMgr.add(self.autoLoop2, "autoLoop2") self.rewardTask = taskMgr.add(self.rewardControl, "reward") self.cue_zone = concatenate((self.cue_zone,arange(\ self.current_number_of_segments*-TUNNEL_SEGMENT_LENGTH,\ self.current_number_of_segments*-TUNNEL_SEGMENT_LENGTH-TUNNEL_SEGMENT_LENGTH-80,\ -1))) self.auto_position_on_track = 0 self.auto_restart = False self.auto_running = True self.contTunnel() else: # Now we create the task. taskMgr is the task manager that actually # calls the function each frame. The add method creates a new task. # The first argument is the function to be called, and the second # argument is the name for the task. It returns a task object which # is passed to the function each frame. self.gameTask = taskMgr.add(self.gameLoop, "gameLoop") # self.stimulusTask = taskMgr.add(self.stimulusControl, "stimulus") self.lickTask = taskMgr.add(self.lickControl, "lick") self.rewardTask = taskMgr.add(self.rewardControl, "reward")
def __init__(self): # Initialize the ShowBase class from which we inherit, which will # create a window and set up everything we need for rendering into it. ShowBase.__init__(self) self.stimtype = 'random image' # session_start self.session_start_time = datetime.datetime.now() # self.accept("escape", sys.exit, [0])#don't let the user do this, because then the data isn't saved. self.accept('q', self.close) self.accept('Q', self.close) self.upArrowIsPressed = base.mouseWatcherNode.isButtonDown(KeyboardButton.up()) self.downArrowIsPressed = base.mouseWatcherNode.isButtonDown(KeyboardButton.down()) self.rightArrowIsPressed = base.mouseWatcherNode.isButtonDown(KeyboardButton.right()) self.leftArrowIsPressed = base.mouseWatcherNode.isButtonDown(KeyboardButton.left()) self.AUTO_REWARD = AUTO_REWARD # disable mouse control so that we can place the camera base.disableMouse() camera.setPosHpr(0, 0, 10, 0, -90, 0) mat = Mat4(camera.getMat()) mat.invertInPlace() base.mouseInterfaceNode.setMat(mat) # base.enableMouse() props = WindowProperties() # props.setOrigin(0, 0) props.setFullscreen(True) props.setCursorHidden(True) props.setMouseMode(WindowProperties.M_relative) base.win.requestProperties(props) base.setBackgroundColor(0, 0, 0) # set the background color to black print('FULSCREEN:') print(props.getFullscreen()) print('=============') # set up the textures # we now get buffer thats going to hold the texture of our new scene altBuffer = self.win.makeTextureBuffer("hello", 1524, 1024) # altBuffer.getDisplayRegion(0).setDimensions(0.5,0.9,0.5,0.8) # altBuffer = base.win.makeDisplayRegion() # altBuffer.makeDisplayRegion(0,1,0,1) # now we have to setup a new scene graph to make this scene self.dr2 = base.win.makeDisplayRegion(0, 0.001, 0, 0.001)#make this really,really small so it's not seeable by the subject altRender = NodePath("new render") # this takes care of setting up ther camera properly self.altCam = self.makeCamera(altBuffer) self.dr2.setCamera(self.altCam) self.altCam.reparentTo(altRender) self.altCam.setPos(0, -10, 0) self.bufferViewer.setPosition("lrcorner") # self.bufferViewer.position = (-.1,-.4,-.1,-.4) self.bufferViewer.setCardSize(1.0, 0.0) print(self.bufferViewer.position) self.imagesTexture = MovieTexture("image_sequence") # success = self.imagesTexture.read("models/natural_images.avi") # success = self.imagesTexture.read("models/movie_5hz.mpg") self.imagesTexture.setPlayRate(1.0) self.imagesTexture.setLoopCount(10) # self.imageTexture =loader.loadTexture("models/NaturalImages/BSDs_8143.tiff") # self.imagesTexture.reparentTo(altRender) self.fixationPoint = OnscreenImage(image='models/fixationpoint.jpg', pos=(0, 0,0),scale=0.01) cm = CardMaker("stimwindow") cm.setFrame(-4, 4, -3, 3) # cm.setUvRange(self.imagesTexture) self.card = NodePath(cm.generate()) self.card.reparentTo(altRender) if self.stimtype == 'image_sequence': self.card.setTexture(self.imagesTexture, 1) # add the score display self.scoreLabel = OnscreenText(text='Current Score:', pos=(-1, 0.9), scale=0.1, fg=(0.8, 0.8, 0.8, 1)) self.scoreText = OnscreenText(text=str(0), pos=(-1, 0.76), scale=0.18, fg=(0, 1, 0, 1), shadow=(0.1, 1, 0.1, 0.5)) self.feebackScoreText = OnscreenText(text='+ ' + str(0), pos=(-0.5, 0.5), scale=0.3, fg=(0, 1, 0, 1), shadow=(0.1, 1, 0.1, 0.5)) self.feebackScoreText.setX(3.) # self.imagesTexture.play() # self.bufferViewer.setPosition("lrcorner") # self.bufferViewer.setCardSize(1.0, 0.0) self.accept("v", self.bufferViewer.toggleEnable) self.accept("V", self.bufferViewer.toggleEnable) # Load the tunnel self.initTunnel() # initialize some things # for the tunnel construction: self.boundary_to_add_next_segment = -1 * TUNNEL_SEGMENT_LENGTH self.current_number_of_segments = 8 # task flow booleans self.in_waiting_period = False self.stim_started = False self.looking_for_a_cue_zone = True self.in_reward_window = False self.show_stimulus = False # for task control self.interval = 0 self.time_waiting_in_cue_zone = 0 self.wait_time = 1.83 self.stim_duration = 0 # in seconds # self.distribution_type = np.random.uniform# # self.distribution_type_inputs = [0.016,0.4] #change the min & max stim duration times #New lines EAS: set weights higher for faster image durations self.durWeights = list() a = np.linspace(0.016,0.4,10) for i,j in enumerate(a): if j<0.1: p1 = 0.25 self.durWeights.append(p1) elif j > 0.1 and j < 0.21: p1 = 0.1 self.durWeights.append(p1) elif j> 0.21: p1 = 0.04 self.durWeights.append(p1) self.rng = np.random.default_rng() a = np.asarray(a) self.distribution_type_inputs = a #subset_size = len(p) #End new lines # self.distribution_type_inputs = [0.05,1.5] #can be anytong should match # self.distribution_type_inputs = [0.016,0.4] #change the min & max stim duration times # self.distribution_type_inputs = [0.016,0.4, 10] #change the min & max stim duration times self.max_stim_duration = 1.0 # in seconds self.stim_elapsed = 0.0 # in seconds self.last_position = base.camera.getZ() self.position_on_track = base.camera.getZ() # for reward control self.reward_window = REWARD_WINDOW # in seconds self.reward_elapsed = 0.0 # self.new_dt = list() # self.reward_volume = 0.008 # in mL. this is for the hardcoded 0.1 seconds of reward time self.reward_volume = int(REWARD_VOLUME) # in uL, for the stepper motor self.reward_time = 0.1 # in sec, based on volume. hard coded right now but should be modified by the (1) calibration and (2) optionally by the main loop for dynamic reward scheduling # self.lick_buffer = [] self.current_score = 0 self.score = 0 self.feedback_score_startime = -2 # INITIALIZE NIDAQ self.nidevice = 'Dev2' self.encodervinchannel = 1 self.encodervsigchannel = 0 self.invertdo = False self.diport = 1 self.lickline = 1 self.doport = 0 self.rewardline = 0 self.rewardlines = [0] self.encoder_position_diff = 0 if have_nidaq: self._setupDAQ() self.do.WriteBit(1, 1) self.do.WriteBit(3, 1) # set reward high, because the logic is flipped somehow. possibly by haphazard wiring of the circuit (12/24/2018 djd) self.previous_encoder_position = self.ai.data[0][self.encodervsigchannel] else: self.previous_encoder_position = 0 self.encoder_gain = 3 # INITIALIZE LICK SENSOR self._lickSensorSetup() # INITIALIZE output data self.lickData = [] self.x = [] self.t = [] self.trialData = [] self.reactionTimeData = [] self.rewardData = [] self.rightKeyData = [] self.leftKeyData = [] self.imageData = [] self.imageTimeData = [] self.scoreData = [] self.trialDurationData = [] self.new_dt = [] # INITIALIZE KEY SENSOR, for backup inputs and other user controls self.keys = key.KeyStateHandler() self.accept('r', self._give_reward, [self.reward_volume]) self.accept('l', self._toggle_reward) # initialize the image list and populate what images you want included # self.img_list = glob.glob('models/2AFC_IMAGES_HUMAN/*.tif') # self.img_list = glob.glob('models/2AFC_IMAGES_HUMAN2/*.tif') # self.img_list = glob.glob('/Users/elizabethstubblefield/Desktop/cheetah_or_elephant/composite_images/masks/all_same_num_ea/*.tif') #Newest images self.img_list = glob.glob('models/all_same_ea/*.tif') #Newest images #No longer hard-coded: self.original_indices = [0,0] #this was manually counted... first number must was the index of the first easy img; was [43, -18] for ndx, name in enumerate(self.img_list): if 'Cheetah255' in name: self.original_indices[0] = ndx elif 'Elephant0' in name: self.original_indices[1] = ndx # print(self.img_list) # self.original_indices = [43,-18] #manually counted, grump #Problematic w/out at least 43 images in the folder self.imageTextures =[loader.loadTexture(img) for img in self.img_list] self.img_id = None #this variable is used so we know which stimulus is being presented self.img_mask = None #this tells us what the image mask being presented is # self._setupEyetracking() # self._startEyetracking() if AUTO_MODE: self.gameTask = taskMgr.add(self.autoLoop2, "autoLoop2") self.rewardTask = taskMgr.add(self.rewardControl, "reward") self.cue_zone = concatenate((self.cue_zone, arange( \ self.current_number_of_segments * -TUNNEL_SEGMENT_LENGTH-50, \ self.current_number_of_segments * -TUNNEL_SEGMENT_LENGTH - TUNNEL_SEGMENT_LENGTH - 100, \ -1))) self.auto_position_on_track = 0 self.auto_restart = False self.auto_running = True self.contTunnel() else: # Now we create the task. taskMgr is the task manager that actually # calls the function each frame. The add method creates a new task. # The first argument is the function to be called, and the second # argument is the name for the task. It returns a task object which # is passed to the function each frame. self.gameTask = taskMgr.add(self.gameLoop, "gameLoop") # self.stimulusTask = taskMgr.add(self.stimulusControl, "stimulus") self.lickTask = taskMgr.add(self.lickControl, "lick") self.rewardTask = taskMgr.add(self.rewardControl, "reward") self.keyTask = taskMgr.add(self.keyControl, "Key press")
def update(self, entities_by_filter): for entity in entities_by_filter['character']: character = entity[CharacterController] character.jumps = False character.sprints = False character.crouches = False character.move.x = 0.0 character.move.y = 0.0 character.heading = 0.0 character.pitch = 0.0 # For debug purposes, emulate analog stick on keyboard # input, being half-way pressed, by holding shift analog = 1 if base.mouseWatcherNode.is_button_down(KeyboardButton.shift()): analog = 0.5 if base.mouseWatcherNode.is_button_down( KeyboardButton.ascii_key("w")): character.move.y += analog if base.mouseWatcherNode.is_button_down( KeyboardButton.ascii_key("s")): character.move.y -= analog if base.mouseWatcherNode.is_button_down( KeyboardButton.ascii_key("a")): character.move.x -= analog if base.mouseWatcherNode.is_button_down( KeyboardButton.ascii_key("d")): character.move.x += analog # Rotation if base.mouseWatcherNode.is_button_down(KeyboardButton.up()): character.pitch += 1 if base.mouseWatcherNode.is_button_down(KeyboardButton.down()): character.pitch -= 1 if base.mouseWatcherNode.is_button_down(KeyboardButton.left()): character.heading += 1 if base.mouseWatcherNode.is_button_down(KeyboardButton.right()): character.heading -= 1 if TurntableCamera in entity: camera = entity[TurntableCamera] camera.heading = camera.pitch = 0 if base.mouseWatcherNode.is_button_down( KeyboardButton.ascii_key("j")): camera.heading = 1 if base.mouseWatcherNode.is_button_down( KeyboardButton.ascii_key("l")): camera.heading = -1 if base.mouseWatcherNode.is_button_down( KeyboardButton.ascii_key("i")): camera.pitch = -1 if base.mouseWatcherNode.is_button_down( KeyboardButton.ascii_key("k")): camera.pitch = 1 # Special movement modes. # By default, you run ("sprint"), unless you press e, in # which case you walk. You can crouch by pressing q; this # overrides walking and running. Jump by pressing space. # This logic is implemented by the Walking system. Here, # only intention is signalled. if base.mouseWatcherNode.is_button_down( KeyboardButton.ascii_key("e")): character.sprints = True if base.mouseWatcherNode.is_button_down( KeyboardButton.ascii_key("c")): character.crouches = True if base.mouseWatcherNode.is_button_down(KeyboardButton.space()): character.jumps = True
def rollTask(self, task): # Standard technique for finding the amount of time since the last # frame #print("\r",self.maze.getR(), self.maze.getP(), self.ballRoot.getPos(), end="") dt = globalClock.getDt() print("\r{:.3} fps ".format(1 / dt), end="") # If dt is large, then there has been a # hiccup that could cause the ball # to leave the field if this functions runs, so ignore the frame if dt > .2: return Task.cont #print(action) if action == "start": a = 1 elif action == "stop": while action == "stop": a = 0 # elif action == "restart": in Line 531 elif action == "coord": a = 1 #ALGUNA CRIDA A METODE DE NARCIS/MARC key_down = base.mouseWatcherNode.is_button_down if self.ready_to_solve: if key_down(KeyboardButton.ascii_key('d')): screenshot = self.camera2_buffer.getScreenshot() if screenshot: v = memoryview(screenshot.getRamImage()).tolist() img = np.array(v, dtype=np.uint8) img = img.reshape( (screenshot.getYSize(), screenshot.getXSize(), 4)) img = img[::-1] #self.digitizer.set_src_img(img) #self.digitizer.digitalize_source() cv2.imshow('img', img) #cv2.waitKey(0) if key_down(KeyboardButton.ascii_key('s')): print("Screenshot!") self.camera2_buffer.saveScreenshot("screenshot.jpg") # The collision handler collects the collisions. We dispatch which function # to handle the collision based on the name of what was collided into for i in range(self.cHandler.getNumEntries()): entry = self.cHandler.getEntry(i) name = entry.getIntoNode().getName() if action == "restart": self.loseGame(entry) if name == "wall_col": self.wallCollideHandler(entry) elif name == "ground_col": self.groundCollideHandler(entry) elif name == "loseTrigger": vr.restart = 1 global th th = threading.Thread(target=listenVoice) th.start() self.loseGame(entry) # Read the mouse position and tilt the maze accordingly # Rotation axes use (roll, pitch, heave) """ if base.mouseWatcherNode.hasMouse(): mpos = base.mouseWatcherNode.getMouse() # get the mouse position self.maze.setP(mpos.getY() * -10) self.maze.setR(mpos.getX() * 10) """ ballPos = self.get_ball_position() #print("BALL POS: ", ballPos) posFPixel = self.path[self.indexPuntActual] xFinal = posFPixel[1] #posFPixel[1]/np.shape(laberint)[0]*13 - 6.5 yFinal = posFPixel[ 0] #-(posFPixel[0]/np.shape(laberint)[1]*13.5 - 6.8) dist = math.sqrt((xFinal - ballPos[1])**2 + (yFinal - ballPos[0])**2) if (dist < self.minDist): if (self.indexPuntActual == len(self.path) - 1): print("SOLVED!!", end="") while (self.aStar.distance( (ballPos[0], ballPos[1]), self.path[self.indexPuntActual]) < self.pas): if (self.indexPuntActual < len(self.path) - 1): self.indexPuntActual += 1 else: break # ball pos (y,x) #print("END POS: ", self.digitizer.endPos) if voice_solving: p_rotation = dir_veu[0] r_rotation = dir_veu[1] if p_rotation == 0 and r_rotation == 0 and ballPos is not None: p_rotation, r_rotation = self.pid.getPR( ballPos[1], ballPos[0], ballPos[1], ballPos[0], self.maze.getP(), self.maze.getR(), dt) else: p_rotation = 0 r_rotation = 0 #print(ballPos, dist) #print(ballPos) if ballPos is not None: p_rotation, r_rotation = self.pid.getPR( ballPos[1], ballPos[0], xFinal, yFinal, self.maze.getP(), self.maze.getR(), dt) #print(p_rotation, r_rotation) if key_down(KeyboardButton.up()): p_rotation = -1 elif key_down(KeyboardButton.down()): p_rotation = 1 if key_down(KeyboardButton.left()): r_rotation = -1 elif key_down(KeyboardButton.right()): r_rotation = 1 self.rotateMaze(p_rotation, r_rotation) # Finally, we move the ball # Update the velocity based on acceleration self.ballV += self.accelV * dt * ACCEL # Clamp the velocity to the maximum speed if self.ballV.lengthSquared() > MAX_SPEED_SQ: self.ballV.normalize() self.ballV *= MAX_SPEED # Update the position based on the velocity self.ballRoot.setPos(self.ballRoot.getPos() + (self.ballV * dt)) #print(self.ballRoot.getPos()) # This block of code rotates the ball. It uses something called a quaternion # to rotate the ball around an arbitrary axis. That axis perpendicular to # the balls rotation, and the amount has to do with the size of the ball # This is multiplied on the previous rotation to incrimentally turn it. prevRot = LRotationf(self.ball.getQuat()) axis = LVector3.up().cross(self.ballV) newRot = LRotationf(axis, 45.5 * dt * self.ballV.length()) self.ball.setQuat(prevRot * newRot) elif key_down(KeyboardButton.ascii_key('1')): self.solve() if key_down(KeyboardButton.ascii_key('i')): self.light.setY(self.light.getY() + 10 * dt) elif key_down(KeyboardButton.ascii_key('k')): self.light.setY(self.light.getY() - 10 * dt) if key_down(KeyboardButton.ascii_key('j')): self.light.setX(self.light.getX() - 10 * dt) elif key_down(KeyboardButton.ascii_key('l')): self.light.setX(self.light.getX() + 10 * dt) if key_down(KeyboardButton.ascii_key('u')): self.lightColor += 10000 * dt self.light.node().setColor( (self.lightColor, self.lightColor, self.lightColor, 1)) elif key_down(KeyboardButton.ascii_key('o')): self.lightColor -= 10000 * dt self.light.node().setColor( (self.lightColor, self.lightColor, self.lightColor, 1)) if key_down(KeyboardButton.ascii_key('8')): self.alightColor += 1 * dt self.ambientL.node().setColor( (self.alightColor, self.alightColor, self.alightColor, 1)) elif key_down(KeyboardButton.ascii_key('9')): self.alightColor -= 1 * dt self.ambientL.node().setColor( (self.alightColor, self.alightColor, self.alightColor, 1)) if key_down(KeyboardButton.ascii_key('r')): base.trackball.node().set_pos(0, 200, 0) base.trackball.node().set_hpr(0, 60, 0) return Task.cont # Continue the task indefinitely
from direct.task import Task from panda3d.core import AmbientLight from panda3d.core import Vec4, Mat4, Point3, Point4, BitMask32 from panda3d.core import LineSegs, NodePath from panda3d.core import LVecBase4, LVecBase2d, InputDevice from pandac.PandaModules import WindowProperties from direct.gui.OnscreenText import OnscreenText from direct.interval.LerpInterval import LerpPosInterval arrow_right = KeyboardButton.right() arrow_left = KeyboardButton.left() arrow_back = KeyboardButton.down() arrow_forward = KeyboardButton.up() GG = LVecBase4(0, 1, 0, 1) # game green constant camera_dict = {"turn_ang_vel": 0.25, "translate_vel": 0.5} NUMET = 2 # number of enemy tanks tanks_dict = { "0": {}, "1": { "init_pos": Point3(30, 50, 0), "color_scale": Point4(0, 0.7, 0, 1.0), "move_params": { "Ax": 25, "Ay": 18, "Bx": -0.15, "By": 0.25, "phix": 10, "phiy": 0