我们从Python开源项目中,提取了以下23个代码示例,用于说明如何使用pygame.K_d()。
def manager(field): put_tile = False for event in pygame.event.get(): if event.type == pygame.QUIT or (event.type == pygame.KEYDOWN and event.dict["key"] == pygame.K_ESCAPE): sys.exit() elif event.type == pygame.KEYDOWN and (event.dict["key"] == pygame.K_RIGHT or event.dict["key"] == pygame.K_d): field.change_right_move(True) elif event.type == pygame.KEYUP and (event.dict["key"] == pygame.K_RIGHT or event.dict["key"] == pygame.K_d): field.change_right_move(False) elif event.type == pygame.KEYDOWN and (event.dict["key"] == pygame.K_LEFT or event.dict["key"] == pygame.K_q): field.change_left_move(True) elif event.type == pygame.KEYUP and (event.dict["key"] == pygame.K_LEFT or event.dict["key"] == pygame.K_q): field.change_left_move(False) elif event.type == pygame.MOUSEBUTTONDOWN and event.dict["button"] == 4: field.change_tile(1) elif event.type == pygame.MOUSEBUTTONDOWN and event.dict["button"] == 5: field.change_tile(-1) elif event.type == pygame.MOUSEBUTTONDOWN and event.dict["button"] == 1: field.put_tile()
def ask(self,question): word="" Text(self.game).draw_text2(self.default,question,green,wth//2,50) #example asking name pygame.display.flip() done = True while done: for event in pygame.event.get(): if event.type==pygame.QUIT: pygame.quit() quit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_a: word+=str(chr(event.key)) if event.key == pygame.K_b: word+=chr(event.key) if event.key == pygame.K_c: word+=chr(event.key) if event.key == pygame.K_d: word+=chr(event.key) if event.key == pygame.K_RETURN: done=False #events... return Text(self.game).draw_text2(self.default,word,green,wth//2,100)
def movement(self, obstacles, offset, i): self.rect[i] += offset collisions = pg.sprite.spritecollide(self, obstacles, False) callback = pg.sprite.collide_mask while pg.sprite.spritecollideany(self, collisions, callback): self.rect[i] += (1 if offset<0 else -1) self.remainder[i] = 0 rand_move = random.choice([pg.K_s, pg.K_a, pg.K_w, pg.K_d]) while rand_move == self.direction: rand_move = random.choice([pg.K_s, pg.K_a, pg.K_w, pg.K_d]) pass self.direction = rand_move if self.direction == pg.K_a: self.direction = pg.K_a self.vector = [-1, 0] elif self.direction == pg.K_w: self.direction = pg.K_w self.vector = [0, -1] elif self.direction == pg.K_s: self.direction = pg.K_s self.vector = [0, 1] elif self.direction == pg.K_d: self.direction = pg.K_d self.vector = [1, 0]
def control_update(self): ''' Uses input from the keyboard to control the player. ''' keys_pressed = pygame.key.get_pressed() action_map = { pygame.K_SPACE: ('hop', INITIAL_HOP), pygame.K_l: ('leap', INITIAL_LEAP), pygame.K_d: ('run', 2), } action = ('run', 0) for key in action_map: if keys_pressed[key]: action = action_map[key] break reward, end_episode = self.simulator.update(action, DT, True) self.total += reward if end_episode: print 'Episode Reward:', self.total self.total = 0.0 self.simulator = Simulator()
def __init__(self): self.down, self.map, self.val, self.scale = [0, 0, 0, 0], [pg.K_a, pg.K_w, pg.K_d, pg.K_s], V2(0, 0), 1
def update(self, screen, event_queue, dt,clock,joystick, netmodel, vizmodel): # Logos/titles screen.blit(self.logo,(screen.get_width() / 4 - 265,screen.get_height() * 3 / 4-500)) screen.blit(self.intel,(screen.get_width() / 4 - 300,screen.get_height()-130)) screen.blit(self.activestate,(screen.get_width() - 980,screen.get_height() - 130)) nextState = self displaytext('Play', 32, screen.get_width() / 4 - 20, screen.get_height() * 3 / 4 - 80, WHITE, screen) displaytext('Train', 32, screen.get_width() / 4 - 20, screen.get_height() * 3 / 4 - 40, WHITE, screen) displaytext('Exit', 32, screen.get_width() / 4 - 20, screen.get_height() * 3 / 4, WHITE, screen) displaytext(u'\u00bb', 32, screen.get_width() / 4 - 60, screen.get_height() * 3 / 4 - 40*self.menu_selection, WHITE, screen) # Each game state processes its own input queue in its own way to avoid messy input logic for event in event_queue: if event.type == pygame.KEYDOWN or event.type == pygame.JOYBUTTONDOWN: if (event.type == pygame.KEYDOWN and (event.key == pygame.K_DOWN)) or (event.type == pygame.JOYBUTTONDOWN and (event.button == 1)) or (event.type == pygame.JOYAXISMOTION and (event.axis == 1 or event.value >= DEADZONE)): self.menu_selection -= 1 if self.menu_selection == -1: self.menu_selection = 2 if (event.type == pygame.KEYDOWN and (event.key == pygame.K_UP)) or (event.type == pygame.JOYBUTTONDOWN and (event.button == 0)) or (event.type == pygame.JOYAXISMOTION and (event.axis == 1 or event.value <= -DEADZONE)): self.menu_selection += 1 if self.menu_selection == 3: self.menu_selection = 0 if (event.type == pygame.KEYDOWN and event.key == pygame.K_RETURN) or (event.type == pygame.JOYBUTTONDOWN and event.button == 11): if self.menu_selection == 2: nextState = Play(False) elif self.menu_selection == 1: nextState = Play(True) else: nextState = None if (event.type == pygame.KEYDOWN and event.key == pygame.K_x): self.ExportModel() if (event.type == pygame.KEYDOWN and event.key == pygame.K_d): self.DumpData() if (event.type == pygame.KEYDOWN and event.key == pygame.K_w): self.DumpWeights() return nextState
def generate_path(self, pointList, up_Z=-1, down_Z=-1): """ Generate path for a line of the image. """ count = 0 toEnd = NOT_ADJUST_THICKNESS start_point = self.robotCoorToPygameCoor( pointList[0] ) for (x, y) in pointList: upZ = self.up_z if up_Z == -1 else up_Z downZ = self.down_z if down_Z == -1 else down_Z if_draw = True end_point = self.robotCoorToPygameCoor( (x, y) ) pygame.draw.line(self.screen, BLACK, start_point, end_point, PYGAME_LINE_WIDTH) pygame.display.update() if not toEnd: pressed_key = self.pygame_wait() if (pressed_key == pygame.K_a): downZ -= Z_THICK_ADJUST pygame.draw.line(self.screen, BLACK, start_point, end_point, PYGAME_THICK_LINE_WIDTH) pygame.display.update() elif (pressed_key == pygame.K_d): downZ += Z_THIN_ADJUST pygame.draw.line(self.screen, WHITE, start_point, end_point, PYGAME_LINE_WIDTH) pygame.draw.line(self.screen, BLACK, start_point, end_point, PYGAME_THIN_LINE_WIDTH) elif (pressed_key == pygame.K_e): toEnd = True elif (pressed_key == pygame.K_p): pygame.draw.line(self.screen, WHITE, start_point, end_point, PYGAME_LINE_WIDTH) if_draw = False start_point = end_point if if_draw: """ Move to the stating point. """ if count == 0: self.create_robot_point(x, y, upZ) self.create_robot_point(x, y, downZ) """ Move to the last point. """ if count == len(pointList) -1: self.create_robot_point(x, y, upZ) count += 1
def setControls(self): """ Setups the controls for the class. setGame must be called first in order for this to run correctly """ self.controls = [] self.values = [self.game.board.callable, self.game.board.mvCurUp, self.game.board.mvCurDown, self.game.board.mvCurLeft, self.game.board.mvCurRight] if self.control_set == "arrows": self.keys = [pygame.K_RETURN, pygame.K_UP, pygame.K_DOWN, pygame.K_LEFT, pygame.K_RIGHT] else: self.keys = [pygame.K_SPACE, pygame.K_w, pygame.K_s, pygame.K_a, pygame.K_d] for i in range(len(self.keys)): self.controls.append([self.keys[i], self.values[i]])
def __init__(self, rect, speed, direction=pg.K_d): pg.sprite.Sprite.__init__(self) self.rect = pg.Rect(rect) self.remainder = [0, 0] #Adjust rect in integers; save remainders. self.mask = self.make_mask() self.speed = speed #Pixels per second; not pixels per frame. self.direction = direction self.old_direction = None #The Players previous direction every frame. self.direction_stack = [] #Held keys in the order they were pressed. self.redraw = False #Force redraw if needed. self.image = None self.angle = -math.radians(135) self.lifes = 6 self.weapon = False self.bullets_left = 0 self.max_bullets = 8 self.sprites = pg.image.load(settings.IMG_DIR + "/player_no_weapon.png").convert_alpha() self.frame = 0 self.frames = self.get_frames() self.animate_timer = 0.0 self.animate_fps = 7.0 self.walkframes = [] self.adjust_images()
def make_frame_dict(self): frames = {pg.K_a: [self.frames[0], self.frames[1], self.frames[2], self.frames[3]], pg.K_d: [self.frames[0], self.frames[1], self.frames[2], self.frames[3]], pg.K_s: [self.frames[0], self.frames[1], self.frames[2], self.frames[3]], pg.K_w: [self.frames[0], self.frames[1], self.frames[2], self.frames[3]]} return frames
def init(): add_key(pygame.K_w) add_key(pygame.K_s) add_key(pygame.K_a) add_key(pygame.K_d) add_key(pygame.K_c) add_key(pygame.K_r) add_key(pygame.K_q) add_key(pygame.K_e) add_key(pygame.K_g) add_key(pygame.K_t) # Adds a new key to be tracked for input
def __init__(self): self._mapping = [ { # Player pygame.K_d:"right", pygame.K_s:"down", pygame.K_q:"left", pygame.K_z:"up" }, { # Player 1 pygame.K_RIGHT:"right", pygame.K_DOWN:"down", pygame.K_LEFT:"left", pygame.K_UP:"up" } ]
def update(self, gamemap): ''' updated die Playerbewegungen beim (knopfdruck events) Parameter: Spielobjekt, gamemap return Value: - ''' keys = pygame.key.get_pressed() newRect = self.rect if keys[pygame.K_w]: newRect = self.rect.move(0, -self.speed) if gamemap.isRectValid(newRect): self.rect = newRect if keys[pygame.K_s]: newRect = self.rect.move(0, self.speed) if gamemap.isRectValid(newRect): self.rect = newRect if keys[pygame.K_a]: newRect = self.rect.move(-self.speed, 0) if gamemap.isRectValid(newRect): self.rect = newRect if keys[pygame.K_d]: newRect = self.rect.move(self.speed, 0) if gamemap.isRectValid(newRect): self.rect = newRect if keys[pygame.K_x]: print self.rect.center, self.room #def shot(self, xPos, yPos, eventPos):
def __init__(self): super(JackitConfigControls, self).__init__() self.up = pygame.K_w self.down = pygame.K_s self.left = pygame.K_a self.right = pygame.K_d self.jump = pygame.K_SPACE self.interact = pygame.K_e self.push = pygame.K_LSHIFT self.reset_code = pygame.K_q self.toggle_sound = pygame.K_m self.kill_self = pygame.K_k self.reset_game = pygame.K_n
def from_json(self, raw): ''' Load the object from JSON loaded from config file ''' # First pass make sure all are valid for key in raw: if isinstance(raw[key], str): if not hasattr(pygame, raw[key]): raise ConfigError( "Invalid control for {}. Must be a valid pygame key constant".format(key) ) else: raw[key] = getattr(pygame, raw[key]) elif isinstance(raw[key], int): pass else: raise ConfigError( "Controls must be a valid pygame key constant as a string or integer" ) # Check for duplicates values = list(raw.values()) values_set = set(values) if len(values) != len(values_set): raise ConfigError("Cannot have duplicate controls") self.up = raw.get('up', getattr(pygame, 'K_w')) self.down = raw.get('down', getattr(pygame, 'K_s')) self.left = raw.get('left', getattr(pygame, 'K_a')) self.right = raw.get('right', getattr(pygame, 'K_d')) self.jump = raw.get('jump', getattr(pygame, 'K_SPACE')) self.interact = raw.get('interact', getattr(pygame, 'K_e')) self.push = raw.get("push", getattr(pygame, "K_LSHIFT")) self.reset_code = raw.get("reset_code", getattr(pygame, "K_q")) self.toggle_sound = raw.get("toggle_sound", getattr(pygame, "K_m")) self.kill_self = raw.get("kill_self", getattr(pygame, "K_k")) self.reset_game = raw.get("reset_game", getattr(pygame, "K_n"))
def update(self, button): keys = pygame.key.get_pressed() if focus == main: elapsed = min(1, self.cds.elapsed("move_keys")) if keys[pygame.K_LEFT] or keys[pygame.K_a]: self.offset[0] = self.offset[0] - (self.key_velocity[0] * elapsed) self.change = True if keys[pygame.K_RIGHT] or keys[pygame.K_d]: self.offset[0] = self.offset[0] + (self.key_velocity[0] * elapsed) self.change = True if keys[pygame.K_UP] or keys[pygame.K_w]: self.offset[1] = self.offset[1] - (self.key_velocity[1] * elapsed) self.change = True if keys[pygame.K_DOWN] or keys[pygame.K_s]: self.offset[1] = self.offset[1] + (self.key_velocity[1] * elapsed) self.change = True self.cds.start() if self.cds.check("save_load"): if keys[pygame.K_q]: save(fnbox.text) self.cds.start() if keys[pygame.K_e]: load(fnbox.text) self.cds.start() if keys[pygame.K_r]: self.new() if self.mmb_down and self.cds.check("navigate"): mpos = pygame.mouse.get_pos() diffx = (mpos[0] - self.mmb_start[0]) / 10 diffy = (mpos[1] - self.mmb_start[1]) / 10 self.offset = [ self.offset[0] + diffx, self.offset[1] + diffy ] self.cds.start() self.change = True
def check_key_down(event, stats, snake_head, snake_parts, foods): if event.key == pygame.K_ESCAPE: sys.exit() elif event.key == pygame.K_p: if stats.game_active: if stats.pause_game: stats.pause_game = False else: stats.pause_game = True else: stats.game_active = True stats.first_start = False initialize_game(stats, snake_head, snake_parts, foods) elif not stats.moved and not stats.pause_game: if event.key == pygame.K_s: if snake_head.facing != "up": snake_head.facing = "down" stats.moved = True elif event.key == pygame.K_w: if snake_head.facing != "down": snake_head.facing = "up" stats.moved = True elif event.key == pygame.K_a: if snake_head.facing != "right": snake_head.facing = "left" stats.moved = True elif event.key == pygame.K_d: if snake_head.facing != "left": snake_head.facing = "right" stats.moved = True
def handleInput(self, sprite, event): if event.type == pygame.KEYDOWN: if event.key == pygame.K_RIGHT or event.key == pygame.K_d: sprite.updateSpeedRight() sprite.rightPressed = True elif event.key == pygame.K_LEFT or event.key == pygame.K_a: sprite.updateSpeedLeft() sprite.leftPressed = True elif event.key == pygame.K_DOWN or event.key == pygame.K_s: sprite.updateSpeedDown() sprite.downPressed = True elif event.key == pygame.K_UP or event.key == pygame.K_w: sprite.updateSpeedUp() sprite.upPressed = True elif event.key == pygame.K_LSHIFT: sprite.leftShiftPressed = True if event.type == pygame.KEYUP: if event.key == pygame.K_RIGHT or event.key == pygame.K_d: sprite.rightPressed = False elif event.key == pygame.K_LEFT or event.key == pygame.K_a: sprite.leftPressed = False elif event.key == pygame.K_UP or event.key == pygame.K_w: sprite.upPressed = False elif event.key == pygame.K_DOWN or event.key == pygame.K_s: sprite.downPressed = False elif event.key == pygame.K_LSHIFT: sprite.leftShiftPressed = False elif event.key == pygame.K_SPACE: sprite.spacePressed = False if event.type == pygame.MOUSEBUTTONDOWN: if event.button == MOUSE_LEFT: sprite.leftMousePressed = True elif event.button == MOUSE_RIGHT: sprite.rightMousePressed = True elif event.type == pygame.MOUSEBUTTONUP: if event.button == MOUSE_LEFT: sprite.leftMousePressed = False elif event.button == MOUSE_RIGHT: sprite.rightMousePressed = False
def process(bug,FPS,total_frames): # processing for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_e: classes.BugAttack.fire = not classes.BugAttack.fire keys = pygame.key.get_pressed() if keys[pygame.K_d]: classes.Bug.going_right = True bug.image = pygame.image.load("images/bug2right.png") bug.velx = 5 elif keys[pygame.K_a]: classes.Bug.going_right = False bug.image = pygame.image.load("images/bug2left.png") bug.velx = -5 else: bug.velx = 0 if keys[pygame.K_w]: bug.jumping = True if keys[pygame.K_SPACE]: if classes.Game.end == True: classes.Game.end = False if classes.Game.start == False: classes.Game.start = True for fly in classes.Fly.List: fly.destroy(classes.Fly) for attack in classes.BugAttack.List: attack.destroy() classes.Fly.count = 0 else: def direction(): if classes.Bug.going_right: p.velx = 6 else: p.image = pygame.transform.flip(p.image, True, False) p.velx = -6 if (classes.BugAttack.fire): p = classes.BugAttack(bug.rect.x,bug.rect.y, "images/fire2.gif") direction() p.velx = p.velx/3.0 else: p = classes.BugAttack(bug.rect.x,bug.rect.y, "images/bolt.gif") direction() if classes.Game.start == True: spawn(FPS,total_frames) collisions(bug)
def userInput(camera, display): deltaT = display.deltaT #keyboard down presses pressed = pygame.key.get_pressed() for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() if event.type == pygame.KEYDOWN: if event.key ==pygame.K_ESCAPE: pygame.quit() quit() if event.type == pygame.MOUSEMOTION: x, y = event.rel event.pos = (display.w/2,display.h/2) #look around if( abs(x)>1 ): camera.turnRight( -x*deltaT) if( abs(y)>1 ): camera.turnUp( -y*deltaT) #capture mouse pygame.mouse.set_pos(display.w/2., display.w/2) pygame.event.get(pygame.MOUSEMOTION) #steal the new mouse event and do nothing with it to reset it #print() #print(camera.posWorld.getString()) #print(camera.view()) #back forth if pressed[pygame.K_w]: camera.forward(deltaT) if pressed[pygame.K_s]: camera.forward(-deltaT) #up, down if pressed[pygame.K_SPACE]: camera.upward(-deltaT) if pressed[pygame.K_LSHIFT]: camera.upward(deltaT) #left right if pressed[pygame.K_a]: camera.sideward(deltaT) if pressed[pygame.K_d]: camera.sideward(-deltaT) #change openGL polygon mode if pressed[pygame.K_1]: glPolygonMode(GL_FRONT_AND_BACK, GL_POINT) if pressed[pygame.K_2]: glPolygonMode(GL_FRONT_AND_BACK, GL_LINE) if pressed[pygame.K_3]: glPolygonMode(GL_FRONT_AND_BACK, GL_FILL) #start the main
def get_input(): for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() if event.type == pygame.KEYUP and event.key == pygame.K_s: state.falling[0] = False if event.type == pygame.KEYUP and event.key == pygame.K_DOWN: state.falling[1] = False if event.type == pygame.KEYDOWN: if state.state == "playing": if event.key == pygame.K_p: state.state = "paused" if event.key == pygame.K_a: if valid(state.X[0] - 1, state.Y[0], state.piece[0].form, 0): state.X[0] -= 1 if event.key == pygame.K_d: if valid(state.X[0] + 1, state.Y[0], state.piece[0].form, 0): state.X[0] += 1 if event.key == pygame.K_LEFT: if valid(state.X[1] - 1, state.Y[1], state.piece[1].form, 1): state.X[1] -= 1 if event.key == pygame.K_RIGHT: if valid(state.X[1] + 1, state.Y[1], state.piece[1].form, 1): state.X[1] += 1 if event.key == pygame.K_w: new_form = Polyomino.rotate_right(state.piece[0].form, state.piece[0].size) if valid(state.X[0], state.Y[0], new_form, 0): state.piece[0].form = new_form if event.key == pygame.K_UP: new_form = Polyomino.rotate_right(state.piece[1].form, state.piece[1].size) if valid(state.X[1], state.Y[1], new_form, 1): state.piece[1].form = new_form if event.key == pygame.K_s: state.falling[0] = True if event.key == pygame.K_DOWN: state.falling[1] = True elif state.state == "paused": if event.key == pygame.K_p: state.state = "playing" elif state.state == "entering high score": if event.key == pygame.K_BACKSPACE and state.cursorpos > 0: state.cursorpos -= 1 state.hiscores[state.scorepos][0] = \ state.hiscores[state.scorepos][0][:state.cursorpos] elif event.key == pygame.K_RETURN: scorefile = open("hiscores_duo.csv", "w") writer = csv.writer(scorefile, dialect = csv.unix_dialect) for row in state.hiscores: writer.writerow(row) scorefile.close() state.start_game() elif (event.unicode.isalpha() or event.key == pygame.K_SPACE) \ and state.cursorpos < INFO_WIDTH - 3 - len(str(state.score)): state.hiscores[state.scorepos][0] = \ state.hiscores[state.scorepos][0][:state.cursorpos] \ + event.unicode state.cursorpos += 1 elif state.state == "lost": if event.key in [pygame.K_SPACE, pygame.K_RETURN]: state.start_game()
def handle_controls(drone, event, pid): # takeoff / land if event.key == pygame.K_RETURN: drone.takeoff() elif event.key == pygame.K_SPACE: drone.land() # emergency elif event.key == pygame.K_BACKSPACE: drone.reset() # forward / backward elif event.key == pygame.K_w: drone.move_forward() elif event.key == pygame.K_s: drone.move_backward() # left / right elif event.key == pygame.K_a: drone.move_left() elif event.key == pygame.K_d: drone.move_right() # up / down elif event.key == pygame.K_UP: drone.move_up() elif event.key == pygame.K_DOWN: drone.move_down() # turn left / turn right elif event.key == pygame.K_LEFT: drone.turn_left() elif event.key == pygame.K_RIGHT: drone.turn_right() # speed elif event.key == pygame.K_1: drone.speed = 0.1 elif event.key == pygame.K_2: drone.speed = 0.2 elif event.key == pygame.K_3: drone.speed = 0.3 elif event.key == pygame.K_4: drone.speed = 0.4 elif event.key == pygame.K_5: drone.speed = 0.5 elif event.key == pygame.K_6: drone.speed = 0.6 elif event.key == pygame.K_7: drone.speed = 0.7 elif event.key == pygame.K_8: drone.speed = 0.8 elif event.key == pygame.K_9: drone.speed = 0.9 elif event.key == pygame.K_0: drone.speed = 1.0 elif event.key == pygame.K_u: pid.enabled = True