示例#1
0
def run_game():
    pygame.init()
    settings = Settings()
    os.environ["SDL_VIDEO_WINDOW_POS"] = "%d, %d" % (settings.screen_left,
                                                     settings.screen_top)
    screen = pygame.display.set_mode(
        (settings.screen_width, settings.screen_height))
    pygame.display.set_caption('外星人入侵')
    ship = Ship(screen, settings.ship_speed_factor)
    bullets = Group()
    aliens = Group()
    gf.creat_aliens(aliens, screen, settings)
    status = GameStatus(settings)
    game_info = GameInfo(screen, ship, settings, 0, len(aliens), status)
    buttons = Buttons(screen)
    pop_msg = ScreenPopMsg(screen)

    while True:
        gf.check_events(screen, ship, aliens, settings, bullets, buttons,
                        status, game_info)
        gf.check_game_status(status)
        if status.game_alive == 2:
            gf.check_game_hit(ship, aliens, bullets, status,
                              settings.screen_height, game_info)
            ship.update()
            gf.update_bullets(bullets)
            gf.update_aliens(aliens, bullets, screen, settings,
                             status.game_alive)
            game_info.prep_statusbar(len(bullets), len(aliens))
            gf.check_fire(bullets, aliens, settings, status, game_info)

        gf.update_screen(settings, screen, ship, game_info, bullets, aliens,
                         buttons, status, pop_msg)
示例#2
0
文件: game.py 项目: jkamuda/protomonk
    def __init__(self):
        # Center window on screen
        os.environ['SDL_VIDEO_CENTERED'] = '1'

        pygame.init()

        self.caption = 'NES Mario'

        size = [constants.SCREEN_WIDTH, constants.SCREEN_HEIGHT]
        self.screen = pygame.display.set_mode(size)

        self.game_info = GameInfo()
        self.sound_manager = SoundManager()
    def get_stats(player, gateway):
        if gateway not in GatewayList:
            raise ValueError('Invalid Gateway')

        try:
            # try grabbing stats from battle.net
            url = 'http://classic.battle.net/war3/ladder/' + GameInfo.get_game_version_str(
            ) + '-player-profile.aspx?Gateway=' + gateway + '&PlayerName=' + player.name
            page = urlopen(url, timeout=10)
            soup = BeautifulSoup(page, 'html.parser')
            BNetStatsScraper.__get_stat(soup, player.solo_stats, 'Solo Games')
            BNetStatsScraper.__get_stat(soup, player.team_stats, 'Team Games')
            BNetStatsScraper.__get_stat(soup, player.ffa_stats, 'FFA Games')
        except:
            try:
                # fallback top 1000 stats from warcraft 3
                url = 'https://warcraft3.info/stats/bnet_data?server=' + gateway
                response = requests.get(url, timeout=5)
                if response.status_code == requests.codes.ok:
                    for entry in response.json()['ranking']:
                        if entry['name'] is None or entry['name'] is '':
                            continue
                        if entry['name'].lower() == player.name.lower():
                            player.solo_stats.wins = entry['wins']
                            player.solo_stats.losses = entry['losses']
                            player.solo_stats.winrate = entry['winrate']
                            player.team_stats.wins = player.ffa_stats.wins = -1
                            break
            except:
                player.solo_stats.wins = player.team_stats.wins = player.ffa_stats.wins = -1
示例#4
0
 def get_list(self, start_url):
     """从列表爬取信息"""
     first_page_i = 18
     last_page_i = 25
     url = start_url + str(first_page_i)
     self.get_page(url)
     first_of_last_list = None
     for page_i in range(first_page_i, last_page_i + 1):
         while True:
             body_content = self.get_bs()
             game_info_page_urls = body_content.find_all("a", "permalink")
             if not game_info_page_urls:
                 sleep(1)
                 continue
             first = game_info_page_urls[0]["href"]
             if first_of_last_list is None or game_info_page_urls and first != first_of_last_list:
                 first_of_last_list = first
                 break
             print("[Warning]", first, "and", first_of_last_list,
                   "are the same")
             sleep(3)
         for a in game_info_page_urls:
             url = "https://store.playstation.com/" + a["href"]
             cid = self.get_cid_from_url(url)
             if self.session.query(GameInfo).filter(
                     GameInfo.cid == cid).first() is None:
                 g = GameInfo(cid=cid,
                              url=url,
                              update_datetime=datetime.now())
                 self.session.add(g)
         self.session.commit()
         print("# parsed list in page:", page_i)
         self.next_page()  # 加载下一页
     self.driver.close()
