def next_tick(self, move_list: list) -> None: '''gets move and handles event''' if Match.matches(self): Match.remove_matches(self) Helper.drop_cells(self) Helper.check_game_over(self) Match.match_cells(self) move = move_list[0] if move == NEXT: if self._faller: Faller.drop_faller(self) elif move == FALLER: if not self._faller: GameState.check_valid_col_faller(self, move_list[1]) Faller.make_faller(self, move_list[1], move_list[2]) elif move == MOVE_LEFT: if self._faller: Faller.move_faller(self, MOVE_LEFT) elif move == MOVE_RIGHT: if self._faller: Faller.move_faller(self, MOVE_RIGHT) elif move == ROTATE: if self._faller: Faller.rotate_faller(self) elif move == QUIT: self._game_over = True else: raise InvalidInput
def playTournament(self): for game in range(self.n_games): generateNewRandomDeck(self.deck) # count total cards available while len(self.deck) + len(self.player1.hand_cards) + len(self.player2.hand_cards) > 0: self.starting_player.takeToFull(True) self.responding_player.takeToFull(False) match = Match(self.starting_player, self.responding_player) # the next starting player will be the one who has won current match self.starting_player = match.playMatch() # the last starting player is the one who won the final match, so he gets 1 extra point self.starting_player.score += 1 if self.player1.score > self.player2.score: self.player1_stats['games_won'] += 1 self.notifier.notify("End of game No.{} Player {} has won with {} points".format( game+1, self.player1.name, self.player1.score )) else: self.player2_stats['games_won'] += 1 self.notifier.notify("End of game No.{} Player {} has won with {} points".format( game+1, self.player2.name, self.player2.score )) self.player1_stats['total_points'] += self.player1.score self.player2_stats['total_points'] += self.player2.score self.player1.endOfGame() self.player2.endOfGame()
def __init__(self): self.match = Match() self.agent_player = TQPlayer() self.human_simulator = RandomPlayer() TFSessionManager.set_session(tf.Session()) TFSessionManager.get_session().run(tf.global_variables_initializer())
def test_2_random_players(self): player1 = RandomPlayer('R1') player2 = RandomPlayer('R2') game = TicTacToe() gui = KtinterGui(game) match = Match(gui, game, players=[player1, player2]) match.play()
def test_2_deterministic_players_gui(self): player1 = DeterministicPlayer('D1') player2 = DeterministicPlayer('D2') game = TicTacToe() gui = KtinterGui(game) match = Match(gui, game, players=[player1, player2]) match.play()
def test_random_human_players_cl(self): player1 = RandomPlayer() player2 = HumanPlayer() game = TicTacToe() gui = CommandlineGui(game) match = Match(gui, game, players=[player1, player2]) match.play()
def test_learner_random_players(self): player1 = Learner() player2 = RandomPlayer() game = TicTacToe() gui = KtinterGui(game) match = Match(gui, game, players=[player1, player2]) match.play()
def test_human_learner_players_cl(self): player1 = HumanPlayer() player2 = Learner() game = TicTacToe() gui = CommandlineGui(game) match = Match(gui, game, players=[player1, player2]) match.play()
def test_2_random_players_cl(self): player1 = RandomPlayer('R1') player2 = RandomPlayer('R2') game = TicTacToe() gui = CommandlineGui(game) match = Match(gui, game, players=[player1, player2]) match.play()
def test_human_learner_players(self): player1 = HumanPlayer() player2 = Learner() game = TicTacToe() gui = KtinterGui(game) match = Match(gui, game, players=[player1, player2]) match.play()
def test_2_human_players(self): player1 = HumanPlayer('H1') player2 = HumanPlayer('H2') game = TicTacToe() gui = KtinterGui(game) match = Match(gui, game, players=[player1, player2]) match.play()
def test_2_human_players_cl(self): player1 = HumanPlayer('H1') player2 = HumanPlayer('H2') game = TicTacToe() gui = CommandlineGui(game) match = Match(gui, game, players=[player1, player2]) match.play()
def main(): summonerName = "Cefiroth" # APIKey = "GAPI-ddf82131-cea0-4065-937f-6f976fcfc8bb" APIKey = "RGAPI-ddf82131-cea0-4065-937f-6f976fcfc8bb" summonerData = requestSummonerDataByName(summonerName, APIKey) if summonerData != None: mySummoner = Summoner(summonerData) print(mySummoner.toString()) # masteryData = requestMasteryDataForSingleChampionOfSummoner(mySummoner.id, 143, APIKey) # if masteryData != None: # myMasteryData = Mastery(masteryData) # print(myMasteryData.toString()) # allMasteryData = requestAllMasteryDataForSummoner(mySummoner.id, APIKey) # if allMasteryData != None: # # for masteryInfo in allMasteryData: # # m = Mastery(masteryInfo) # # print(m.toString()) # champKey = allMasteryData[0]['championId'] # champ = getChampionByKey(champKey) # print(champ.toString()) allMatchData = requestMatchHistoryData(mySummoner.accountId, APIKey) if allMatchData != None: myAllMatchData = MatchList(allMatchData) mostRecentGame = myAllMatchData.getMostRecentMatchId() print("Most recent Match Id is: " + str(mostRecentGame)) myMatch = Match(requestMatchDataByMatchId(mostRecentGame, APIKey)) print(myMatch.toString())
def _get_match_list_of_current_gameday(self): most_recent_game_day_matches = [] odds = self.getOdds() # Scrape the html to gather the required information table = self.browser.find_element_by_xpath("//table[@id='tippabgabeSpiele']") for row in table.find_elements_by_xpath(".//tr"): data_of_table_row = row.find_elements_by_xpath(".//td") if len(data_of_table_row) >= 3: match = Match(home_team=data_of_table_row[1].text, away_team=data_of_table_row[2].text, odd_home_team_wins=float(0), odd_draw=float(0), odd_away_team_wins=float(0), table_data_html=data_of_table_row[3] ) for odd in odds: awayTeamInside = match.away_team in odd['teams'] if (odd['home_team'] == match.home_team and awayTeamInside): match.odd_home_team_wins = float(odd['sites'][0]['odds']['h2h'][0]) match.odd_away_team_wins = float(odd['sites'][0]['odds']['h2h'][1]) break most_recent_game_day_matches.append(match) print(most_recent_game_day_matches) return most_recent_game_day_matches
def addMatch(self, match: Match): self.matches.append(match) if match.isWhiteVictory(): self.whiteWins += 1 if match.isBlackVictory(): self.blackWins += 1 if match.isDraw(): self.draws += 1
def _freeze_faller(gamestate) -> None: '''freezes faller, changes cell attributes and checks gameover''' faller_cells = Helper._get_faller_cells(gamestate) for cell in faller_cells: cell.make_frozen_cell(cell._display) Match.match_cells(gamestate) if not Match.matches(gamestate): Helper.check_game_over(gamestate) Faller._faller_gone(gamestate)
def match(self, resume, job): imptKeywordSet = set( InformationNode.convertStringIntoList(job.getImptKeywords())) # print(imptKeywordSet) eduResult = 0 expResult = 0 resultLocationSet = 0 resultLang = 0 resultSkill = 0 matchedKeywords = [] if (resume.isSkillsPresent() and job.isSkillsPresent()): rskillSet = set(resume.getSkills()) jskillSet = set(job.getSkills()) resultSkillSet = rskillSet.intersection(jskillSet) resultSkillSet2 = rskillSet.intersection(imptKeywordSet) resultSkill = (len(resultSkillSet) + len(resultSkillSet2)) self.mergeSetIntoList(matchedKeywords, resultSkillSet.union(resultSkillSet2)) # print(rskillSet) # print(jskillSet) if (resume.isLanguagePresent() and job.isLanguagePresent()): rLangSet = set(resume.getLanguage()) jLangSet = set(job.getLanguage()) resultLangSet = rLangSet.intersection(jLangSet) resultLangSet2 = jLangSet.intersection(imptKeywordSet) resultLang = (len(resultLangSet) + len(resultLangSet2)) self.mergeSetIntoList(matchedKeywords, resultLangSet.union(resultLangSet2)) # print(rLangSet) # print(jLangSet) if (resume.isLocationPresent() and job.isLocationPresent()): rLocationSet = resume.getLocation().getCountry() jLocationSet = job.getLocation().getCountry() resultLocationSet = int(rLocationSet == jLocationSet) # print(resultLocationSet) if (resume.isEducationPresent() and job.isEducationPresent()): eduResult = (self.compareEducationBetweenJobandResume( resume.getEducation(), job.getEducation())) # print(resumeNode.getEducation()) # print(jobNode.getEducation()) if (resume.isExperiencePresent() and job.isExperiencePresent()): expResult = (self.compareExperienceBetweenJobandResume( resume.getExperience(), job.getExperience(), InformationNode.convertStringIntoList(job.getImptKeywords()), matchedKeywords)) finalResult = eduResult + expResult + resultLocationSet + resultLang + resultSkill new_match = Match(resume, job, finalResult, matchedKeywords) print(finalResult) print(new_match.getMatchedKeyWords()) return new_match
def parseNBACSVFile(connection, csvFile, delimiter): cursor = connection.cursor() rownum = 0 with open(csvFile, 'rb') as f: reader = csv.reader(f, delimiter=delimiter) for row in reader: # skip header if rownum == 0: rownum += 1 else: leagueAcronym = row[1].strip() stage = row[2] seasonId = row[3] date = row[5] homeClubName = row[6].strip() awayClubName = row[7].strip() homeClubScore = row[8] awayClubScore = row[9] extraTime = row[10] homeOdds = row[11] if row[11] != 'NA' else -1 awayOdds = row[12] if row[12] != 'NA' else -1 homeOddsProg = row[13] if row[13] != 'NA' else -1 awayOddsProg = row[14] if row[14] != 'NA' else -1 cursor.execute(''' SELECT id FROM leagues WHERE leagues.acronym = "%s" ''' % leagueAcronym) leagueId = cursor.fetchall()[0][0] cursor.execute(''' SELECT id FROM clubs WHERE clubs.name LIKE "%s" ''' % homeClubName) homeClubId = cursor.fetchall()[0][0] cursor.execute(''' SELECT id FROM clubs WHERE clubs.name LIKE "%s" ''' % awayClubName) awayClubId = cursor.fetchall()[0][0] match = Match(seasonId, leagueId, date, stage, homeClubId, awayClubId, homeClubScore, awayClubScore, homeOdds, awayOdds, homeOddsProg, awayOddsProg, extraTime) if rownum % 500 == 0: print "[CSV Parser] Inserting match %d..." % rownum match.dbInsert(connection) rownum += 1
def get(self): self.response.write('Hello world!') match = Match() match.homeTeam = "Wuhan" match.awayTeam = "Jiangsu" match.homeScore = 2 match.awayScore = 1 match.matchCity = "Wuhan" match.stadium = "Wuhan Sports Center" match.put()
def get_match_by_id(self, mid): ret = self.db.run_query('get_match_by_id', (mid,))[0] m = Match(mid, ret['name'], home_id=ret['homeTeamId'], away_id=ret['awayTeamId']) # Match-specific: played data fields completion m.set_score(ret['homeTeamScore'], ret['awayTeamScore']) if ret['played'] == 1: m.end_match() self.save_to_storage('match', m) return m
def match(self, resume, job): imptKeywordSet = set(InformationNode.convertStringIntoList(job.getImptKeywords())) # print(imptKeywordSet) eduResult = 0 expResult = 0 resultLocationSet = 0 resultLang = 0 resultSkill = 0 matchedKeywords = [] if(resume.isSkillsPresent() and job.isSkillsPresent()): rskillSet = set(resume.getSkills()) jskillSet = set(job.getSkills()) resultSkillSet = rskillSet.intersection(jskillSet) resultSkillSet2 = rskillSet.intersection(imptKeywordSet) resultSkill = (len(resultSkillSet) + len(resultSkillSet2)) self.mergeSetIntoList(matchedKeywords, resultSkillSet.union(resultSkillSet2)) # print(rskillSet) # print(jskillSet) if(resume.isLanguagePresent() and job.isLanguagePresent()): rLangSet = set(resume.getLanguage()) jLangSet = set(job.getLanguage()) resultLangSet = rLangSet.intersection(jLangSet) resultLangSet2 = jLangSet.intersection(imptKeywordSet) resultLang = (len(resultLangSet) + len(resultLangSet2)) self.mergeSetIntoList(matchedKeywords, resultLangSet.union(resultLangSet2)) # print(rLangSet) # print(jLangSet) if (resume.isLocationPresent() and job.isLocationPresent()): rLocationSet = resume.getLocation().getCountry() jLocationSet = job.getLocation().getCountry() resultLocationSet = int(rLocationSet == jLocationSet) # print(resultLocationSet) if(resume.isEducationPresent() and job.isEducationPresent()): eduResult = (self.compareEducationBetweenJobandResume(resume.getEducation(), job.getEducation())) # print(resumeNode.getEducation()) # print(jobNode.getEducation()) if(resume.isExperiencePresent() and job.isExperiencePresent()): expResult = (self.compareExperienceBetweenJobandResume(resume.getExperience(), job.getExperience(),InformationNode.convertStringIntoList(job.getImptKeywords()), matchedKeywords)) finalResult = eduResult + expResult +resultLocationSet + resultLang + resultSkill new_match = Match(resume, job, finalResult, matchedKeywords) print(finalResult) print(new_match.getMatchedKeyWords()) return new_match
def find_match(mdatetime, local, visitor): logger.debug('Start finding match: %s, %s, %s', mdatetime, local, visitor) query = {'mdatetime': mdatetime, 'local': local, 'visitor': visitor} match_dict = coll.find_one(query) match = Match.from_json(match_dict) logger.debug('Stop finding match: %s', match) return match
def scrapeMatchFromRow(self, row): data = row.findAll('td') homeClub, homeLevel = getClubAndLevelFromTeamName(data[1].text) awayClub, awayLevel = getClubAndLevelFromTeamName(data[2].text) homeTeam = Team(homeClub, homeLevel) awayTeam = Team(awayClub, awayLevel) startDate = data[0].text startDate = datetime.strptime(startDate, '%d-%m-%Y').date() startTime = data[4].text startTime = datetime.strptime(startTime, '%H:%M').time() try: meetingTime = data[3].text meetingTime = datetime.strptime(meetingTime, '%H:%M').time() except: meetingTime = startTime meetingDateTime = datetime.combine(startDate, meetingTime) startDateTime = datetime.combine(startDate, startTime) endDateTime = startDateTime + MATCH_DURATION # Assume that returning takes the same amount of time as the time between meeting and start of the match. returnedDateTime = endDateTime + (startDateTime - meetingDateTime) referee = Referee("Not Scheduled", "", "", "", "", "", []) match = Match(homeTeam, awayTeam, meetingDateTime, startDateTime, endDateTime, returnedDateTime, referee) return match
def conduct(self): for n in range(len(self.participants)): for i in range(len(self.participants)): if n == i: continue else: match = Match(self.participants[n], self.participants[i]) winner_bool = match.play() if winner_bool == 0: self.points[n] += 1 elif winner_bool == 1: self.points[i] += 1 else: raise Exception return self.participants[np.argmax(self.points)]
def scrapeTP(): driver = webdriver.Chrome("./chromedriver") wait = WebDriverWait(driver, 4) driver.get('https://thunderpick.com/en/esports/csgo?list=upcoming') Time.sleep(3) soup = BeautifulSoup(driver.page_source, features="html.parser") matches = soup.find_all("div", class_="thp-matches-page__match-row-container") match_list = [] for match in matches: try: time_set = match.find_all("div", class_="t--center match-row--large__time-to-start visible") time_to_match = [i.contents[0] for i in time_set] times_to_match = time_to_match[0].split(':') time = datetime.now().replace(microsecond=0) + timedelta(hours=int(times_to_match[0]), minutes=int(times_to_match[1]), seconds=int(times_to_match[2])) matchtime = time teams = match.find_all("div", class_="match-row--large__participant-name") team1name = teams[0].get_text() team2name = teams[1].get_text() odds = match.find_all("button", class_="odds-button odds-button--theme-primary odds-button--variant-dark") team1odds = odds[0].get_text() team2odds = odds[1].get_text() # print(f"Time: {matchtime} Team 1: {team1name} odds: {team1odds} Team 2: {team2name} odds: {team2odds}") match_list.append(Match(matchtime, team1name, team2name, "TP", team1odds, team2odds)) except: continue return match_list
def _handle_events(self) -> None: '''Handles all events''' self._check_end_game() for event in pygame.event.get(): if event.type == pygame.QUIT: self._end_game() elif event.type == pygame.VIDEORESIZE: self._resize_surface(event.size) if event.type == pygame.KEYDOWN: if event.key == pygame.K_RIGHT: self._state.next_tick([MOVE_RIGHT]) if event.key == pygame.K_LEFT: self._state.next_tick([MOVE_LEFT]) if event.key == pygame.K_SPACE: self._state.next_tick([ROTATE]) if pygame.key.get_pressed()[pygame.K_DOWN]: self._fall_tick_ratio = .8 else: self._fall_tick_ratio = .2 if not self._state._faller and not Match.matches(self._state): self._state.next_tick([FALLER, self._next_col, self._next_jewels]) self._get_random_col() self._get_random_jewels() if self._ticks * self._fall_tick_ratio > 1.6: self._ticks = 0 self._state.next_tick([NEXT]) self._ticks += 1
def get_matches(day): logger.info('Start scraping matches on: %s', str(day)) matches_obj = [] finished = False page = 0 url = 'https://sports.bwin.es/es/sports/indexmultileague' post_data = {'sportId': '4', 'page': str(page), 'dateFilter': str(day)} while not finished: logger.info('Scraping page %d', page) request = requests.post(url, post_data) soup = BeautifulSoup(request.text, 'html.parser') competitions = soup.find_all(class_='event-group-level1') logger.info('%d competitions found', len(competitions)) for competition in competitions: comp_obj = _get_competition(competition) logger.info('Scraping competition: %s', comp_obj) match_listing = competition.parent.findNext('ul') matches = match_listing.find_all(class_='col3 three-way') logger.info('%d matches found', len(matches)) for match in matches: teams, mults, match_time = _get_match_data(match) match_obj = Match(teams[0], teams[1], mults, comp_obj, datetime.combine(day, match_time)) matches_obj.append(match_obj) if len(competitions) == 0: finished = True page += 1 post_data['page'] = page logger.info('Stop scraping matches on: %s. Matches found: %d', str(day), len(matches_obj)) return matches_obj
def getMatches(matches, prevRound, url): response = requests.get(url) soup = BeautifulSoup(response.text, 'lxml') currentRound = prevRound + 1 Rounds = soup.findAll(class_='ncet') resultDivs = soup.findAll(class_='compgrp') resultDiv = [] for i in range(len(Rounds)): if (int(Rounds[i].getText().split()[1]) == currentRound): resultDiv.append(resultDivs[i]) matchesRaw = [] for result in resultDiv: matchesRaw.append(result.select('table.blocks.gteam')) for groupOfMatches in matchesRaw: for match in groupOfMatches: homeTeam = match.select('td.home.uc')[0].getText().strip() awayTeam = match.select('td.away.uc')[0].getText().strip() score = [] for rawScore in match.find('td', class_='score'): if (rawScore.name == 'a'): scores = rawScore.getText().split() score.append(scores[0]) score.append(scores[2]) matches.append(Match(homeTeam, awayTeam, score))
def matching(x_dataset, y_dataset, n): """ Loops through all values in y_dataset and compares to the single entry in x_dataset. The best matches are returned Only the values in columns with names in ./Constants/columnLables.txt will be compared. The weights for the calculation are found in ./Constants/weightMatrix.txt :param x_dataset: single entry data of type dataset :param y_dataset: multiple entry data of type dataset :param n: length of list of best matches :return: best n matches """ print("\n\n----- STARTING MATCHING -----\n\n") weight_matrix = Weights.get_weight_matrix() value_labels = columns.get_value_labels() x_row = columns.get_row_values(0, x_dataset.df, x_dataset.lost_or_found) x = Entry(x_row[0],remove_first(x_row)) scores = [] y_ids = [] all_matches=[] for i in range(len(y_dataset.df)): y_row = columns.get_row_values(i, y_dataset.df, y_dataset.lost_or_found) y = Entry(y_row[0],remove_first(y_row)) try: values=compare_entries(x.values,y.values,value_labels) score=calculate_score(weight_matrix,values) scores.append(score) y_ids.append(y.id) except Exception as e: print("Error calculating score") print(e) [bestMatches, bestScores] = find_best_matches(scores, y_ids, n) matches = [] for i in range(0, len(bestMatches)): if x_dataset.lost_or_found == "lost": matches.append(Match(x.id, bestMatches[i], bestScores[i])) else: matches.append(Match(bestMatches[i], x.id, bestScores[i])) print("matching successful") return matches
def main(): fname = '分诊评测集标注.xlsx' bk = xlrd.open_workbook(fname) sh = bk.sheet_by_name("Sheet1") #获取行数 nrows = sh.nrows #获取列数 ncols = sh.ncols #获取第八列数据 DES_list = [] for i in range(1, nrows): DESvalue = sh.cell_value(i, 7) DES_list.append(DESvalue) # Get the departments (correct results) DEP_list = [] for i in range(1, nrows): DEPvalue = sh.cell_value(i, 0) DEP_list.append(DEPvalue) count = 0 i = 0 d = Diagnosis() # report to log discrepancies between prediction and actual results report = {} # Process the natural language and extract keywords matcher = Match() matcher.load("disease_symptom.json") for describe in DES_list: # Extracting keywords takes place here describe = matcher.match(describe).rstrip() request = [{'request': {'text': describe}}] response = d.run(json.dumps(request, ensure_ascii=False)) predictedDept = response.get('text')[INDEX_OF_DEPT] if predictedDept == DEP_list[i]: count += 1 else: report[describe] = [predictedDept, DEP_list[i]] i += 1 percentage = (count / nrows) * HUNDRED print("Estimated accuracy: " + percentage + "%") print("Incorrect results: ") print(report)
def continue_game(self): level = self.save['level'] lives = self.save['lives'] points = self.save['points'] if os.path.isfile(f"saves/{self.active_profile_name}_save.json"): # Delete all profile saves os.remove(f"saves/{self.active_profile_name}_save.json") self.clear_screen() self.match = Match(self.canvas, self, level, lives, points)
def update_matches(self, mts): if mts is not None: matches = [] for m in mts: if m is not None and m.user is not None: matches.append(Match(m.user)) return matches return None
def create_match(self, name, homeTeamId, awayTeamId): mid = self.db.run_query('create_match', (name, homeTeamId, awayTeamId,)) m = Match(mid, name, home_id=homeTeamId, away_id=awayTeamId) self.save_to_storage('match', m) return m
def add_match(a, b): if a.get_id() not in Elo.__players: raise KeyError('Player 1 does not exist') if b.get_id() not in Elo.__players: raise KeyError('Player 2 does not exist') Elo.__match_count += 1 Elo.__matches[Elo.__match_count] = Match(Elo.__match_count, a, b) return (Elo.__match_count)
def get_match_by_team(self, tid): ret = self.db.run_query('get_match_by_team', (tid, tid, )) matches = [] for row in ret: m = Match(row['id'], row['name'], home_id=row['homeTeamId'], away_id=row['awayTeamId']) # Match-specific: played data fields completion m.set_score(row['homeTeamScore'], row['awayTeamScore']) if row['played'] == 1: m.end_match() matches.append(m) self.save_to_storage('match', m) return matches
def from_dict(self, dict_in): players_arr = dict_in["players"] for player in players_arr: player_obj = Player.from_dict(player) self.players[player_obj.player_id] = player_obj for match in dict_in["matches"]: self.matches.append(Match.from_dict(match)) self.league_title = dict_in["league_title"] self.recalculate_rankings()
def getMathes(conn): cursor = conn.cursor() cursor.execute("SELECT * FROM matches ") matchList = [] row = cursor.fetchone() while row: match = Match(row[0],row[1],row[2],row[3],row[4],row[5],row[6]) match.TournamentName = getTournament(match.getTournamentID(), conn).Name match.VenueName = getVenue(match.getVenueID(), conn).Name matchList.append(match) row = cursor.fetchone() return matchList
def handleDistribHtmlPage(self, htmlPage): euro7startRx = QRegExp("data-grid-id=\"(\\d*)\"") indexGrille = "" posi = 0 while posi != -1 and indexGrille != self._gridList[self._indexGrille][0]: print "posi = %d" % posi print "indexGrille = %s" % indexGrille print "self._indexGrille = %s" % self._gridList[self._indexGrille][0] posi= euro7startRx.indexIn(htmlPage, posi+1) indexGrille = euro7startRx.cap(1) euro7TeamRx = QRegExp("<label for=\"[^\"]*\">([^<]*)<\/label>") self._grid = Grille() self._grid.setReturnRate(0.75) self._grid.setFirstRankRate(0.55) self._grid.setScndRankRate(0.45) jackpot = int(self._gridList[self._index][2]) self._grid.setJackpot(jackpot) self._grid.setNbPlayers(jackpot) index_l = 0 total = 0 #size_l = 5 i=0 #try: if True: posi= euro7TeamRx.indexIn(htmlPage, posi) print "posi = %d" % posi while posi != -1 and i < self._gridSize: i += 1 team1 = euro7TeamRx.cap(1) print "team1 = %s" % team1 posi= euro7TeamRx.indexIn(htmlPage, posi+1) posi= euro7TeamRx.indexIn(htmlPage, posi+1) team2 = euro7TeamRx.cap(1) print "indice %i" % i print "team2 = %s" % team2 match = Match(team1 + " vs " + team2) match.setTeam1(team1) match.setTeam2(team2) p1 = 0.33 pN = 0.33 p2 = 0.33 total = p1 + pN +p2 r1 = p1/total*100 r2 = p2/total*100 rN = pN/total*100 match.setRepartition(p1/total, pN/total, p2/total) self._grid.addGame(match) print "game added : %d" % i posi= euro7TeamRx.indexIn(htmlPage, posi+1) #except: #msg = QMessageBox() #msg.setText("Loading page error") #msg.exec_() #self.__workbook1.save(self.__outPutFileName) return
def from_dict(self, dict_in): players_arr = dict_in["players"] for player in players_arr: player_obj = Player.from_dict(player) self.players[player_obj.player_id] = player_obj if self.__use_true_skill is True: from trueskill import Rating player_obj.true_skill = Rating() for match in dict_in["matches"]: self.matches.append(Match.from_dict(match)) self.recalculate_rankings()
def handleDistribHtmlPage(self, htmlPage): self._grid = Grille() self._grid.setReturnRate(0.75) self._grid.setFirstRankRate(0.55) self._grid.setScndRankRate(0.45) jackpot = int(self._gridList[self._index][2]) / 0.75 self._grid.setJackpot(jackpot) self._grid.setNbPlayers(jackpot) #print "handleDistribHtmlPage" #print htmlPage myParser = WSGridParser() myParser.html = filter(onlyascii, htmlPage) self.writeHtmlToFile(myParser.html) myParser.feed(myParser.html) index_l = 0 total = 0 size_l = 7 print "!!!!!!!!!!!!!!!!!! End Of parsing !!!!!!!!!!!!!!!!!!!" try: print "Grille :" print "%s" % myParser.wsDataFormat.grille for i in range(0, size_l) : print "indice %i" % i team1 = myParser.wsDataFormat.grille['team1'][i] team2 = myParser.wsDataFormat.grille['team2'][i] match = Match(team1 + " vs " + team2) match.setTeam1(team1) match.setTeam2(team2) p1 = myParser.wsDataFormat.grille['croix_1'][i] pN = myParser.wsDataFormat.grille['croix_x'][i] p2 = myParser.wsDataFormat.grille['croix_2'][i] total = float(p1+pN+p2) r1 = p1/total*100 r2 = p2/total*100 rN = pN/total*100 match.setRepartition(p1/total, pN/total, p2/total) #print "{} vs {} \t{0:.3f}\t{0:.3f}\t{0:.3f}\n".format( WSDataFormat.grille['team1'][i], WSDataFormat.grille['team2'][i], r1, rN, r2) #print "{} vs {}\t{:10.3f}\t{:10.3f}\t{:10.3f} ".format( myParser.wsDataFormat.grille['team1'][i].encode('utf-8'), myParser.wsDataFormat.grille['team2'][i].encode('utf-8'), r1,rN,r2) self._grid.addGame(match) print "%d grilles" % total except: msg = QMessageBox() msg.setText("Loading page error") msg.exec_() #self.__workbook1.save(self.__outPutFileName) return
class MatchTest(unittest.TestCase): def setUp(self): self.match = Match() def scoreNpoints(self,player,points): for i in range(0, points): self.match.scores(player) def testEndMatch(self): self.assertEqual(True,self.match.endMatch()) def testPlayer1Score(self): self.assertEqual("0",self.match.getScore("Player1")) def testPlayer1Scores(self): self.scoreNpoints("Player1",1) self.assertEqual("15",self.match.getScore("Player1")) def testPlayer1Scores(self): self.scoreNpoints("Player1",2) self.assertEqual("30",self.match.getScore("Player1")) def testPlayer1ScoresThreeTimes(self): self.scoreNpoints("Player1",3) self.assertEqual("40",self.match.getScore("Player1")) def testPlayer1ScoresFourTimes(self): self.scoreNpoints("Player1",4) self.assertEqual("0",self.match.getScore("Player1")) self.assertEqual("1-0",self.match.getGamesScore()) def testPlayer2ScoresThreeTimes(self): self.scoreNpoints("Player1",1) self.scoreNpoints("Player2",1) self.assertEqual("15",self.match.getScore("Player1")) self.assertEqual("15",self.match.getScore("Player2")) def testPlayerAd(self): self.scoreNpoints("Player1",3) self.scoreNpoints("Player2",3) self.scoreNpoints("Player1",1) self.assertEqual("AD",self.match.getScore("Player1")) self.assertEqual("40",self.match.getScore("Player2")) def testEqualsAfterAd(self): self.scoreNpoints("Player1",3) self.scoreNpoints("Player2",3) self.scoreNpoints("Player1",1) self.scoreNpoints("Player2",1) self.assertEqual("40",self.match.getScore("Player1")) self.assertEqual("40",self.match.getScore("Player2")) def testGameAfterEquals(self): self.scoreNpoints("Player1",3) self.scoreNpoints("Player2",3) self.scoreNpoints("Player1",1) self.scoreNpoints("Player2",1) self.scoreNpoints("Player1",2) self.assertEqual("0",self.match.getScore("Player1")) self.assertEqual("0",self.match.getScore("Player1")) self.assertEqual("1-0",self.match.getGamesScore()) def tearDown(self): pass
def handleDistribHtmlPage(self, htmlPage): print "handleDistribHtmlPage" jackpot = int(self._gridList[self._index][2]) / 0.70 self._grid.setJackpot(jackpot) self._grid.setNbPlayers(jackpot) htmlStrPage = filter(onlyascii, str(htmlPage)) teamString = "<td class=\"center matchs_av\">((\\(?\\)?\\d*\\w*\\.?'?-?\\s*)*)<\/td>" enfOfGridString = "<div class=\"repart_legende\">" loto15Teamrx = QRegExp(teamString) endOfGridRx = QRegExp(enfOfGridString) posiEndOfGrid= endOfGridRx.indexIn(htmlStrPage, 0) repString = ">(\\d*,*\\d*)\\s*\%<" loto15Reprx = QRegExp(repString) index_l = 0 total = 0 posi = 0 i = 0 #try: if True : posi= loto15Teamrx.indexIn(htmlStrPage, posi+1) print "posi = %d" % posi while posi != -1: i+=1 print "indice %i" % i team1 = loto15Teamrx.cap(1) posi= loto15Teamrx.indexIn(htmlStrPage, posi+1) print "posi2 = %d" % posi print "posi2 = %d" % posi print "team1 = %s" % team1 team2 = loto15Teamrx.cap(1) posiMax= loto15Teamrx.indexIn(htmlStrPage, posi+1) if posiMax < 0: posiMax = posiEndOfGrid print "posi3 = %d" % posi print "team2 = %s" % team2 match = Match(team1 + " vs " + team2) match.setTeam1(team1) match.setTeam2(team2) posiInter= loto15Reprx.indexIn(htmlStrPage, posi+1) print "posiInter = %d" % posiInter print "posiMax = %d" % posiMax if (posiInter > 0) and (posiInter <= posiMax) : posi = posiInter print "posi4 = %d" % posi p1 = float(loto15Reprx.cap(1).replace(",",".")) posi= loto15Reprx.indexIn(htmlStrPage, posi+1) print "posi5 = %d" % posi pN = float(loto15Reprx.cap(1).replace(",",".")) posi= loto15Reprx.indexIn(htmlStrPage, posi+1) print "posi6 = %d" % posi p2 = float(loto15Reprx.cap(1).replace(",",".")) total = float(p1+pN+p2) r1 = p1/total*100 r2 = p2/total*100 rN = pN/total*100 match.setRepartition(p1/total, pN/total, p2/total) self._grid.addGame(match) print "game added : %d" % i posi= loto15Teamrx.indexIn(htmlStrPage, posi+1) print "posi1 = %d" % posi print "%d grilles" % i self._gridSize = i #except: #msg = QMessageBox() #msg.setText("Loading page error") #msg.exec_() #self.__workbook1.save(self.__outPutFileName) return
def setUp(self): self.match = Match()
def get_matches(self): return [match for match in Match.query() if str(self._id) in match.player_scores.keys()]