Python pygame.KEYDOWN Examples

The following are 30 code examples of pygame.KEYDOWN(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module pygame , or try the search function .
Example #1
Source File: video_looper.py    From pi_video_looper with GNU General Public License v2.0 9 votes vote down vote up
def _handle_keyboard_shortcuts(self):
        while self._running:
            event = pygame.event.wait()
            if event.type == pygame.KEYDOWN:
                # If pressed key is ESC quit program
                if event.key == pygame.K_ESCAPE:
                    self._print("ESC was pressed. quitting...")
                    self.quit()
                if event.key == pygame.K_k:
                    self._print("k was pressed. skipping...")
                    self._player.stop(3)
                if event.key == pygame.K_s:
                    if self._playbackStopped:
                        self._print("s was pressed. starting...")
                        self._playbackStopped = False
                    else:
                        self._print("s was pressed. stopping...")
                        self._playbackStopped = True
                        self._player.stop(3) 
Example #2
Source File: Game3.py    From Games with MIT License 7 votes vote down vote up
def ShowEndInterface(screen, width, height):
	screen.fill(cfg.BACKGROUNDCOLOR)
	font = pygame.font.Font(cfg.FONTPATH, width//15)
	title = font.render('恭喜! 你成功完成了拼图!', True, (233, 150, 122))
	rect = title.get_rect()
	rect.midtop = (width/2, height/2.5)
	screen.blit(title, rect)
	pygame.display.update()
	while True:
		for event in pygame.event.get():
			if (event.type == pygame.QUIT) or (event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE):
				pygame.quit()
				sys.exit()
		pygame.display.update() 
Example #3
Source File: Game3.py    From Games with MIT License 7 votes vote down vote up
def ShowStartInterface(screen, width, height):
	screen.fill(cfg.BACKGROUNDCOLOR)
	tfont = pygame.font.Font(cfg.FONTPATH, width//4)
	cfont = pygame.font.Font(cfg.FONTPATH, width//20)
	title = tfont.render('拼图游戏', True, cfg.RED)
	content1 = cfont.render('按H或M或L键开始游戏', True, cfg.BLUE)
	content2 = cfont.render('H为5*5模式, M为4*4模式, L为3*3模式', True, cfg.BLUE)
	trect = title.get_rect()
	trect.midtop = (width/2, height/10)
	crect1 = content1.get_rect()
	crect1.midtop = (width/2, height/2.2)
	crect2 = content2.get_rect()
	crect2.midtop = (width/2, height/1.8)
	screen.blit(title, trect)
	screen.blit(content1, crect1)
	screen.blit(content2, crect2)
	while True:
		for event in pygame.event.get():
			if (event.type == pygame.QUIT) or (event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE):
				pygame.quit()
				sys.exit()
			elif event.type == pygame.KEYDOWN:
				if event.key == ord('l'): return 3
				elif event.key == ord('m'): return 4
				elif event.key == ord('h'): return 5
		pygame.display.update() 
Example #4
Source File: Game4.py    From Games with MIT License 7 votes vote down vote up
def ShowStartInterface(screen, screensize):
	screen.fill((255, 255, 255))
	tfont = pygame.font.Font(cfg.FONTPATH, screensize[0]//5)
	cfont = pygame.font.Font(cfg.FONTPATH, screensize[0]//20)
	title = tfont.render(u'滑雪游戏', True, (255, 0, 0))
	content = cfont.render(u'按任意键开始游戏', True, (0, 0, 255))
	trect = title.get_rect()
	trect.midtop = (screensize[0]/2, screensize[1]/5)
	crect = content.get_rect()
	crect.midtop = (screensize[0]/2, screensize[1]/2)
	screen.blit(title, trect)
	screen.blit(content, crect)
	while True:
		for event in pygame.event.get():
			if event.type == pygame.QUIT:
				pygame.quit()
				sys.exit()
			elif event.type == pygame.KEYDOWN:
				return
		pygame.display.update() 
Example #5
Source File: gamestart.py    From Games with MIT License 7 votes vote down vote up
def GameStartInterface(screen, sounds, cfg):
	dino = Dinosaur(cfg.IMAGE_PATHS['dino'])
	ground = pygame.image.load(cfg.IMAGE_PATHS['ground']).subsurface((0, 0), (83, 19))
	rect = ground.get_rect()
	rect.left, rect.bottom = cfg.SCREENSIZE[0]/20, cfg.SCREENSIZE[1]
	clock = pygame.time.Clock()
	press_flag = False
	while True:
		for event in pygame.event.get():
			if event.type == pygame.QUIT:
				pygame.quit()
				sys.exit()
			elif event.type == pygame.KEYDOWN:
				if event.key == pygame.K_SPACE or event.key == pygame.K_UP:
					press_flag = True
					dino.jump(sounds)
		dino.update()
		screen.fill(cfg.BACKGROUND_COLOR)
		screen.blit(ground, rect)
		dino.draw(screen)
		pygame.display.update()
		clock.tick(cfg.FPS)
		if (not dino.is_jumping) and press_flag:
			return True 
Example #6
Source File: scan_agent.py    From streetlearn with Apache License 2.0 6 votes vote down vote up
def loop(env, screen, pano_ids_yaws):
  """Main loop of the scan agent."""
  for (pano_id, yaw) in pano_ids_yaws:

    # Retrieve the observation at a specified pano ID and heading.
    logging.info('Retrieving view at pano ID %s and yaw %f', pano_id, yaw)
    observation = env.goto(pano_id, yaw)

    current_yaw = observation["yaw"]
    view_image = interleave(observation["view_image"],
                            FLAGS.width, FLAGS.height)
    graph_image = interleave(observation["graph_image"],
                             FLAGS.width, FLAGS.height)
    screen_buffer = np.concatenate((view_image, graph_image), axis=1)
    pygame.surfarray.blit_array(screen, screen_buffer)
    pygame.display.update()

    for event in pygame.event.get():
      if (event.type == pygame.QUIT or
          (event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE)):
        return
    if FLAGS.save_images:
      filename = 'scan_agent_{}_{}.bmp'.format(pano_id, yaw)
      pygame.image.save(screen, filename) 
Example #7
Source File: Game9.py    From Games with MIT License 6 votes vote down vote up
def GameOver(screen, width, height, score, highest):
	screen.fill((255, 255, 255))
	tfont = pygame.font.Font('./font/simkai.ttf', width//10)
	cfont = pygame.font.Font('./font/simkai.ttf', width//20)
	title = tfont.render('GameOver', True, (255, 0, 0))
	content = cfont.render('Score: %s, Highest: %s' % (score, highest), True, (0, 0, 255))
	trect = title.get_rect()
	trect.midtop = (width/2, height/4)
	crect = content.get_rect()
	crect.midtop = (width/2, height/2)
	screen.blit(title, trect)
	screen.blit(content, crect)
	pygame.display.update()
	while True:
		for event in pygame.event.get():
			if event.type == pygame.QUIT:
				sys.exit()
			elif event.type == pygame.KEYDOWN:
				return 
Example #8
Source File: utils.py    From Games with MIT License 6 votes vote down vote up
def endInterface(screen, color, is_win):
	screen.fill(color)
	clock = pygame.time.Clock()
	if is_win:
		text = 'VICTORY'
	else:
		text = 'FAILURE'
	font = pygame.font.SysFont('arial', 30)
	text_render = font.render(text, 1, (255, 255, 255))
	while True:
		for event in pygame.event.get():
			if event.type == pygame.QUIT:
				pygame.quit()
				sys.exit()
			if (event.type == pygame.KEYDOWN) or (event.type == pygame.MOUSEBUTTONDOWN):
				return
		screen.blit(text_render, (350, 300))
		clock.tick(60)
		pygame.display.update() 
Example #9
Source File: endGame.py    From Games with MIT License 6 votes vote down vote up
def endGame(screen, sounds, showScore, score, number_images, bird, pipe_sprites, backgroud_image, other_images, base_pos, cfg):
	sounds['die'].play()
	clock = pygame.time.Clock()
	while True:
		for event in pygame.event.get():
			if event.type == pygame.QUIT or (event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE):
				pygame.quit()
				sys.exit()
			elif event.type == pygame.KEYDOWN:
				if event.key == pygame.K_SPACE or event.key == pygame.K_UP:
					return
		boundary_values = [0, base_pos[-1]]
		bird.update(boundary_values, float(clock.tick(cfg.FPS))/1000.)
		screen.blit(backgroud_image, (0, 0))
		pipe_sprites.draw(screen)
		screen.blit(other_images['base'], base_pos)
		showScore(screen, score, number_images)
		bird.draw(screen)
		pygame.display.update()
		clock.tick(cfg.FPS) 
Example #10
Source File: skinnedanimation.py    From renpy-shader with MIT License 6 votes vote down vote up
def update(self, frameNumber, editor):
        for event, pos in editor.context.events:
            if event.type == pygame.KEYDOWN:
                bone = editor.getActiveBone()
                key = event.key
                if key == pygame.K_i:
                    if bone:
                        if event.mod & pygame.KMOD_ALT:
                            if bone.name in self.frames[frameNumber].keys:
                                del self.frames[frameNumber].keys[bone.name]
                        else:
                            key = self.frames[frameNumber].getBoneKey(bone.name)
                            copyKeyData(bone, key)
                        self.dirty = True
                elif key == pygame.K_o:
                    if bone:
                        data = self.getBoneData(bone.name)
                        data.repeat = not data.repeat
                        self.dirty = True
                elif key == pygame.K_p:
                    if bone:
                        data = self.getBoneData(bone.name)
                        data.reversed = not data.reversed
                        self.dirty = True 
Example #11
Source File: battle_city_utils.py    From AirGesture with MIT License 6 votes vote down vote up
def gameOverScreen(self):
        """ Show game over screen """

        global screen

        # stop game main loop (if any)
        self.running = False

        screen.fill([0, 0, 0])

        self.writeInBricks("game", [125, 140])
        self.writeInBricks("over", [125, 220])
        pygame.display.flip()

        while 1:
            time_passed = self.clock.tick(50)
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    quit()
                elif event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_RETURN:
                        self.showMenu()
                        return 
Example #12
Source File: waterworld.py    From PyGame-Learning-Environment with MIT License 6 votes vote down vote up
def _handle_player_events(self):
        self.dx = 0
        self.dy = 0
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()

            if event.type == pygame.KEYDOWN:
                key = event.key

                if key == self.actions["left"]:
                    self.dx -= self.AGENT_SPEED

                if key == self.actions["right"]:
                    self.dx += self.AGENT_SPEED

                if key == self.actions["up"]:
                    self.dy -= self.AGENT_SPEED

                if key == self.actions["down"]:
                    self.dy += self.AGENT_SPEED 
Example #13
Source File: puckworld.py    From PyGame-Learning-Environment with MIT License 6 votes vote down vote up
def _handle_player_events(self):
        self.dx = 0.0
        self.dy = 0.0
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()

            if event.type == pygame.KEYDOWN:
                key = event.key

                if key == self.actions["left"]:
                    self.dx -= self.AGENT_SPEED

                if key == self.actions["right"]:
                    self.dx += self.AGENT_SPEED

                if key == self.actions["up"]:
                    self.dy -= self.AGENT_SPEED

                if key == self.actions["down"]:
                    self.dy += self.AGENT_SPEED 
Example #14
Source File: viewer.py    From generals-bot with MIT License 6 votes vote down vote up
def mainViewerLoop(self):
		while not self._receivedUpdate: # Wait for first update
			time.sleep(0.5)

		self._initViewier()

		while self._runPygame:
			for event in pygame.event.get(): # User did something
				if event.type == pygame.QUIT: # User clicked quit
					self._runPygame = False # Flag done
				elif event.type == pygame.MOUSEBUTTONDOWN: # Mouse Click
					self._handleClick(pygame.mouse.get_pos())
				elif event.type == pygame.KEYDOWN: # Key Press Down
					self._handleKeypress(event.key)

			if self._receivedUpdate:
				self._drawViewer()
				self._receivedUpdate = False

			time.sleep(0.2)

		pygame.quit() # Done. Quit pygame. 
Example #15
Source File: tank.py    From Jtyoui with MIT License 5 votes vote down vote up
def get_event(self):
        global SCREEN_WIDTH, SCREEN_HEIGHT
        event_list = pygame.event.get()
        for event in event_list:
            if event.type == pygame.VIDEORESIZE:
                SCREEN_WIDTH, SCREEN_HEIGHT = event.size
                self.window = self.display.set_mode([SCREEN_WIDTH, SCREEN_HEIGHT], pygame.RESIZABLE, 32)

            if event.type == pygame.QUIT:
                self.end_game()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_w:
                    self.my_tank.direction = U
                elif event.key == pygame.K_s:
                    self.my_tank.direction = D
                elif event.key == pygame.K_a:
                    self.my_tank.direction = L
                elif event.key == pygame.K_d:
                    self.my_tank.direction = R
                else:
                    return None
                self.my_tank.move_stop = False
            elif event.type == pygame.MOUSEBUTTONDOWN:
                if len(TankGame.my_bullet_list) < 3:
                    bullet = self.my_tank.fire()
                    load_music('fire')
                    TankGame.my_bullet_list.append(bullet)
            elif event.type == pygame.KEYUP:
                self.my_tank.move_stop = True 
Example #16
Source File: game.py    From Games with MIT License 5 votes vote down vote up
def __nextLevel(self):
		clock = pygame.time.Clock()
		while True:
			for event in pygame.event.get():
				if event.type == pygame.QUIT:
					pygame.quit()
					sys.exit(-1)
				if event.type == pygame.KEYDOWN and event.key == pygame.K_RETURN:
					return
			self.screen.fill(self.cfg.AQUA)
			text = 'Press <Enter> to enter the next level'
			text_render = self.font_big.render(text, False, self.cfg.BLUE)
			self.screen.blit(text_render, ((self.cfg.SCREENWIDTH-text_render.get_rect().width)//2, (self.cfg.SCREENHEIGHT-text_render.get_rect().height)//3))
			pygame.display.flip()
			clock.tick(30) 
Example #17
Source File: game.py    From Games with MIT License 5 votes vote down vote up
def __endInterface(self, is_win):
		if is_win:
			text1 = 'Congratulations! You win!'
		else:
			text1 = 'Game Over! You fail!'
		text2 = 'Press <R> to restart the game'
		text3 = 'Press <Esc> to quit the game.'
		clock = pygame.time.Clock()
		while True:
			for event in pygame.event.get():
				if event.type == pygame.QUIT or (event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE):
					pygame.quit()
					sys.exit(-1)
				if event.type == pygame.KEYDOWN and event.key == pygame.K_r:
					return
			self.screen.fill(self.cfg.AQUA)
			text_render1 = self.font_big.render(text1, False, self.cfg.BLUE)
			text_render2 = self.font_big.render(text2, False, self.cfg.BLUE)
			text_render3 = self.font_big.render(text3, False, self.cfg.BLUE)
			self.screen.blit(text_render1, ((self.cfg.SCREENWIDTH-text_render1.get_rect().width)//2, (self.cfg.SCREENHEIGHT-text_render1.get_rect().height)//4))
			self.screen.blit(text_render2, ((self.cfg.SCREENWIDTH-text_render2.get_rect().width)//2, (self.cfg.SCREENHEIGHT-text_render2.get_rect().height)//2))
			self.screen.blit(text_render3, ((self.cfg.SCREENWIDTH-text_render3.get_rect().width)//2, (self.cfg.SCREENHEIGHT-text_render2.get_rect().height)//1.5))
			pygame.display.flip()
			clock.tick(30) 
Example #18
Source File: Game23.py    From Games with MIT License 5 votes vote down vote up
def main(cfg):
	# 游戏初始化
	pygame.init()
	screen = pygame.display.set_mode(cfg.SCREENSIZE)
	pygame.display.set_caption('2048 —— 微信公众号:Charles的皮卡丘')
	# 播放背景音乐
	pygame.mixer.music.load(cfg.BGMPATH)
	pygame.mixer.music.play(-1)
	# 实例化2048游戏
	game_2048 = Game2048(matrix_size=cfg.GAME_MATRIX_SIZE, max_score_filepath=cfg.MAX_SCORE_FILEPATH)
	# 游戏主循环
	clock = pygame.time.Clock()
	is_running = True
	while is_running:
		screen.fill(pygame.Color(cfg.BG_COLOR))
		# --按键检测
		for event in pygame.event.get():
			if event.type == pygame.QUIT:
				pygame.quit()
				sys.exit()
			elif event.type == pygame.KEYDOWN:
				if event.key in [pygame.K_UP, pygame.K_DOWN, pygame.K_LEFT, pygame.K_RIGHT]:
					game_2048.setDirection({pygame.K_UP: 'up', pygame.K_DOWN: 'down', pygame.K_LEFT: 'left', pygame.K_RIGHT: 'right'}[event.key])
		# --更新游戏状态
		game_2048.update()
		if game_2048.isgameover:
			game_2048.saveMaxScore()
			is_running = False
		# --将必要的游戏元素画到屏幕上
		drawGameMatrix(screen, game_2048.game_matrix, cfg)
		start_x, start_y = drawScore(screen, game_2048.score, game_2048.max_score, cfg)
		drawGameIntro(screen, start_x, start_y, cfg)
		# --屏幕更新
		pygame.display.update()
		clock.tick(cfg.FPS)
	return endInterface(screen, cfg) 
Example #19
Source File: Game24.py    From Games with MIT License 5 votes vote down vote up
def main(cfg):
	# 游戏初始化
	pygame.init()
	screen = pygame.display.set_mode(cfg.SCREENSIZE)
	pygame.display.set_caption('Greedy Snake —— 微信公众号:Charles的皮卡丘')
	clock = pygame.time.Clock()
	# 播放背景音乐
	pygame.mixer.music.load(cfg.BGMPATH)
	pygame.mixer.music.play(-1)
	# 游戏主循环
	snake = Snake(cfg)
	apple = Apple(cfg, snake.coords)
	score = 0
	while True:
		screen.fill(cfg.BLACK)
		# --按键检测
		for event in pygame.event.get():
			if event.type == pygame.QUIT:
				pygame.quit()
				sys.exit()
			elif event.type == pygame.KEYDOWN:
				if event.key in [pygame.K_UP, pygame.K_DOWN, pygame.K_LEFT, pygame.K_RIGHT]:
					snake.setDirection({pygame.K_UP: 'up', pygame.K_DOWN: 'down', pygame.K_LEFT: 'left', pygame.K_RIGHT: 'right'}[event.key])
		# --更新贪吃蛇和食物
		if snake.update(apple):
			apple = Apple(cfg, snake.coords)
			score += 1
		# --判断游戏是否结束
		if snake.isgameover: break
		# --显示游戏里必要的元素
		drawGameGrid(cfg, screen)
		snake.draw(screen)
		apple.draw(screen)
		showScore(cfg, score, screen)
		# --屏幕更新
		pygame.display.update()
		clock.tick(cfg.FPS)
	return endInterface(screen, cfg) 
Example #20
Source File: gameend.py    From Games with MIT License 5 votes vote down vote up
def GameEndInterface(screen, cfg):
	replay_image = pygame.image.load(cfg.IMAGE_PATHS['replay'])
	replay_image = pygame.transform.scale(replay_image, (35, 31))
	replay_image_rect = replay_image.get_rect()
	replay_image_rect.centerx = cfg.SCREENSIZE[0] / 2
	replay_image_rect.top = cfg.SCREENSIZE[1] * 0.52
	gameover_image = pygame.image.load(cfg.IMAGE_PATHS['gameover'])
	gameover_image = pygame.transform.scale(gameover_image, (190, 11))
	gameover_image_rect = gameover_image.get_rect()
	gameover_image_rect.centerx = cfg.SCREENSIZE[0] / 2
	gameover_image_rect.centery = cfg.SCREENSIZE[1] * 0.35
	clock = pygame.time.Clock()
	while True:
		for event in pygame.event.get():
			if event.type == pygame.QUIT:
				pygame.quit()
				sys.exit()
			elif event.type == pygame.KEYDOWN:
				if event.key == pygame.K_SPACE or event.key == pygame.K_UP:
					return True
			elif event.type == pygame.MOUSEBUTTONDOWN:
				mouse_pos = pygame.mouse.get_pos()
				if replay_image_rect.collidepoint(mouse_pos):
					return True
		screen.blit(replay_image, replay_image_rect)
		screen.blit(gameover_image, gameover_image_rect)
		pygame.display.update()
		clock.tick(cfg.FPS) 
Example #21
Source File: startGame.py    From Games with MIT License 5 votes vote down vote up
def startGame(screen, sounds, bird_images, other_images, backgroud_image, cfg):
	base_pos = [0, cfg.SCREENHEIGHT*0.79]
	base_diff_bg = other_images['base'].get_width() - backgroud_image.get_width()
	msg_pos = [(cfg.SCREENWIDTH-other_images['message'].get_width())/2, cfg.SCREENHEIGHT*0.12]
	bird_idx = 0
	bird_idx_change_count = 0
	bird_idx_cycle = itertools.cycle([0, 1, 2, 1])
	bird_pos = [cfg.SCREENWIDTH*0.2, (cfg.SCREENHEIGHT-list(bird_images.values())[0].get_height())/2]
	bird_y_shift_count = 0
	bird_y_shift_max = 9
	shift = 1
	clock = pygame.time.Clock()
	while True:
		for event in pygame.event.get():
			if event.type == pygame.QUIT or (event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE):
				pygame.quit()
				sys.exit()
			elif event.type == pygame.KEYDOWN:
				if event.key == pygame.K_SPACE or event.key == pygame.K_UP:
					return {'bird_pos': bird_pos, 'base_pos': base_pos, 'bird_idx': bird_idx}
		sounds['wing'].play()
		bird_idx_change_count += 1
		if bird_idx_change_count % 5 == 0:
			bird_idx = next(bird_idx_cycle)
			bird_idx_change_count = 0
		base_pos[0] = -((-base_pos[0] + 4) % base_diff_bg)
		bird_y_shift_count += 1
		if bird_y_shift_count == bird_y_shift_max:
			bird_y_shift_max = 16
			shift = -1 * shift
			bird_y_shift_count = 0
		bird_pos[-1] = bird_pos[-1] + shift
		screen.blit(backgroud_image, (0, 0))
		screen.blit(list(bird_images.values())[bird_idx], bird_pos)
		screen.blit(other_images['message'], msg_pos)
		screen.blit(other_images['base'], base_pos)
		pygame.display.update()
		clock.tick(cfg.FPS) 
Example #22
Source File: Game17.py    From Games with MIT License 5 votes vote down vote up
def endInterface(screen, score_left, score_right):
	clock = pygame.time.Clock()
	font1 = pygame.font.Font(config.FONTPATH, 30)
	font2 = pygame.font.Font(config.FONTPATH, 20)
	msg = 'Player on left won!' if score_left > score_right else 'Player on right won!'
	texts = [font1.render(msg, True, config.WHITE),
			 font2.render('Press ESCAPE to quit.', True, config.WHITE),
			 font2.render('Press ENTER to continue or play again.', True, config.WHITE)]
	positions = [[120, 200], [155, 270], [80, 300]]
	while True:
		screen.fill((41, 36, 33))
		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_RETURN:
					return
				elif event.key == pygame.K_ESCAPE:
					sys.exit()
					pygame.quit()
		for text, pos in zip(texts, positions):
			screen.blit(text, pos)
		clock.tick(10)
		pygame.display.update() 
Example #23
Source File: game_main.py    From Python24 with MIT License 5 votes vote down vote up
def __event(self):
        # 获取所有窗口中的事件监听 -> 列表
        event_list = pygame.event.get()
        # 遍历所有的事件
        for event in event_list:
            # 如果是鼠标点击关闭事件
            if event.type == pygame.QUIT:
                self.game_over()

            # 监听按下事件
            if event.type == pygame.KEYDOWN:
                # 是否按下的是Esc
                if event.key == pygame.K_ESCAPE:
                    self.game_over()
                # 是否按下的是空格
                if event.key == pygame.K_SPACE:
                    self.hero_plane.shoot()

        # 监听键盘长按事件 -> 元组(0没按下,1长按了) 字母对应阿斯克码
        pressed_keys = pygame.key.get_pressed()

        # 判断向上是否被长按(1)
        if pressed_keys[pygame.K_UP] or pressed_keys[pygame.K_w]:
            self.hero_plane.move_up()

        # 判断向下是否被长按(1)
        if pressed_keys[pygame.K_DOWN] or pressed_keys[pygame.K_s]:
            self.hero_plane.move_down()

        # 判断向左是否被长按(1)
        if pressed_keys[pygame.K_LEFT] or pressed_keys[pygame.K_a]:
            self.hero_plane.move_left()

        # 判断向右是否被长按(1)
        if pressed_keys[pygame.K_RIGHT] or pressed_keys[pygame.K_d]:
            self.hero_plane.move_right()

    # 4- 刷新窗口 
Example #24
Source File: 六个类合一.py    From Python24 with MIT License 5 votes vote down vote up
def __event(self):
        # 获取所有窗口中的事件监听 -> 列表
        event_list = pygame.event.get()
        # 遍历所有的事件
        for event in event_list:
            # 如果是鼠标点击关闭事件
            if event.type == pygame.QUIT:
                self.game_over()

            # 监听按下事件
            if event.type == pygame.KEYDOWN:
                # 是否按下的是Esc
                if event.key == pygame.K_ESCAPE:
                    self.game_over()
                # 是否按下的是空格
                if event.key == pygame.K_SPACE:
                    self.hero_plane.shoot()

        # 监听键盘长按事件 -> 元组(0没按下,1长按了) 字母对应阿斯克码
        pressed_keys = pygame.key.get_pressed()

        # 判断向上是否被长按(1)
        if pressed_keys[pygame.K_UP] or pressed_keys[pygame.K_w]:
            self.hero_plane.move_up()

        # 判断向下是否被长按(1)
        if pressed_keys[pygame.K_DOWN] or pressed_keys[pygame.K_s]:
            self.hero_plane.move_down()

        # 判断向左是否被长按(1)
        if pressed_keys[pygame.K_LEFT] or pressed_keys[pygame.K_a]:
            self.hero_plane.move_left()

        # 判断向右是否被长按(1)
        if pressed_keys[pygame.K_RIGHT] or pressed_keys[pygame.K_d]:
            self.hero_plane.move_right()

    # 4- 刷新窗口 
Example #25
Source File: draw.py    From rpisurv with GNU General Public License v2.0 5 votes vote down vote up
def check_keypress():
    try:
        for event in pygame.event.get():
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_q or event.key == pygame.K_a or event.key == pygame.K_KP_DIVIDE or event.key == pygame.K_BACKSPACE:
                    logger.debug("Keypress 'a' or 'q' or 'backspace' or 'keypad /' detected.")
                    return "end_event"
                if event.key == pygame.K_n or event.key == pygame.K_SPACE or event.key == pygame.K_KP_PLUS:
                    logger.debug("Keypress 'n' or 'space' or 'keypad +' detected.")
                    return "next_event"
                if event.key == pygame.K_r or event.key == pygame.K_KP_PERIOD or event.key == pygame.K_COMMA:
                    logger.debug("Keypress 'r' or ',' or 'keypad .' detected")
                    return "resume_rotation"
                if event.key == pygame.K_p or event.key == pygame.K_KP_MULTIPLY:
                    logger.debug("Keypress 'p' or 'keypad *' detected")
                    return "pause_rotation"
                for numeric_key_counter, key in enumerate([pygame.K_F1,pygame.K_F2,pygame.K_F3,pygame.K_F4,pygame.K_F5,pygame.K_F6,pygame.K_F7,pygame.K_F8,pygame.K_F9,pygame.K_F10,pygame.K_F11,pygame.K_F12]):
                    if event.key == key:
                        logger.debug("Keypress 'F" + str(numeric_key_counter + 1) + "' detected")
                        return numeric_key_counter
                for numeric_key_counter, key in enumerate([pygame.K_KP0,pygame.K_KP1,pygame.K_KP2,pygame.K_KP3,pygame.K_KP4,pygame.K_KP5,pygame.K_KP6,pygame.K_KP7,pygame.K_KP8,pygame.K_KP9]):
                    if event.key == key:
                        logger.debug("Keypress 'keypad " + str(numeric_key_counter + 1) + "' detected")
                        return numeric_key_counter
                else:
                    return None
    except pygame.error as e:
        logger.debug("Exception " + repr(e))
        exit(0) 
Example #26
Source File: viewfinder.py    From viewfinder with Apache License 2.0 5 votes vote down vote up
def ProcessMotion(vf_time):
  """Process pygame events for the window. Mousedown in the target area
  starts the simulation. Mouse movement is reported to the 'vf_time' arg
  to adjust the current time. Mouseup stop the simulation.
  """
  last_pos = None
  for event in pygame.event.get():
    if event.type == pygame.QUIT or event.type == pygame.KEYDOWN:
      return sys.exit(0)
    if vf_time.IsActive():
      if event.type == pygame.MOUSEMOTION:
        if event.buttons[0]:
          last_pos = event.pos
      elif event.type == pygame.MOUSEBUTTONUP:
        if event.button == 1:
          vf_time.Stop()
    else:
      if event.type == pygame.MOUSEBUTTONDOWN:
        if event.button == 1:
          pos = PixelsToDimensions(event.pos)
          x, y = pos
          if x > iphone_dims[0] - target_box_width - target_box_padding and \
                x < iphone_dims[0] - target_box_padding and \
                y > target_box_padding and \
                y < iphone_dims[1] - target_box_padding:
            vf_time.Start(pos)

  if last_pos:
    vf_time.AdjustTime(PixelsToDimensions(last_pos)) 
Example #27
Source File: timeline.py    From viewfinder with Apache License 2.0 5 votes vote down vote up
def ProcessMotion(active, last_pos):
  new_pos = last_pos
  for event in pygame.event.get():
    if event.type == pygame.QUIT or event.type == pygame.KEYDOWN:
      return sys.exit(0)
    if active:
      if event.type == pygame.MOUSEMOTION:
        if event.buttons[0]:
          new_pos = event.pos
      elif event.type == pygame.MOUSEBUTTONUP:
        if event.button == 1:
          active = False
    else:
      if event.type == pygame.MOUSEBUTTONDOWN:
        if event.button == 1:
          x_pos, y_pos = [float(pos) / dim for pos, dim in zip(event.pos, window_dimensions)]
          if x_pos > (1.0 - target_box_width - target_box_padding) and \
                x_pos < (1.0 - target_box_padding) and \
                y_pos > target_box_padding and \
                y_pos < 1.0 - target_box_padding:
            active = True
            new_pos = event.pos

  x_ratio = EnforceBounds(float(new_pos[0]) / window_dimensions[0], 0.0, 1.0)
  old_y_ratio = EnforceBounds(float(last_pos[1]) / window_dimensions[1], 0.0, 1.0)
  y_ratio = EnforceBounds(float(new_pos[1]) / window_dimensions[1], 0.0, 1.0)
  y_delta = y_ratio - old_y_ratio

  return active, new_pos, x_ratio, y_ratio, y_delta 
Example #28
Source File: viewfinder.py    From viewfinder with Apache License 2.0 5 votes vote down vote up
def ProcessMotion(vf_time):
  """Process pygame events for the window. Mousedown in the target area
  starts the simulation. Mouse movement is reported to the 'vf_time' arg
  to adjust the current time. Mouseup stop the simulation.
  """
  last_pos = None
  for event in pygame.event.get():
    if event.type == pygame.QUIT or event.type == pygame.KEYDOWN:
      return sys.exit(0)
    if vf_time.IsActive():
      if event.type == pygame.MOUSEMOTION:
        if event.buttons[0]:
          last_pos = event.pos
      elif event.type == pygame.MOUSEBUTTONUP:
        if event.button == 1:
          vf_time.Stop()
    else:
      if event.type == pygame.MOUSEBUTTONDOWN:
        if event.button == 1:
          pos = PixelsToDimensions(event.pos)
          x, y = pos
          if x > iphone_dims[0] - target_box_width - target_box_padding and \
                x < iphone_dims[0] - target_box_padding and \
                y > target_box_padding and \
                y < iphone_dims[1] - target_box_padding:
            vf_time.Start(pos)

  if last_pos:
    vf_time.AdjustTime(PixelsToDimensions(last_pos)) 
Example #29
Source File: timeline.py    From viewfinder with Apache License 2.0 5 votes vote down vote up
def ProcessMotion(active, last_pos):
  new_pos = last_pos
  for event in pygame.event.get():
    if event.type == pygame.QUIT or event.type == pygame.KEYDOWN:
      return sys.exit(0)
    if active:
      if event.type == pygame.MOUSEMOTION:
        if event.buttons[0]:
          new_pos = event.pos
      elif event.type == pygame.MOUSEBUTTONUP:
        if event.button == 1:
          active = False
    else:
      if event.type == pygame.MOUSEBUTTONDOWN:
        if event.button == 1:
          x_pos, y_pos = [float(pos) / dim for pos, dim in zip(event.pos, window_dimensions)]
          if x_pos > (1.0 - target_box_width - target_box_padding) and \
                x_pos < (1.0 - target_box_padding) and \
                y_pos > target_box_padding and \
                y_pos < 1.0 - target_box_padding:
            active = True
            new_pos = event.pos

  x_ratio = EnforceBounds(float(new_pos[0]) / window_dimensions[0], 0.0, 1.0)
  old_y_ratio = EnforceBounds(float(last_pos[1]) / window_dimensions[1], 0.0, 1.0)
  y_ratio = EnforceBounds(float(new_pos[1]) / window_dimensions[1], 0.0, 1.0)
  y_delta = y_ratio - old_y_ratio

  return active, new_pos, x_ratio, y_ratio, y_delta 
Example #30
Source File: battle_city_utils.py    From AirGesture with MIT License 5 votes vote down vote up
def animateIntroScreen(self):
        """ Slide intro (menu) screen from bottom to top
        If Enter key is pressed, finish animation immediately
        @return None
        """

        global screen

        self.drawIntroScreen(False)
        screen_cp = screen.copy()

        screen.fill([0, 0, 0])

        y = 416
        while (y > 0):
            time_passed = self.clock.tick(50)
            for event in pygame.event.get():
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_RETURN:
                        y = 0
                        break

            screen.blit(screen_cp, [0, y])
            pygame.display.flip()
            y -= 5

        screen.blit(screen_cp, [0, 0])
        pygame.display.flip()