示例#5
0
    def reset(self,
              scored=False,
              puck_was_hit=False,
              puck_is_at_the_bottom=False,
              distance_decreased=False,
              hit_the_border=False):

        draw_puck = self.use_object['puck']
        draw_top_mallet = self.use_object['top_mallet']

        # 重置冰球、两个击球器的位置
        if draw_puck:
            # self.puck.reset(self.dim, self.dim.rink_top, self.dim.center[1])
            # self.puck.reset(self.dim, self.dim.center[1], self.dim.rink_bottom-self.dim.mallet_radius-10) # 将冰球置于中线以下
            self.puck.reset(self.dim,
                            self.dim.rink_top + self.dim.mallet_radius + 10,
                            self.dim.center[1])
            # self.puck.reset(self.dim, self.dim.rink_top - self.dim.mallet_radius , self.dim.rink_top - self.dim.mallet_radius+1)
            self.bottom_mallet.reset(self.dim, self.dim.center[1],
                                     self.dim.rink_bottom)

        if draw_top_mallet:
            self.top_mallet.reset(self.dim, self.dim.rink_top,
                                  self.dim.center[1])

        self.motions.clear_all_motions()

        # Resolve possible interpenetration
        Collision.circle_circle([self.puck, self.top_mallet])
        Collision.circle_circle([self.top_mallet, self.bottom_mallet])
        # 计算小球是否在bottom_target这个圆圈里
        in_the_target = Collision.circle_circle(
            [self.bottom_mallet, self.bottom_target], resolve=False)

        # 读取贴图
        # self.sprites, self.dominant_arm = load_sprites()
        # 画图
        self.render()

        puck_position = self.puck.get_position()
        puck_velocity = V.address_data(self.puck.get_velocity())
        bottom_mallet_position = self.bottom_mallet.get_position()
        bottom_mallet_velocity = V.address_data(
            self.bottom_mallet.get_velocity())
        top_mallet_position = self.top_mallet.get_position()
        top_mallet_velocity = V.address_data(self.top_mallet.get_velocity())

        puck_position_mode = bool(
            self.dim.center[1] <= puck_position[1] <= self.dim.rink_bottom)
        game_info = GameInfo([], puck_position, puck_velocity,
                             bottom_mallet_position, bottom_mallet_velocity,
                             top_mallet_position, top_mallet_velocity,
                             puck_was_hit, puck_is_at_the_bottom,
                             distance_decreased, hit_the_border, in_the_target,
                             puck_position_mode)

        return game_info
  def get_stats(player, gateway):
    if gateway not in GatewayList:
      raise ValueError('Invalid Gateway')

    page = urlopen('http://classic.battle.net/war3/ladder/' + GameInfo.get_game_version_str() + '-player-profile.aspx?Gateway=' + gateway + '&PlayerName=' + player.name)
    soup = BeautifulSoup(page, 'html.parser')
    BNetStatsScraper.__get_stat(soup, player.solo_stats, 'Solo Games')
    BNetStatsScraper.__get_stat(soup, player.team_stats, 'Team Games')
    BNetStatsScraper.__get_stat(soup, player.ffa_stats, 'FFA Games')
示例#7
0
    def step(self,
             robot_action=None,
             human_action=None,
             debug=False,
             n_steps=4):

        dt = 0.25  # dt is randomly in interval [1, 2)
        time_iter = dt * n_steps

        # 记录上一步的游戏状态
        past_bottom_pos = self.bottom_mallet.get_position()

        # 如果输入参数是None,就使用AI move
        if robot_action is None:
            if self.use_object['puck']:
                # robot_action = self.bottom_ai.move()
                robot_action = [0, 0]
            else:
                robot_action = [0, 0]
        if human_action is None:
            if self.use_object['top_mallet']:
                human_action = self.top_ai.move()
                # human_action = [0, 0]
            elif not self.use_object['puck']:
                human_action = [0, 0]
            else:
                human_action = [0, 0]

        self.bot_mallet_motion.set_motion(robot_action)
        self.top_mallet_motion.set_motion(self.top_ai.move())
        # self.bottom_ai_motion.update_motion(robot_action)

        # 用数组来储存n_steps循环中
        # puck_was_hit 和 border_was_hit 和 scored 的值

        n_puck_was_hit = np.zeros(n_steps, dtype=np.float32)
        n_hit_the_border = np.zeros(n_steps, dtype=np.float32)
        n_score_flag = np.zeros(n_steps, dtype=np.float32)

        for k in range(n_steps):

            # Clear forces from last frame
            for body in self.bodies:
                body.clear_accumulated_v()

            self.motions.update_motions()

            # Move bodies
            for body in self.bodies:
                body.speed_position_update(dt)

            # Check collisions between all possible pairs of bodies
            if self.use_object['top_mallet']:
                Collision.circle_circle([self.puck, self.top_mallet])

            Collision.circle_circle([self.top_mallet, self.bottom_mallet])

            if self.use_object['puck']:
                n_puck_was_hit[k] = bool(
                    Collision.circle_circle([self.puck, self.bottom_mallet]))
            else:
                n_puck_was_hit[k] = False

            in_the_target = Collision.circle_circle(
                [self.bottom_mallet, self.bottom_target], resolve=False)

            # Make sure all bodies are within their borders
            collided = [False, False, False]
            for i, body in enumerate(self.bodies):
                for border in body.borders:
                    if Collision.circle_line(body, border):
                        collided[i] = True
            n_hit_the_border[k] = collided[2]

            puck_is_at_the_bottom = self.puck.position[1] > self.dim.center[1]

            distance_decreased = False
            if puck_is_at_the_bottom:
                distance = V.magnitude(self.puck.position -
                                       self.bottom_mallet.position)
                distance_decreased = distance < self.distance
                self.distance = distance
            else:
                self.distance = P.max_distance

            _, n_score_flag[k] = self.score.update(self.puck)

        puck_position = self.puck.get_position()
        puck_velocity = V.address_data(self.puck.get_velocity())
        bottom_mallet_position = self.bottom_mallet.get_position()
        bottom_mallet_velocity = V.address_data(
            self.bottom_mallet.get_velocity())
        for i in range(len(past_bottom_pos)):
            if np.linalg.norm(past_bottom_pos[i] -
                              self.bottom_mallet.get_position()[i]) < 1e-5:
                bottom_mallet_velocity[i] = 0
            else:
                pass
        top_mallet_position = self.top_mallet.get_position()
        top_mallet_velocity = V.address_data(self.top_mallet.get_velocity())
        puck_was_hit = np.any(n_puck_was_hit == 1)
        hit_the_border = np.any(n_hit_the_border == 1)

        scored = None
        score_flag = 0
        if np.any(n_score_flag == 1):
            score_flag = 1
            self.score.add_bottom()
            scored = 'bottom'
        elif np.any(n_score_flag == -1):
            score_flag = -1
            self.score.add_top()
            scored = 'top'

        puck_position_mode = bool(
            self.dim.center[1] <= puck_position[1] <= self.dim.rink_bottom)
        game_info = GameInfo([], puck_position, puck_velocity,
                             bottom_mallet_position, bottom_mallet_velocity,
                             top_mallet_position, top_mallet_velocity,
                             robot_action, human_action, scored, score_flag,
                             puck_was_hit, puck_is_at_the_bottom,
                             distance_decreased, hit_the_border, in_the_target,
                             time_iter, puck_position_mode)

        return game_info
示例#8
0
	def parse ( ):
		games_count = 0
		kills_count = 0
		index = 0
		game = [ ]
		game_index = 0
		
		print ( 'open file for read' )
		file = open ( 'log/quake.log', 'r' )
		
		gameInfo = GameInfo ( )
		
		for line in file:
			tempKillIndex = line.find ( 'Kill:' )
			tempConnectPlayer = line.find ( 'ClientUserinfoChanged:' )
			
			if ( line.find ( 'InitGame:' ) > -1 ):
				game_index += 1
				gameInfo = GameInfo ( game_index , dict ( )  , dict ( ) , 0 )
				game.append ( gameInfo )
			
			elif ( tempConnectPlayer  > -1 ):
				tempStartIndex = line.find ( 'n\\' ) + 2
				tempPlayerIndex = line[tempConnectPlayer+22 : tempStartIndex - 2].strip ( )
				
				tempEndIndex = line [ tempStartIndex : ] .find ( '\\' )
				name = line[tempStartIndex: tempStartIndex + tempEndIndex]
				
				if ( tempPlayerIndex not in gameInfo.players ):
					gameInfo.players[tempPlayerIndex] = KillInfo ( name.strip ( ) , 0 )
				else: 
					gameInfo.players[tempPlayerIndex].name = name.strip ( )
			
			elif ( tempKillIndex > -1 ):
				index = tempKillIndex + 5
				tempKillStartIndex = line [ index: ].find ( ': ' )
				
				lineSplitted = line [ index: index + tempKillStartIndex].strip ( ).split ( ' ' )
				
				killer = gameInfo.players [ lineSplitted[ 0 ] ].name.strip ( ) if lineSplitted[ 0 ] in gameInfo.players else ''
				killed = gameInfo.players [ lineSplitted[ 1 ] ].name.strip ( ) if lineSplitted[ 1 ] in gameInfo.players else ''
				
				if ( killer != killed ):	
					if ( line.find ( '<world>' ) == -1 ):				
						gameInfo.players [ lineSplitted[ 0 ] ].kills += 1
					else:
						gameInfo.players [ lineSplitted[ 1 ] ].kills -= 1
				else:
					gameInfo.players [ lineSplitted[ 0 ] ].kills -= 1
					
				kills_count += 1
				gameInfo.total_kills += 1
			
		print ( 'close file' )
		file.close ( )
		print( len ( game ) )
		
		for item in game:
			print ( item.game_index )
			
			for player in item.players:
				print ( item.players[player].name, item.players[player].kills )
			print ( item.total_kills )
			print ( '---------------------------------------' )
示例#9
0
	def parse ( ):
		games_count = 0
		kills_count = 0
		index = 0
		game = [ ]
		game_index = 0
		
		print ( 'open file for read' )
		file = open ( 'log/quake.log', 'r' )
		
		gameInfo = GameInfo ( )
		
		for line in file:
			
			tempKillIndex = line.find ( 'Kill:' )
			
			if ( line.find ( 'InitGame:' ) > -1 ):
				game_index += 1
				gameInfo = GameInfo ( game_index , [ ] , dict ( ) , 0 )
				game.append ( gameInfo )
			
			elif ( tempKillIndex > -1 ):
				index = tempKillIndex + 5
				tempKillStartIndex = line [ index: ].find ( ': ' )
				
				index += tempKillStartIndex + 2
				tempPlayerKiller  = line [ index: ]. find ( ' killed ' ) 
				killer = line [ index : index + tempPlayerKiller ] 
				
				tempPlayerKilled = line [ index + tempKillStartIndex: ]. find ( ' by ' ) 
				killed = line [ index + tempPlayerKiller + 8 : index + tempKillStartIndex + tempPlayerKilled] 
				
				if ( killer != killed ):	
					if ( line[tempKillIndex:].find ( '<world>' ) == -1 ):				
						gameInfo.kills[killer] += 1
					else:
						gameInfo.kills[killed] -= 1
						# voltar esta linha se o jogador não puder ficar com score negativo
						#gameInfo.kills[killed] = gameInfo.kills[killed] - 1 if gameInfo.kills[killed] > 0 else 0;
					
				kills_count += 1
				gameInfo.total_kills += 1
			
			elif ( line.find ( 'ClientUserinfoChanged:' )  > -1 ):
				tempStartIndex = line.find ( 'n\\' ) + 2
				tempEndIndex = line [ tempStartIndex : ] .find ( '\\' )
				name = line[tempStartIndex: tempStartIndex + tempEndIndex]
				
				if ( name not in gameInfo.players ):
					gameInfo.players.append ( name )
					gameInfo.kills[name] = 0
				
		print ( 'close file' )
		file.close ( )	
		print( len ( game ) )
		
		for item in game:
			print ( item.game_index )
			print ( item.players )
			print ( item.kills )
			print ( item.total_kills )
			print ( '---------------------------------------' )
示例#10
0
 def start_game():
     return GameInfo()
示例#11
0
文件: game.py 项目: jkamuda/protomonk
class Game():
    def __init__(self):
        # Center window on screen
        os.environ['SDL_VIDEO_CENTERED'] = '1'

        pygame.init()

        self.caption = 'NES Mario'

        size = [constants.SCREEN_WIDTH, constants.SCREEN_HEIGHT]
        self.screen = pygame.display.set_mode(size)

        self.game_info = GameInfo()
        self.sound_manager = SoundManager()

    def get_game_state(self, game_state):
        if game_state == GameState.STATE_MENU:
            # TODO kind of an ugly place to put this reset...
            self.game_info.reset()
            return Menu()
        elif game_state == GameState.STATE_LOAD:
            return LoadScreen(self.game_info)
        elif game_state == GameState.STATE_GAME:
            return MarioGame(self.game_info, self.sound_manager)
        elif game_state == GameState.STATE_GAME_OVER:
            return GameOverScreen(self.game_info, self.sound_manager)

    def run(self):
        pygame.display.set_caption(self.caption)

        running = True
        clock = pygame.time.Clock()

        overhead_info = Overhead(self.game_info)
        game_state = self.get_game_state(GameState.STATE_MENU)

        while running:
            game_time = pygame.time.get_ticks()

            if game_state.switch_state():
                game_state = self.get_game_state(game_state.next)

            events = pygame.event.get()
            for event in events:
                if event.type == pygame.QUIT:
                    running = False

                if event.type == pygame.KEYDOWN:
                    key = event.key
                    if key == pygame.K_ESCAPE or key == pygame.K_q:
                        running = False

            game_state.process_events(events)

            overhead_info.update(game_time)
            game_state.update(game_time)

            game_state.draw(self.screen)
            overhead_info.draw(self.screen)

            # Limit to 60 frames per second
            clock.tick(60)

            # Update screen
            pygame.display.flip()

        pygame.quit()
示例#12
0
 def get_info(data):
     roundNumber = int(data['RoundNumber'])
     info = GameInfo(roundNumber)
     info.print_debug()
     return info