Example #1
1
def main():
    '''
    Main function permits to launch a match of Quarto
    It permits also to modify game configuration (mainly players attributes)
    '''

    hostname = None
    if len(argv) == 2:
        hostname = argv[1]

    configuration = {
        'name_player1': 'Mr. R',
        'name_player2': 'Mr. N',
        'intelligence_player1': Minimax(3),
        'intelligence_player2': Minimax(4),
        'hostname': hostname
    }

    choice = None

    while choice != "q":
        ui.showMenu()
        try:
            choice = ui.askChoice(("p", "t", "c", "q")).lower()
        except EOFError:
            choice = "q"

        if choice == "p":
            match = Match(configuration)
            match.run()
        elif choice == "t":
            try:
                tournament = Tournament(configuration)
                tournament.run()
            except Exception, e:
                print e
        elif choice == "c":
            configuration = change_configuration()
Example #2
0
	def startGame(self):
		playerNumber = input("'one' player or 'two' players?\n")
		
		#pull this out
		if playerNumber == "two":
			player1 = Human()
			player2 = Human()
		elif playerNumber == "one":
			player1 = Human()
			player2 = AI()
		####

	
		match = Match()


		while match.matchNumber < 3:
			match.countMatches()
			match.startMatch(player1, player2)

			if player1.wins >= 2 or match.matchNumber == 3 and player1.wins > player2.wins:
				self.winner = "Player 1!"
				break
			elif player2.wins >= 2 or match.matchNumber == 3 and player2.wins > player1.wins:
				self.winner = "Player 2!"
				break
def test_match_full_sentences():
    for (test_sentence, gold_result) in zip(test_sentences, gold_results_all_sentences):
        sys.stderr.write("gold: " + str(gold_result) + "\n")
        sys.stderr.write("test: " + str(test_sentence) + "\n")
        if sys.version_info[0] >= 3:
            eq_(gold_result, Match.match(test_text, test_sentence))
        else:
            eq_(gold_result, Match.match(test_text.decode("utf8"), test_sentence))
        sys.stderr.write("\n")
class BlackJackTable(cmd.Cmd):
    minbet = 3
    maxbet = 10
    intro = (
        "Welcome to the blackjack table. Type help or ? to list commands.\n The minimum bet is %s dollars, the maximum bet is %s dollars\n"
        % (minbet, maxbet)
    )
    prompt = "(input) "
    file = None

    # Instructions
    def do_start(self, arg):
        "Starts a game"
        self.match = Match(table=self)
        self.do_display(None)

    def feedback(self, question):
        return input(question)

    def do_hitme(self, arg):
        "Hit me"
        self.match.hit()
        self.do_display(None)

    def do_bet(self, arg):
        "Bet an amount of money"

    def do_buyIn(self, arg):
        "Buy a certain amount of chips"
        self.match.playerBuysIn(*parse(arg))

    def do_deck(self, arg):
        "Fix the number of decks be used: deck 6"
        self.math.newDecks(*parse(arg))

    def do_changeDefault(self, arg):
        "Change the default amount for a bet: changeDefault 3 10"
        if parse(arg)[0] >= parse(arg)[1]:
            print("Ensure that minimum is lower than the maximum")
        else:
            (BlackJackTable.minbet, BlackJackTable.maxbet) = parse(arg)

    def do_rules(self, arg):
        "Print the current rules"
        print("The minimum bet is " + str(BlackJackTable.minbet) + " and maximum is " + str(BlackJackTable.maxbet))

    def do_display(self, arg):
        "Display your hand"
        print(self.match)

    def do_quit(self, arg):
        "Quit the game"
        print("Thanks for visiting.")
        return True
Example #5
0
def match_and_link(dhs, masechet):
    match = Match(in_order=True, min_ratio=80, guess=False, range=True, can_expand=False)
    links = []
    for daf in dhs:
        talmud_text = get_text_plus(masechet+"."+AddressTalmud.toStr("en", daf))['he']
        result = match.match_list(dhs[daf], talmud_text)
        for line in result:
            talmud_range = result[line].replace("0:", "")
            Ritva_end = "Ritva on "+masechet+"."+str(AddressTalmud.toStr("en", daf))+"."+str(line)
            talmud_end = masechet + "." + AddressTalmud.toStr("en", daf) + "." + talmud_range
            links.append({'refs': [Ritva_end, talmud_end], 'type': 'commentary', 'auto': 'True', 'generated_by': masechet+"Ritva"})
    post_link(links)
Example #6
0
    def test_winner(self):
        game1 = Game(Team("Cate"), Team("Opponent1"), Team("Cate"))
        game2 = Game(Team("Cate"), Team("Opponent1"), Team("Cate"))
        games = []
        for x in range(0, 6):
            games.append(game1)
        set1 = Set(games)
        sets = []
        for x in range(0, 18):
            sets.append(set1)

        match1 = Match(sets, game1.teamA, game1.teamB)
        self.assertEqual(game1.teamA, match1.winner())
Example #7
0
def get_true_true(result, index, param, mass):
	true_true = []
	for i in range(len(result)):
		title = result[i][0]
		spec = index.spec_dict[title]
		ch = spec.ch

		candidate = []
		sum_int = []
		for j in range(len(result[i][1])):
			pep1 = index.unique_pep[0][result[i][1][j][0][0]]
			pep2 = index.unique_pep[0][result[i][1][j][0][1]]
			sl = [set(), set()]
			pos = result[i][1][j][1]

			for pro in pep1.pro_id:
				cols = pro.split('|R')
				if len(cols) > 1 and len(cols[1]) > 0:
					sl[0].add(cols[1][0])

			for pro in pep2.pro_id:
				cols = pro.split('|R')
				if len(cols) > 1 and len(cols[1]) > 0:
					sl[1].add(cols[1][0])

			feature = list(result[i][1][j][2][0])
			feature.extend(result[i][1][j][2][1])
			if feature[0] / float(feature[7]) >= 0.20 and feature[1] / float(feature[7]) >= 0.20 and feature[8] / float(feature[15]) >= 0.20 and feature[9] / float(feature[15]) >= 0.20 and feature[2] >= 0.1 and feature[10] >= 0.1 and (len(sl[0]) == 0 or len(sl[1]) == 0 or len(sl[0].intersection(sl[1]))) > 0:
				xl = XLink(pep1, pep2, pos, ch, mass, param)
				match = Match(spec, xl, mass, param)
				match.match(mass)

				candidate.append(match)
				sum_int.append(feature[2] + feature[10])

		if len(candidate) == 0:
			continue
		combo = zip(candidate, sum_int)
		candidate = list(zip(*sorted(combo, key = lambda x : x[1], reverse = True))[0])
		sum_int = list(zip(*sorted(combo, key = lambda x : x[1], reverse = True))[1])
		true_true.append(candidate[0])

	for i in range(len(true_true)):
		pep1 = true_true[i].xlink.pep[0]
		pep2 = true_true[i].xlink.pep[1]
		s = pep1.seq + '\t' + pep2.seq + '\t' + ','.join(pep1.pro_id) + '\t' + ','.join(pep2.pro_id)
		print s

	if len(true_true) < 150:
		print '\nWARNING: The number of True-True PSMs(' + str(len(true_true)) + ') is too small and maybe insufficient for training an reliable model!\n'
	return true_true
Example #8
0
 def parse(self, textfile = None):
     if textfile is not None:
         self.textfile = textfile
     if self.textfile is None:
         return False
     text = self.textfile.get_src_text()
     m = Match(r"(?s)\/\*[*]+(?=\s)"
               r"((?:.(?!\*\/))*.)\*\/"
               r"([^/\{\}\;\#]+)[\{\;]")
     self.children = []
     for found in m.finditer(text):
         child = FunctionHeader(self, found.group(1), found.group(2))
         self.children += [ child ]
     return len(self.children) > 0
Example #9
0
def get_matches_per_spec(mass, param, index, title):
	spec_dict = index.spec_dict
	unique_pep = index.unique_pep[0]
#	search_index = index.search_index
	x_residue = param['x_residue']

	index_list = index.get_candidates(title)
	spec = spec_dict[title]

	matches = []
	for i in range(len(index_list)):
		index1 = index_list[i][0]
		index2 = index_list[i][1]
		
		pep1 = unique_pep[index1]
		pep2 = unique_pep[index2]

		pep_sorted = sorted([pep1, pep2], key = lambda x : x.seq)
		pep1 = pep_sorted[0]
		pep2 = pep_sorted[1]

		ch = spec_dict[title].ch

		mz = spec_dict[title].mz
		it = spec_dict[title].it

		k_pos1 = []
		k_pos2 = []
		if param['ntermxlink'] == True:
			if pep1.is_nterm == True:
				k_pos1.append(0)
			if pep2.is_nterm == True:
				k_pos2.append(0)

		pep_seq1 = pep1.seq
		k_pos1.extend(list(zip(*filter(lambda x : x[1] == x_residue, enumerate(pep_seq1[:-1])))[0]))
		pep_seq2 = pep2.seq
		k_pos2.extend(list(zip(*filter(lambda x : x[1] == x_residue, enumerate(pep_seq2[:-1])))[0]))

		for p1 in k_pos1:
			for p2 in k_pos2:
				pos = [p1, p2]
				xl = XLink(pep1, pep2, pos, ch, mass, param)
			
				match = Match(spec, xl, mass, param)
				match.match(mass)
				matches.append(match.get_match_info(index))

	return matches
def matchobj(daf_num, amud, text):
    new_shas =[]
    index = (daf_num-2)*2
    if amud=="b":
        index= index + 1
    list =text.split(" ")
    string= " ".join(list[0:7])
    string = re.sub(ur'(?:@|[0-9]|<|>|b|\[|\*|\])',"",string)
    match_obj = Match(min_ratio=50, guess =True)
    for line in shas[index]:
        new_line = re.sub(ur'<[^<]+?>',"",line)
        new_shas.append(new_line)
    #print string, daf_num, amud
    results = match_obj.match_list([string], new_shas)
    return(results)
Example #11
0
 def parse(self, functionheader = None):
     if functionheader is not None:
         self.functionheader = functionheader
     if self.functionheader is None:
         return False
     found = Match()
     prototype = self.get_prototype()
     if prototype & found(r"(?s)^(.*[^.])"
                          r"\b(\w[\w.]*\w)\b"
                          r"(\s*\(.*)$"):
         self.prespec = found.group(1).lstrip()
         self.namespec = found.group(2)
         self.callspec = found.group(3).lstrip()
         self.name = self.namespec.strip()
         return True
     return False
Example #12
0
 def setUp(self):
     json = {  
                "_links":{  
                   "self":{  
                      "href":"http://api.football-data.org/v1/fixtures/153572"
                   },
                   "competition":{  
                      "href":"http://api.football-data.org/v1/competitions/433"
                   },
                   "homeTeam":{  
                      "href":"http://api.football-data.org/v1/teams/679"
                   },
                   "awayTeam":{  
                      "href":"http://api.football-data.org/v1/teams/676"
                   }
                },
                "date":"2016-08-26T18:00:00Z",
                "status":"TIMED",
                "matchday":4,
                "homeTeamName":"Vitesse Arnhem",
                "awayTeamName":"FC Utrecht",
                "result":{  
                   "goalsHomeTeam":0,
                   "goalsAwayTeam":0
                },
                "odds":{}
             }
     self.match = Match(json)
Example #13
0
    def catch_content(self):
        question_id = Match.question(self.url).group('question_id')
        question_obj = self.client.question(int(question_id))
        # TODO: hyperlink, pictures, Youku links
        bulk_data = list()
        bulk_data.append({
            '_index': 'zhihu',
            '_type': 'question',
            '_id': question_obj.id,
            '_op_type': 'update',
            '_source': {'doc': question_obj.pure_data, 'doc_as_upsert': True}
        })

        for item in question_obj.answers:
            if item.pure_data['cache'] is not None:
                doc_data = item.pure_data['cache']
            else:
                doc_data = item.pure_data['data']
            doc_data.update({'content': item.content})
            _source_data = {'doc': doc_data, 'doc_as_upsert': True}
            bulk_data.append({
                '_index': 'zhihu',
                '_type': 'answer',
                '_id': item.id,
                '_op_type': 'update',
                '_source': _source_data
            })
        helpers.bulk(self.es, bulk_data)
Example #14
0
def match_and_link(text, masechet):
	match = Match(in_order=True, min_ratio=80, guess=False, range=True, can_expand=False)
	for daf_count, daf in enumerate(text):
		dhs = []
		comments = []
		for each_line in daf:
			if each_line.find("כו'") >= 0:
				dh, comment = each_line.split("כו'", 1)
			elif each_line.find(".") >= 0:
				dh, comment = each_line.split(".", 1)
			else:
				dh, comment = splitText(each_line, 10)
			dhs.append(dh)
			comments.append(comment)
		pdb.set_trace()
		talmud_text = get_text_plus(masechet+"."+AddressTalmud.toStr("en", daf_count+3))['he']
		result = match.match_list(dhs, talmud_text)
Example #15
0
def post(text, dh_dict, tractate):
     text_array = convertDictToArray(text)
     send_text = {
         "text": text_array,
         "versionTitle": "Ramban on Talmud",
         "versionSource": "http://www.sefaria.org",
         "language": "he"
     }
     post_text("Chiddushei Ramban on "+tractate, send_text)
     links_to_post = []
     daf_array = get_text_plus(tractate)['he']
     match = Match(in_order=True, min_ratio=80, guess=False, range=True, can_expand=False)
     for daf in sorted(dh_dict.keys()):
         dh_list = dh_dict[daf]
         results = match.match_list(dh_list, daf_array[daf-1], tractate+" "+AddressTalmud.toStr("en", daf))
         for key, value in results.iteritems():
             value = value.replace("0:", "")
             talmud_end = tractate + "." + AddressTalmud.toStr("en", daf) + "." + value
             ramban_end = "Chiddushei_Ramban_on_" + tractate + "." + AddressTalmud.toStr("en", daf) + "." + str(key)
             links_to_post.append({'refs': [talmud_end, ramban_end], 'type': 'commentary', 'auto': 'True', 'generated_by': "ramban"+tractate})
     post_link(links_to_post)
Example #16
0
 def __init__(self, director, background_match):
     '''
     Constructor
     '''
     Scene.__init__(self, director, background_match)        
     self.match = Match()
     self.scene_winner =  Sce_Winner(director, 'winner', MATCH_SCENE)
     self.c_fails = 0
     
     self.match.generate_table()
     for buttom in self.common_buttoms.itervalues():
         buttom.is_visible = True
Example #17
0
 def match_zero_or_more(self, text, index=0):
     """
     Accumulates zero or more matches into a single Match object.
     This will always return a Match, (0 or 1) = true
     """
     accumulated_match = Match(index, '')
     while True:
         start_index = index + len(accumulated_match.text)
         match = self.match_all_sub_queries(text, start_index)
         if match and match.index == start_index:
             accumulated_match = Match.join_matches([accumulated_match, match])
         else: break
     return accumulated_match
Example #18
0
    def fix_image(self, content, recipe):
        content = Match.fix_html(content=content, recipe_kind=recipe)
        for img in re.findall(r'<img[^>]*', content):
            if recipe not in [Type.sinablog_author, Type.cnblogs_author]:
                # fix img
                if img[-1] == '/':
                    img = img[:-1]
            img += '>'
            src = re.search(r'(?<=src=").*?(?=")', img)
            if not src:
                new_image = img + '</img>'
                content = content.replace(img, new_image)
                continue
            else:
                src = src.group(0)
                if src.replace(' ', '') == '':
                    new_image = img + '</img>'
                    content = content.replace(img, new_image)
                    continue
            src_download = HtmlCreator.fix_image_src(src)
            if src_download:
                if recipe in Type.zhihu and not src_download.startswith('http'):
                    # fix zhuanlan image href
                    src_download = src_download.split('.')[0]
                    filename = self.image_container.add('https://pic2.zhimg.com/'+src_download+'_b.jpg')
                elif recipe in Type.generic:
                    filename = ''    # TODO
                else:
                    filename = self.image_container.add(src_download)
            else:
                filename = ''
            new_image = img.replace('"{}"'.format(src), '"../images/{}"'.format(filename))

            if recipe in Type.jianshu:
                new_image = new_image.replace('data-original-src', 'temppicsr')
                new_image = new_image.replace('src', 'falsesrc')
                new_image = new_image.replace('temppicsr', 'src')    # 应该有更好的方式, 暂时先这样写
                new_image += '</img>'
            elif recipe in Type.sinablog:
                # 硬编码, 可以优化?写到fix_html函数中
                new_image = new_image.replace('http://simg.sinajs.cn/blog7style/images/common/sg_trans.gif',\
                                          '../images/{}'.format(filename))
            elif recipe in Type.zhihu:
                new_image = new_image.replace('//zhstatic.zhihu.com/assets/zhihu/ztext/whitedot.jpg',
                                              '../images/{}'.format(filename))
                new_image += '</img>'
            elif recipe in Type.cnblogs:
                pass
            content = content.replace(img, '<div class="duokan-image-single">{}</div>'.format(new_image))

        return content
Example #19
0
    def match_all_sub_queries(self, text, index=0):
        """
            Recursively matches all subqueries in this Query.
            This function searches left to right for matches to subqueries.
            For each subquery, if a match is found, then:
                if it is adjacent to the last match or it is the first match
                    for this query, we add it to the matches array
                otherwise, we empty the matches array and start searching from
                    the first subquery again
            If at any point no match for a subquery is found, we return None
            Once we have found matches for all subqueries, we join all matches
                into a single Match object, which is then returned.
        """
        while index < len(text):
            matches = []
            for i, query in enumerate(self.queries):
                match = None
                if type(query) is str:
                    found_index = text.find(query, index)
                    match = Match(found_index, query)
                else:
                    match = query.match(text, index)

                if match is None or match.index == -1: return None

                if matches == [] or index == match.index:
                    index = match.index + len(match.text)
                    matches.append(match)
                elif index != 0 and index != match.index:
                    curr_match = Match.join_matches(matches)
                    if len(curr_match.text) == 0:
                        index += 1
                    break
                else:
                    return None
            else:
                return Match.join_matches(matches)
        return None
Example #20
0
def post(text, dh_dict):
     actual_text = {}
     for perek in text:
         actual_text[perek] = convertDictToArray(text[perek])
     text_to_post = convertDictToArray(actual_text)
     send_text = {"text":text_to_post,
                         "versionTitle":"OYW",
                        "versionSource": "http://mobile.tora.ws/",
                        "language":"he"
                         }
     post_text("Gur Aryeh on "+book, send_text)

     links = []
     for perek in dh_dict:
        for passuk in dh_dict[perek]:


            dh_list = dh_dict[perek][passuk]
            rashi_text = get_text_plus("Rashi on "+book+"."+str(perek)+"."+str(passuk))['he']
            match_out_of_order = Match(in_order=False, min_ratio=85, guess=True, range=True, can_expand=False)
            results = match_out_of_order.match_list(dh_orig_list=dh_list, page=rashi_text, ref_title="Gur Aryeh")
            for dh_pos in results:
                result = results[dh_pos].replace("0:","")
                if result.find('-')>=0:
                    x,y = result.split('-')
                    if int(x)>int(y):
                        pdb.set_trace()
                links.append({
                    "refs": [
                        "Rashi on "+book+"."+str(perek)+"."+str(passuk)+"."+result,
                        "Gur Aryeh on "+book+"."+str(perek)+"."+str(passuk)+"."+str(dh_pos)
                    ],
                    "type": "commentary",
                    "auto": True,
                    "generated_by": "Gur Aryeh on "+book+" linker"})
     	post_link(links)
     	links = []
Example #21
0
    def catch_content(self):
        column_id = Match.column(self.url).group("column_id")
        print("column_id: {}".format(column_id))
        headers = {
          'User-Agent': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Mobile Safari/537.36'
        }

        r = requests.get(
            url="https://zhuanlan.zhihu.com/api/columns/{}".format(column_id),
            headers=headers
        )
        columns_info = json.loads(r.text)
        print("Got column info: {}".format(columns_info["intro"] if columns_info["intro"] != '' else 'None'))

        offset = 0
        for offset in range(0, int(columns_info["postsCount"]), 50):
            self.send_bulk(headers, column_id, offset, 50, columns_info)
        self.send_bulk(headers, column_id, offset, columns_info["postsCount"]-offset, columns_info)
Example #22
0
class TestMatch(unittest.TestCase):
    def setUp(self):
        json = {  
                   "_links":{  
                      "self":{  
                         "href":"http://api.football-data.org/v1/fixtures/153572"
                      },
                      "competition":{  
                         "href":"http://api.football-data.org/v1/competitions/433"
                      },
                      "homeTeam":{  
                         "href":"http://api.football-data.org/v1/teams/679"
                      },
                      "awayTeam":{  
                         "href":"http://api.football-data.org/v1/teams/676"
                      }
                   },
                   "date":"2016-08-26T18:00:00Z",
                   "status":"TIMED",
                   "matchday":4,
                   "homeTeamName":"Vitesse Arnhem",
                   "awayTeamName":"FC Utrecht",
                   "result":{  
                      "goalsHomeTeam":0,
                      "goalsAwayTeam":0
                   },
                   "odds":{}
                }
        self.match = Match(json)

    def test_match_create(self):
        self.assertEqual(self.match.homeTeamName, 'Vitesse Arnhem')
        self.assertEqual(self.match.awayTeamName, 'FC Utrecht')

    def test_calculate_minutes(self):
        mins = self.match.calculateMinutes()
        self.assertEqual(mins, '18:00')
Example #23
0
    for line in f:
        line = line.replace("\n", "")
        something = line.replace(" ", "")
        if len(something) > 0:
            if count % 2 == 0:
                dh_dict[i + 3].append(line)
            else:
                rashi_comments[i + 3].append(line)
            count += 1
    f.close()
for i in range(20):
    book[str(i + 3)] = get_text(title_book + "." +
                                AddressTalmud.toStr("en", i + 3))
    lines = len(book[str(i + 3)])
    if len(dh_dict[i + 3]) > 0:
        match_obj = Match(in_order=True, min_ratio=70, guess=False)
        result = match_obj.match_list(dh_dict[i + 3], book[str(i + 3)])
        matched += getMatched(result)
        total += getTotal(result)
        guess += getGuesses(result)
        non_match += getNotMatched(result)
        log_info = getLog(i + 3, result, dh_dict, rashi_comments)
        if log_info != []:
            log.append(log_info)
        result_dict = {}
        for key in result:
            line_n = result[key][0]
            if line_n in result_dict:
                result_dict[line_n] += 1
            else:
                result_dict[line_n] = 1
Example #24
0
            just_added_dh = False
        before_dh = ""
        temp_text = ""
result = {}
guess = 0
no_guess = 0
for daf in dh_dict.keys():
    if len(dh_dict[daf]) != len(comm_dict[daf]):
        pdb.set_trace()

brackets_file = open('brackets.txt', 'w')
for daf in dh_dict.keys():
    last_one = max(dh_dict.keys())
    text = get_text(masechet + "." + AddressTalmud.toStr("en", daf))
    try:
        match_obj = Match(in_order=True, min_ratio=77, guess=False, range=True)
    except:
        pdb.set_trace()
    dh_arr = []
    for i in range(len(dh_dict[daf])):
        if len(dh_dict[daf][i]) > 0:
            dh_arr.append(dh_dict[daf][i])
    try:
        result[daf] = match_obj.match_list(
            dh_arr, text, masechet + " " + AddressTalmud.toStr("en", daf))
    except:
        pdb.set_trace()
    for i in range(len(comm_dict[daf])):
        if (daf, i) in before_dh_dict:
            comm_dict[daf][i] = before_dh_dict[(
                daf, i)] + "<b>" + dh_dict[daf][i] + "</b>" + comm_dict[daf][i]
Example #25
0
        if (configuration["game_mode"]=="fight"):
            configuration["nb_players_team"]=1

        difficulty=int(configuration["difficulty"])
        nb_players_team=int(configuration["nb_players_team"])
        match_length=int(configuration["duration"])
        west_team_index,east_team_index=0,1
        (teamA_filename,west_team_index,teamB_filename,east_team_index)=select_teams(display,nesfont,mainClock,west_team_index,east_team_index)
        if (teamA_filename=="?"):
            configuration["exit_menu"]="no"
            
        
    
    #players_human_teamA,players_human_teamB,difficulty,nb_players_team,match_length,teamA_filename,teamB_filename=call_all_menus(display,nesfont,mainClock)

    match=Match(teamA_filename,teamB_filename)
    match.show_loading(display,nesfont)   
    match.init(players_human_teamA,nb_players_team,players_human_teamB,nb_players_team,difficulty,match_length)
    
    while not match.is_finished:
        screen = display.get_surface()
        
        if (Inputs.player_just_Esc[1] or Inputs.player_just_Esc[2]):
            match.is_finished=True
        
        match.update()
        
        match.draw(screen,nesfont)
        
        display.update()
        mainClock.tick(50)
Example #26
0
def step_impl(context):
    context.match = Match(games=['11:4'], player1_id='1', player2_id='2')
Example #27
0
        except:
            comm = comm_dict_no_dh[current_perek][comment_key]
        if comm.find("<br>") == 0:
            comm = comm[4:]
        comm = comm.replace("<br><br>", "<br>")
        text = {
            "versionTitle": "Yad Ramah",
            "versionSource": "http://www.sefaria.org/",
            "language": "he",
            "text": [comm],
        }
        post_text(
            "Yad Ramah on Bava Batra, Perek " + str(current_perek) +
            ", Comment " + str(comment_key), text)

match_obj = Match(in_order=True, min_ratio=80, guess=False, range=True)
skipped_arr = []
result = {}
for current_perek in range(10):
    current_perek += 1
    print current_perek
    search_for = 0
    for daf in sorted(daf_dict[current_perek].keys()):
        print daf
        text = get_text("Bava Batra." + AddressTalmud.toStr("en", daf))
        dh_list = daf_dict[current_perek][daf]
        result[daf] = match_obj.match_list(
            dh_list, text, "Bava Batra " + AddressTalmud.toStr("en", daf))
        print result[daf]
        for key in result[daf]:
            if result[daf][key].find("0:") >= 0:
Example #28
0
from game import Game
from match import Match
from player import Player
from network import Network

####### Functions #######


def parseArgs():
    for arg in sys.args():
        # Do some stuff
        pass


def chooseRandom(board):
    #TODO make this only look at available moves
    print("Choosing a random move....")
    while True:
        move = np.random.randint(0, 9)
        if board[move] == 1:
            break
    return move


####### Main #######
if __name__ == "__main__":
    p1 = Player(1, 243, 0.2, 0.95)
    p2 = Player(2, 243, 0.2, 0.95)
    match = Match(100, p1, p2)
    print("Match Summary:", "\n\tPlayer 1 wins:", match.p1_wins,
          "\n\tPlayer 2 wins:", match.p2_wins, "\n\tDraws:", match.draws)
Example #29
0
        format(epoch + 1, loss_valid, acc_valid))
    print('---------------------------------------------------------')

game_window = pyglet.window.Window(height=512, width=512)
message_label = pyglet.text.Label(font_name='Times New Roman',
                                  font_size=36,
                                  color=(35, 203, 35, 255),
                                  x=game_window.width // 2,
                                  y=game_window.height // 2,
                                  anchor_x='center',
                                  anchor_y='center')
board_normal = pyglet.sprite.Sprite(
    pyglet.image.load('resources/board-normal.png'))
board_imgs = [[None for _ in range(8)] for _ in range(8)]
piece_held = None
match = Match()
ai_mode = True
promotion = None
old_pos = (0, 0)


def update_board():
    for i, j in itertools.product(range(8), repeat=2):
        piece = match.board.chessboard[i][j]
        if piece == '':
            continue
        if piece.isupper():
            piece_name = f'{piece}w'
        else:
            piece_name = f'{piece}b'
        board_imgs[i][j] = pyglet.sprite.Sprite(
	for line in f:
		line = line.replace("\n", "")
		something = line.replace(" ", "")
		if len(something) > 0:
			if count % 2 == 0:
				dh_dict[i+3].append(line)
			else:
				rashi_comments[i+3].append(line)
			count+=1
	f.close()		
for j in range(2):
	i = j+149
	book[str(i+3)] = get_text(title_book+"."+AddressTalmud.toStr("en", i+3))
	lines = len(book[str(i+3)])
	if len(dh_dict[i+3]) > 0: 
		match_obj=Match(in_order=True, min_ratio=70, guess=False)
		result=match_obj.match_list(dh_dict[i+3], book[str(i+3)])
		matched += getMatched(result)
		total += getTotal(result)
		guess += getGuesses(result)
		non_match += getNotMatched(result)
		log_info = getLog(i+3, result, dh_dict, rashi_comments)
		if log_info != []:
			log.append(log_info)
		result_dict = {}
		for key in result:
			line_n = result[key][0]
			if line_n in result_dict:
				result_dict[line_n] += 1
			else:
				result_dict[line_n] = 1
def main():
    #Wait for the data fetcher to ask resources from Football API
    #And for the DB to be up and ready
    time.sleep(60*5)
    #time.sleep(15)
    config = configparser.ConfigParser()
    config.read('../config/config.ini')
    dao = None
    if "POSTGRESQL" in config:
        dao = initPGConn(config)    
        if not dao:
            print("No connection could be established")
            return        
        else:
            print("Connected...")
    else:
        print("There are no postgre options in config.ini")
        return

    print("Finding new files to upload ...")
    competitions_list = {}
    with os.scandir('../data/init') as entries:
        for entry in entries:
            #league_{ID}_season_{YEAR}_...
            s = entry.name.replace('.json', '').split('_')
            if 'league' in s and not s[1] in competitions_list:
                competitions_list[s[1]] = set()
            if 'season' in s and s[3] not in competitions_list[s[1]]:
                competitions_list[s[1]].add(s[3])

    if not competitions_list:
        return

    areas_map = {}
    leagues_map = {}
    teams_map = {}

    areas_map = {}
    for area in dao.getAllAreas():
        if not areas_map.get(area.get_id()):
            areas_map[area.get_id()] = area

    leagues_map = {}
    for league in dao.getAllLeagues():
        if not leagues_map.get(league.get_id()):
            leagues_map[league.get_id()] = league

    teams_map = {}
    for team in dao.getAllTeams():
        if not teams_map.get(team.get_id()):
            teams_map[team.get_id()] = team
    print("Found {} leagues:".format(len(competitions_list)))
    for key, value in competitions_list.items():
        print("League {} with {} seasons".format(key, value))

    for league_id in competitions_list.keys():
        
        #Apro il file della lega
        with open('../data/init/league_{}.json'.format(league_id), 'r') as file:
            print("Opened json file for League {}".format(league_id))
            data = file.read()
            deserialized_data = json.loads(data)
            league = League.fromJson(data)
            print("League object created, ID: {} name: {}".format(league.get_id(), league.attributes['name']))
            area = Area.fromJson(json.dumps(deserialized_data['area']))
            print("Area object created, ID: {} name: {}".format(area.get_id(), area.attributes['name']))
            if not area.get_id() in areas_map:
                areas_map[area.get_id()] = area
                dao.scheduleAsyncQuery(area.create())
                print("Area does not exist, running CREATE query")
            elif areas_map.get(area.get_id) != area:
                dao.scheduleAsyncQuery(area.update())
                print("Area does exist, running UPDATE query")

            seasons_map = {}
            for season in dao.getAllSeasons():
                if not seasons_map.get(season.get_id()):
                    seasons_map[season.get_id()] = season

            dao.executeAsync()

            stats_query = ''
            #Ciclo per ogni stagione (per ora solo la prima)
            for s in deserialized_data['seasons'][:len(competitions_list[league_id])]:
                new_season = False
                season = Season.fromJson(json.dumps(s))
                print("Season object created, startDate: {}".format(season.attributes['start_date']))
                #Aggiorno la lista delle stagioni
                if not season.get_id() in seasons_map:
                    #### NB #########
                    #Iniziata una nuova stagione, devi salvare le SQUADRE
                    new_season = True
                    seasons_map[season.get_id()] = season
                    dao.scheduleAsyncQuery(season.create())
                    print("Season does not exist, running CREATE query")
                elif seasons_map.get(season.get_id) != season:
                    dao.scheduleAsyncQuery(season.update())
                    print("Season does exist, running UPDATE query")
                dao.executeAsync()

                matches_map = {}
                for match in dao.getAllMatches(season.get_id()):
                    if not matches_map.get(match.get_id()):
                        matches_map[match.get_id()] = match

                #Per ogni stagione guardo le squadre
                with open('../data/init/league_{}_season_{}_teams.json'.format(league_id, season.attributes['start_date'][:4]), 'r') as team_file:
                    print("Opened json file for Teams in season {}".format(season.attributes['start_date'][:4]))
                    team_data = team_file.read()
                    team_deserialized_data = json.loads(team_data)
                    print("Found {} teams".format(len(team_deserialized_data['teams'])))
                    new_teams_counter = 0; old_teams_counter = 0
                    for t in team_deserialized_data['teams']:   
                        team = Team.fromJson(json.dumps(t))
                        if not t['area']['id'] in areas_map:
                            print("Team {} name {} is in a different Area from League".format(team.get_id(), team.attributes['name']))
                            area = Area.fromJson(json.dumps(t['area']))
                            print("Area object created, ID: {} name: {}".format(area.get_id(), area.attributes['name']))
                            areas_map[area.get_id()] = area
                            dao.scheduleAsyncQuery(area.create())

                        if not team.get_id() in teams_map:
                            teams_map[team.get_id()] = team
                            dao.scheduleAsyncQuery(team.create())
                            new_teams_counter += 1
                        else:
                            dao.scheduleAsyncQuery(team.update())
                            old_teams_counter += 1
                        if new_season:
                            stats_query += 'INSERT INTO team_league (league_id, team_id, season_id) VALUES ({}, {}, {});'.format(league.get_id(), team.get_id(), season.get_id())

                    print("Found {} new teams and {} old teams".format(new_teams_counter, old_teams_counter))
                    dao.executeAsync()

                #E i match
                with open('../data/init/league_{}_season_{}_matches.json'.format(league_id, season.attributes['start_date'][:4]), 'r') as match_file:
                    print("Opened json file for Matches in season {}".format(season.attributes['start_date'][:4]))
                    match_data = match_file.read()
                    match_deserialized_data = json.loads(match_data)
                    print("Found {} matches".format(len(match_deserialized_data['matches'])))
                    new_matches_counter = 0; old_matches_counter = 0
                    for m in match_deserialized_data['matches']:
                        match = Match.fromJson(json.dumps(m))
                        if not match.get_id() in matches_map:
                            matches_map[match.get_id()] = match
                            dao.scheduleAsyncQuery(match.create())
                        elif matches_map.get(match.get_id()) != match:
                            dao.scheduleAsyncQuery(match.update())

                    print("Found {} new matches and {} old matches".format(new_matches_counter, old_matches_counter))
                    dao.executeAsync()

            if not league.get_id() in leagues_map:
                leagues_map[league.get_id()] = league
                dao.scheduleAsyncQuery(league.create())

            print("League found and created-> ID: {} name: {}".format(league.attributes['league_id'], league.attributes['name']))
            print("Now executing queries...")
            if dao.executeAsync():
                print("Succeded!")
            else:
                print("mmmmmmmm")
            if new_season:
                print("Executing stats queries...")
                if dao.executeQuery(stats_query):
                    print("Succeded!")
                else:
                    print("mmmmmmmm")

    with open('../queries/team_stats_view.sql', 'r') as sql_file:
        dao.executeQuery(sql_file.read())

    with open('../queries/team_standings_view.sql', 'r') as sql_file:
        dao.executeQuery(sql_file.read())            
    assert len(
        app.rank_inst
    ) != 0 or app.failed_to_match, 'It should not be that len(app.rank_inst) == 0' + str(
        app.name)

####

print('Institutions review applicants after interview, Rank Applicants')
for inst in all_institutions:
    print(
        str(inst.name) + ' is interviewing ' +
        str(len(inst.invite_interview)) + ' Applicants')
    inst.inst_rank_app(inst.invite_interview)
    print(
        str(inst.name) + ' is Ranking ' + str(len(inst.rank_list)) +
        ' Applicants')
    #print [x.quality for x in inst.rank_list]

####

print('Now for the Match')
m1 = Match(all_applicants, all_institutions, True)
m1.run_match()

####

print('Results')
r1 = StatsAndplots(all_applicants, all_institutions)
r1.stats()
#r1.plots()
Example #33
0
    def execute(self):
        print('Loading previous results')
        self._load_previous_results()

        print('Getting seed')
        seed_account_id = self._get_seed_account_id()
        champions_names = Champion._query_champions_names()
        match = Match(self.api_key, seed_account_id, champions_names, 10)
        result = match.execute()

        print('Successfully got seed account\n')

        self.viewed_matches.append(result['match'].get('gameId'))
        self.stack_accounts.extend(result['account_ids'])
        self.matches.append(result['match'])

        print('Beginning to crawl\n')

        while self.stack_accounts:
            start_time = time()
            
            random.shuffle(self.stack_accounts)
            account_id = self.stack_accounts.pop()

            print('accountId {}'.format(account_id))
            
            match = Match(self.api_key, account_id, champions_names, 10)
            result = match.execute()

            if not result['match']:
                print()
                continue

            match_id = result['match'].get('gameId')

            print('gameId {}'.format(match_id))

            if match_id in self.viewed_matches:
                print('[INFO] Already parsed this match\n')
                continue

            self.COUNTER += 1

            self.matches.append(result['match'])
            self.viewed_matches.append(match_id)

            print('Buffer size: {} matches '.format(len(self.matches)))

            if len(self.stack_accounts) < self.STACK_SIZE:
                self.stack_accounts.extend(result['account_ids'])
                print('[INFO] Extending stack to {} Ids'.format(len(self.stack_accounts)))

            if len(self.matches) > self.CHUNK_SIZE:
                print('[INFO] Saving matches to pickle')
                self._save_matches()
                self.matches = []

            if self.COUNTER > self.SIZE:
                break

            if self.COUNTER % 10 == 0:
                print('[INFO] Parsed {} games'.format(self.COUNTER))
            
            print('{:.2f}s seconds elapsed'.format(time() - start_time))
            print()

            gc.collect()

        self._save_matches()

        return
Example #34
0
 def prepMatch(self):
     best_eleven = self.getPlayers()[:11]
     self.__match = Match(1, best_eleven)
     return self.__match
Example #35
0
                if just_added_dh == False:
                    dh_dict[daf].append("")
                just_added_dh = False
            before_dh = ""
            temp_text = ""
result = {}
guess = 0
no_guess = 0
for daf in dh_dict.keys():
    if len(dh_dict[daf]) != len(comm_dict[daf]):
        pdb.set_trace()
for daf in dh_dict.keys():
    text = get_text("Shabbat." + AddressTalmud.toStr("en", daf))
    match_obj = Match(in_order=True,
                      min_ratio=70,
                      guess=False,
                      range=True,
                      maxLine=len(text) - 1)
    dh_arr = []
    for i in range(len(dh_dict[daf])):
        if len(dh_dict[daf][i]) > 0:
            dh_arr.append(dh_dict[daf][i])
    #try:
    result[daf] = match_obj.match_list(dh_arr, text)
    #except:
    #	pdb.set_trace()
    dh_count = 1
    for i in range(len(comm_dict[daf])):
        if (daf, i) in before_dh_dict:
            comm_dict[daf][i] = before_dh_dict[(
                daf, i)] + "<b>" + dh_dict[daf][i] + "</b>" + comm_dict[daf][i]
Example #36
0
from evaluator import ZeroEvaluator
from match import Match
from mcts import MonteCarloTS
from strategy_factory import StrategyFactory

if __name__ == "__main__":
    mctsFactory = StrategyFactory(MonteCarloTS,
                                  playerOneEvaluator=ZeroEvaluator(),
                                  playerTwoEvaluator=ZeroEvaluator(),
                                  maxSeconds=3)
    mctsFactoryTwo = StrategyFactory(MonteCarloTS,
                                     playerOneEvaluator=ZeroEvaluator(),
                                     playerTwoEvaluator=ZeroEvaluator(),
                                     maxSeconds=3)

    won, lost, drawn = 0, 0, 0
    for _ in range(1000):
        match = Match(mctsFactory, mctsFactoryTwo)
        match.play()
        one, two = match.playerOne.state.score()
        if one > two:
            won += 1
        elif two > one:
            lost += 1
        else:
            drawn += 1
        match.save("MCTS_VS_MCTS")
        print(".", end="")
    print(won, lost, drawn)
Example #37
0
import csv

potential_matches = []
fixtures = []

print("Loading all potential matches")
with open('resources/all_potential_matches.csv',
          mode='r',
          newline='',
          encoding='utf-8') as csvfile:
    csvreader = csv.reader(csvfile, delimiter=',')
    for row in csvreader:
        potential_matches.append(
            Match(hometeam=row[1],
                  awayteam=row[2],
                  homevenue=row[3],
                  preferredday=row[4],
                  preferredtime=row[5],
                  weight=int(row[6])))
print(len(potential_matches))

print("Loading all available spots")
with open('resources/all_available_spots.csv',
          mode='r',
          newline='',
          encoding='utf-8') as csvfile:
    csvreader = csv.reader(csvfile, delimiter=',')
    for row in csvreader:
        fixtures.append(
            Fixture(round=row[0],
                    when=datetime.strptime(row[1] + " " + row[3],
                                           "%d/%m/%Y %H:%M"),
					dh, comment = comment.split(".", 1)
					dh += ". "
					if onlyOne(dh, "כו'"):  
						dh1 = dh
						dh2 = ""
					elif dh.find("כו'")>=0:
						dh1, dh2 = dh.split("כו'", 1)
						dh1 += "כו' "	
					else:
						dh1 = dh
						dh2 = ""
				addDHComment(dh1, dh2, comment, category)
	else:
		print 'line did not start with 11'

match_obj=Match(in_order=False, min_ratio=80, guess=False, range=False)

last_daf = max(comm_dict.keys())
param = "off"
for daf in comm_dict:
	if daf==last_daf:
		param = "on"
	send_text = {
				"versionTitle": "Maharam Shif on "+masechet,
				"versionSource": "http://www.sefaria.org",
				"language": "he",
				"text": comm_dict[daf],
				}
	post_text("Maharam Shif on "+masechet+"."+AddressTalmud.toStr("en", daf), send_text, param)

def main():
    config = configparser.ConfigParser()
    config.read('../config/config.ini')
    dao = None
    if "POSTGRESQL" in config:
        dao = initPGConn(config)
        if not dao:
            print("No connection could be established")
            return
        else:
            print("Connected...")
    else:
        print("There are no postgre options in config.ini")
        return

    print("Finding new files to upload ...")

    competitions_list = set()
    with os.scandir('../data/updates') as entries:
        for entry in entries:
            s = entry.name.replace('.json', '').split('_')
            if 'league' in s and not s[1] in competitions_list:
                competitions_list.add(s[1])
    if not competitions_list:
        return

    today = date.today()

    areas_map = {}
    for area in dao.getAllAreas():
        if not areas_map.get(area.get_id()):
            areas_map[area.get_id()] = area

    leagues_map = {}
    for league in dao.getAllLeagues():
        if not leagues_map.get(league.get_id()):
            leagues_map[league.get_id()] = league

    teams_map = {}
    for team in dao.getAllTeams():
        if not teams_map.get(team.get_id()):
            teams_map[team.get_id()] = team

    ##Riempio le mappe dal DB

    for league_id in competitions_list:

        #Apro il file della lega
        with open('../data/updates/league_{}.json'.format(league_id),
                  'r') as file:
            data = file.read()
            deserialized_data = json.loads(data)
            league = League.fromJson(data)
            area = Area.fromJson(json.dumps(deserialized_data['area']))
            if not area.get_id() in areas_map:
                areas_map[area.get_id()] = area
                dao.scheduleAsyncQuery(area.create())
            elif areas_map.get(area.get_id) != area:
                dao.scheduleAsyncQuery(area.update())

            seasons_map = {}
            for season in dao.getAllSeasons():
                if not seasons_map.get(season.get_id()):
                    seasons_map[season.get_id()] = season

            stats_query = ''
            #Ciclo per ogni stagione (per ora solo la prima)
            for s in deserialized_data['seasons'][:1]:
                new_season = False
                season = Season.fromJson(json.dumps(s))
                #Aggiorno la lista delle stagioni
                if not season.get_id() in seasons_map:
                    #### NB #########
                    #Iniziata una nuova stagione, devi salvare le SQUADRE ( o rilanciare init.py )
                    new_season = True
                    seasons_map[season.get_id()] = season
                    dao.scheduleAsyncQuery(season.create())
                elif seasons_map.get(season.get_id) != season:
                    dao.scheduleAsyncQuery(season.update())

                matches_map = {}
                for match in dao.getAllMatches(season.get_id()):
                    if not matches_map.get(match.get_id()):
                        matches_map[match.get_id()] = match

                if new_season:
                    with open(
                            '../data/init/league_{}_season_{}_teams.json'.
                            format(league_id,
                                   season.attributes['start_date'][:4]),
                            'r') as team_file:
                        team_data = team_file.read()
                        team_deserialized_data = json.loads(team_data)
                        for t in team_deserialized_data['teams']:
                            team = Team.fromJson(json.dumps(t))
                            if not team.get_id() in teams_map:
                                teams_map[team.get_id()] = team
                                dao.scheduleAsyncQuery(team.create())
                            else:
                                dao.scheduleAsyncQuery(team.update())

                            stats_query += 'INSERT INTO team_league (league_id, team_id, season_id) VALUES ({}, {}, {});'.format(
                                league.get_id(), team.get_id(),
                                season.get_id())

                #E i match
                #league_ID_season_YEAR_updated_matches_DATE
                with open(
                        '../data/updates/league_{}_season_{}_updated_matches_{}.json'
                        .format(league_id, season.attributes['start_date'][:4],
                                today.strftime("%Y_%m_%d")),
                        'r') as match_file:
                    match_data = match_file.read()
                    match_deserialized_data = json.loads(match_data)
                    for m in match_deserialized_data['matches']:
                        match = Match.fromJson(json.dumps(m))
                        if not match.get_id() in matches_map:
                            matches_map[match.get_id()] = match
                            dao.scheduleAsyncQuery(match.create())
                        elif matches_map.get(match.get_id) != match:
                            dao.scheduleAsyncQuery(match.update())

            if not league.get_id() in leagues_map:
                leagues_map[league.get_id()] = league
                dao.scheduleAsyncQuery(league.create())
            elif leagues_map.get(league.get_id) != league:
                dao.scheduleAsyncQuery(league.update())

            print("League found and created-> ID: {} name: {}".format(
                league.attributes['league_id'], league.attributes['name']))
            print("Executing queries...")
            if dao.executeAsync():
                print("Succeded!")
            else:
                print("mmmmmmmm")
			match = re.search(marker, line)
			if match:
				line = line.replace(match.group(0), "")
			if perek_num in dh_dict:
				dh_dict[perek_num].append(line)
			else:
				dh_dict[perek_num] = []
				dh_dict[perek_num].append(line)
f.close()
#at end of this, for each comm[perek is a list of rambam's comments and for each perek is a list of the dhs
#for each perek, figure out how many mishnayot are in that perek, grab them all and send them to match with list of dhs for that perek
for j in range(perek_num):
	perek = {}
	perek[j+1] = get_text(title_book+"."+str(j+1))
	if len(dh_dict[j+1]) > 0: 
		match_obj=Match(in_order=True, min_ratio=70, guess=False)
		result = match_obj.match_list(dh_dict[j+1], perek[j+1], j+1)
		matched += getMatched(result)
		total += getTotal(result)
		guess += getGuesses(result)
		non_match += getNotMatched(result)
		log_info = getLog("http://dev.sefaria.org/"+title_comm, j+1, result)
		if log_info != []:
			log.append(log_info)
		#for each key which tracks a dh and a comm, its value is the mishna number corresponding to it
		#when a particular mishna number is corresponded to more than once by two or more dhs, and when the 
		#comments are the same for those dhs, then combine the dhs and just post one comment,
		#otherwise			
		comm_dict = {}
		result_dict = {}
		prev_comm = ""
Example #41
0
class Client:
    def __init__(self):
        self.args = get_args()
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.match = Match()
        self.searcher = Searcher()
        self.side = 'B'
        self.last_packet = -1

    def run(self):
        self.sock.connect((self.args.host, self.args.port))
        while True:  #Client Main Loop
            # Game things

            data = self.s_recv(1024, "B")

            if not data:
                break

            if self.match.board.score <= -MATE_LOWER:
                print("You lost")
                break

            if self.match.board.score <= -MATE_LOWER:
                print("You won")
                break

            # Fire up the engine to look for a move.
            move, score = self.searcher.search(self.match.board, secs=2)

            if score == MATE_UPPER:
                print("Checkmate!")

    def s_recv(self, size, expected_type):  #Received messages handler

        try:
            msg = self.sock.recv(size)
            data = pickle.loads(msg)
        except EOFError:
            print("Your opponent has timed out! GG!!")
            return 0
        except ConnectionAbortedError:
            print("Server has aborted connection with you :(")

        if (data[0] == "B"):  #receives board from server
            self.match.upgradeBoard(data[1:])
            print_pos(self.match.board)
            return 1

        elif (data[0] == "Y"):  #its your turn, make a move
            # We query the user until she enters a (pseudo) legal move.
            self.side = data[1]
            if self.side == self.last_packet:
                print("Received a duplicated packet")
                return 1
            self.last_packet = self.side
            move = None
            while move not in self.match.board.gen_moves():
                print(self.side + ' ', end='')
                match = re.match('([a-h][1-8])' * 2, input('Make a move: '))
                if match:
                    move = parse(match.group(1)), parse(match.group(2))
                else:
                    # Inform the user when invalid input (e.g. "help") is entered
                    print("Please enter a move like g8f6")

            self.match.board = self.match.board.move(move)

            #if self.side == "W":
            print_pos(self.match.board.rotate()
                      )  #Updates the board and rotate so player sees his move
            #else:
            #print_pos(self.match.board)

            try:
                self.sock.send(pickle.dumps(move))
            except ConnectionAbortedError:
                print("Server has aborted connection with you :( ")

            return 1

        elif (data[0] == "U"):  #Update the board
            # Update the client with adversary (pseudo) legal move.
            move = data[1:]
            self.match.board = self.match.board.move(move[0])
            if self.side == "B":
                print("Your opponent move: ",
                      render(move[0][0]) + render(move[0][1]))
                print_pos(
                    self.match.board
                )  #Updates the board and rotate so player sees his move
            else:
                print("Your opponent move: ",
                      render(119 - move[0][0]) + render(119 - move[0][1]))
                print_pos(self.match.board)

            return 1

    def printBoard(self, board):
        board.printBoard()
Example #42
0
if __name__ == "__main__":
    modelFactory = StrategyFactory(
        MonteCarloTS,
        playerOneEvaluator=ModelEvaluator(1, "../models/6x6eval.tf"),
        playerTwoEvaluator=ModelEvaluator(-1, "../models/deepeval.tf"),
        maxSeconds=3,
        alpha=1)
    modelFactoryTwo = StrategyFactory(
        MonteCarloTS,
        playerOneEvaluator=ModelEvaluator(2, "../models/6x6eval.tf"),
        playerTwoEvaluator=ModelEvaluator(-1, "../models/6x6eval.tf"),
        maxSeconds=3,
        alpha=1)

    won, lost, drawn = 0, 0, 0
    for _ in range(100):
        for _ in range(10):
            match = Match(modelFactory, modelFactoryTwo)
            match.play()
            one, two = match.playerOne.state.score()
            if one > two:
                won += 1
            elif two > one:
                lost += 1
            else:
                drawn += 1
            #match.save("MODEL_VS_MODEL")
            print(".", end="")
        print(won, lost, drawn)
		for i in range(curr_dh_count):
			if perek_num in comm:
				comm[perek_num].append(line)
			else:
				comm[perek_num] = []
				comm[perek_num].append(line)
		curr_dh_count = 0
f.close()

#at end of this, for each comm[perek is a list of rambam's comments and for each perek is a list of the dhs
#for each perek, figure out how many mishnayot are in that perek, grab them all and send them to match with list of dhs for that perek
for j in range(perek_num):
	perek = {}
	perek[j+1] = get_text(title_book+"."+str(j+1))
	if len(dh_dict[j+1]) > 0: 
		match_obj=Match(in_order=True, min_ratio=70, guess=False)
		result = match_obj.match_list(dh_dict[j+1], perek[j+1], j+1)
		matched += getMatched(result)
		total += getTotal(result)
		guess += getGuesses(result)
		non_match += getNotMatched(result)
		log_info = getLog("http://dev.sefaria.org/"+title_comm, j+1, result)
		if log_info != []:
			log.append(log_info)
		result_dict = {}
		for key in result:
			dh = "<b>"+dh_dict[j+1][key-1]+"</b>. "
			mishnah_n = result[key][0]
			if mishnah_n in result_dict:
				result_dict[mishnah_n] += 1
			else:
Example #44
0
 def add_match(self, new_when, the_team_a, the_team_b, the_venue, the_pool):
     match = Match(new_when, the_team_a, the_team_b, the_venue, the_pool)
     self.matches.append(match)
     return match
Example #45
0
def step_impl(context):
    context.match = Match(games=['11:4'], winner='2', loser='1')
Example #46
0
    def get_live_match_basic_data(self, event):
        self.renderer.click(event)
        teams = [name.text for name in event.find_elements_by_tag_name('span')]
        match_url = self.renderer.current_url

        return Match(MatchTitle(teams), match_url, '', self)
from combatents import AiPlayer
from match import Match
from training import load_model, MatchThread
from tqdm import tqdm

CYCLES = 500
NUM_THREADS = 20
NAMES = ['Carlos', 'Emar']

win_register = {name: 0 for name in NAMES}
win_register[None] = 0
models = [load_model(name) for name in NAMES]

for i in tqdm(range(CYCLES)):
    matches = [
        Match([AiPlayer(NAMES[i], models[i]) for i in range(2)])
        for _ in range(NUM_THREADS)
    ]
    threads = [MatchThread(match) for match in matches]
    for thread in threads:
        thread.start()

    for thread in threads:
        thread.join()

    for match in matches:
        win_register[match.get_winner().name] += 1

for name in NAMES:
    print(f"{name}'s win count: {win_register[name]}.")
Example #48
0
from datetime import datetime

from league import League
from match import MatchList, Match

import rugby_stats

# Load up a match, Wales v Scotland Six Nations 2018
WalesVScotland = Match.fromMatchId(291689)
print WalesVScotland
# print out the tries in the match
for tryEvent in WalesVScotland.matchEventList.getAllEventsForType(1):
    print tryEvent

# Load the champions cup from the database
championsCup = League.fromLeagueName('Champions Cup')

# get matches in the range of dates
# in this example these dates encompass Round 2 matches
startDate = datetime(2018, 10, 18)
endDate = datetime(2018, 10, 22)
roundTwoMatches = championsCup.getMatchesInDateRange(startDate, endDate)

# Get the number of tackles for each player
tackles = rugby_stats.getPlayerStatInMatches(roundTwoMatches, 'tackles')
print "\nChampions Cup Round Two Top Tacklers"
for player in tackles[:10]:
    print "Player: {}, Team: {}, Tackles: {}".format(player[0], player[1],
                                                     player[2])

# Get the leaders across the full champions cup season
last_daf = max(comm_dict.keys())
param = "off"
text_to_post = convertDictToArray(comm_dict)
send_text = {
			"versionTitle": "Shita Mekubetzet on "+masechet,
			"versionSource": "http://www.sefaria.org",
			"language": "he",
			"text": text_to_post,
			}
post_text("Shita Mekubetzet on "+masechet, send_text, "on")

links_to_post = []
for daf in dh_dict:
	text = get_text(masechet+"."+AddressTalmud.toStr("en", daf))
	match_obj=Match(in_order=True, min_ratio=85, guess=False, range=True)
	dh_arr = dh_dict[daf]
	result = match_obj.match_list(dh_arr, text, masechet+" "+AddressTalmud.toStr("en", daf))
	for key in result:
		line_n = result[key]
		line_n = line_n.replace("0:","")
		links_to_post.append({
				"refs": [
						 masechet+"."+AddressTalmud.toStr("en", daf)+"."+line_n, 
						"Shita Mekubetzet on "+masechet+"."+AddressTalmud.toStr("en", daf)+"."+str(key)
					],
				"type": "commentary",
				"auto": True,
				"generated_by": "Shita on "+masechet+" linker",
			 })
post_link(links_to_post)
 def do_start(self, arg):
     "Starts a game"
     self.match = Match(table=self)
     self.do_display(None)
        pass
        #print max([x.quality for x in app.applied_to]), float(s1) / len(app.applied_to), min([x.quality for x in app.applied_to]), len(app.applied_to), app.name
    else:
        print('to picky', index, app.quality)

#Institutions invite applicants for interview
for index, inst in enumerate(all_institutions):
    inst.interview(inst.applied)
    s1 = sum([x.quality for x in inst.invite_interview])
    #print float(s1) / len(inst.invite_interview), len(inst.invite_interview), inst.quality

#Applicants review the places they interviewed at, and choose who to rank, Then Rank them
for app in all_applicants:
    app.rank_interviewed_inst(app.interviewed_at)
    #print [x.quality for x in app.rank_inst]
    app.sort_rank_interviewed_inst()
    #print [x.quality for x in app.rank_inst]

#Institutions review applicants after interview, Rank Applicants
for inst in all_institutions:
    inst.rank_interviewed_inst(inst.invite_interview)
    #print [x.quality for x in inst.rank_list]

# Now for the Match
m1 = Match(all_applicants, all_institutions)
m1.run_match()

# Results
r1 = StatsAndplots(all_applicants, all_institutions)
r1.stats()
Example #52
0
import pytest
from match import Match

test_match = Match(1, "Bot")
'''
TODO: 
create moneypatch for allowing multiple case tests
 '''

# @pytest.fixture
# def childs_page_number_setup():
#     print("childs_page_number_setup")
#     test_match.childs_page_number = [456]


def test_data_fix(monkeypatch):
    def substitution():
        return [456]

    monkeypatch.setattr('main.Match.childs_page_number', substitution)
    # monkeypatch.setattr('Match.childs_page_number', substitution)

    print("---> test_match.childs_page_number ", test_match.childs_page_number)

    assert test_match.pseudo_query(2) == [3, 6, 9]


def test_data_fix_2():
    # def test_data_fix_2(childs_page_number_setup):
    print("test_match.childs_page_number ", test_match.childs_page_number)
    assert test_match.pseudo_query(1)[-1] == 2
def GUI_mainLoop(firstServer, numOfServes):
    mainLoop = GUI()

    player1 = Player("player1", 0, 200, 25)
    player2 = Player("player2", 1, 500, 25)
    currentMatch = Match(player1, player2, firstServer, numOfServes, 5)
    player1.textFunc = currentMatch.getScore
    player2.textFunc = currentMatch.getScore
    
    player1ScoreStr = str(currentMatch.score['player1'])
    player2ScoreStr = str(currentMatch.score['player2'])
    
    player1Score = TextObject("scorePlayer1", player1ScoreStr, 200, 25, 100)
    player2Score = TextObject("scorePlayer2", player2ScoreStr, 500, 25, 100)
    serveIndicatorPlayer1 = TextObject("servePlayer1", "-->", 525, 200, 125)
    serveIndicatorPlayer2 = TextObject("servePlayer2", "<--", 175, 200, 125)
    servingColor = (255,117,73)
    notServingColor = (200,199,211)
        
    keyMapping = initMapping()
    keyMapping["rshoulder"] = lambda x: currentMatch.scorePoint(x)
       
    
    mainLoop.addGUIObject(player1Score)
    mainLoop.addGUIObject(player2Score)
    mainLoop.addGUIObject(serveIndicatorPlayer1)
    mainLoop.addGUIObject(serveIndicatorPlayer2)
    mainLoop.setupGUI()

    running = True
    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
                break;
            if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
                running = False
                pygame.display.set_mode((700,400))
                break;
            if event.type == pygame.JOYBUTTONDOWN:
                button = parseButton(event)
                if button in keyMapping and keyMapping[button] is not None:
                    print(event)
                    if event.joy is not None:
                        score = None
                        if event.joy == 0:
                            score = keyMapping[button]("player1")
                        elif event.joy == 1:
                            score = keyMapping[button]("player2")
                    player1Score.text = str(score['player1'])
                    player2Score.text = str(score['player2'])
                    if(currentMatch.currentServer == "player1"):
                        serveIndicatorPlayer1.color = servingColor
                        serveIndicatorPlayer2.color = notServingColor
                    elif(currentMatch.currentServer == "player2"):
                        serveIndicatorPlayer1.color = notServingColor
                        serveIndicatorPlayer2.color = servingColor
                
                    print(score)
                
        
        
        pygame.display.update()
        mainLoop.update()
        mainLoop.draw()
        mainLoop.clock.tick(30)
        
    mainLoop.objects = []
Example #54
0
from evaluator import ZeroEvaluator
from match import Match
from mcts import MonteCarloTS
from strategy_factory import StrategyFactory

if __name__ == "__main__":
    mctsFactory = StrategyFactory(MonteCarloTS,
                                  playerOneEvaluator=ZeroEvaluator(),
                                  playerTwoEvaluator=ZeroEvaluator(),
                                  maxSeconds=1)
    mctsFactoryTwo = StrategyFactory(MonteCarloTS,
                                     playerOneEvaluator=ZeroEvaluator(),
                                     playerTwoEvaluator=ZeroEvaluator(),
                                     maxSeconds=3)

    won, lost, drawn = 0, 0, 0
    for _ in range(1):
        match = Match(mctsFactory, mctsFactoryTwo, size=8)
        match.play()
        one, two = match.playerOne.state.score()
        if one > two:
            won += 1
        elif two > one:
            lost += 1
        else:
            drawn += 1
        match.save()

    print(won, lost, drawn)
Example #55
0
from player import Player
from match import Match
from ships_models import *
from pprint import *

player_one = Player('Joao')
player_two = Player('Maria')

#board = SetUpBoard(8).get_board()

#ships names Encouracado, PortaAvioes, Destroyer, Submarino, BarcoDePatrulha
player_one.create_ship(Destroyer('1A'))
player_one.create_ship(PortaAvioes('1C'))
player_one.create_ship(Destroyer('3C'))
player_one.create_ship(Destroyer('2E'))
player_one.create_ship(Destroyer('1D'))
player_two.launch_bomb('3A')
player_two.launch_bomb('1A')
player_two.launch_bomb('3D')
player_two.launch_bomb('2A')
player_two.launch_bomb('3D')
player_two.launch_bomb('2E')
match = Match(player_one, player_two, 5)
print(match.bombs_positions)

print(match.get_result())
print(match.destroyed_ship())
pprint(match.board)
Example #56
0
from quixo import Quixo
from match import Match
import numpy as np

game = Quixo(5, 5)

state = game.initial_state()

match = Match(game, state, 20)

match.set_players()

match.start()
#
# count = 100
# wincount = [0, 0]
# draw = 0
# for i in range(count):
# 	game = Quixo(5, 5)
#
# 	state = game.initial_state()
#
# 	match = Match(game, state, 20)
# 	match.playersvs("random", "random")
# 	match.start()
				pdb.set_trace()
			if just_added_dh == False:
				dh_dict[daf].append("")
			just_added_dh = False
		before_dh =""
		temp_text = ""
result = {}
guess=0
no_guess=0
for daf in dh_dict.keys():
	if len(dh_dict[daf]) != len(comm_dict[daf]):
		pdb.set_trace()
for daf in dh_dict.keys():
	text = get_text("Gittin."+AddressTalmud.toStr("en", daf))
	try:
		match_obj=Match(in_order=True, min_ratio=70, guess=False, range=True, maxLine=len(text)-1)
	except:
		pdb.set_trace()
	dh_arr = []
	for i in range(len(dh_dict[daf])):
		if len(dh_dict[daf][i]) > 0:
			dh_arr.append(dh_dict[daf][i])
	result[daf] = match_obj.match_list(dh_arr, text)
	dh_count = 1
	'''
	if len(dh_dict[daf][i]) == 0, then comm_dict[daf][i] gets added to comm_dict[daf][i-1]+"<br>"
	'''
	for i in range(len(comm_dict[daf])):
		 if (daf, i) in before_dh_dict:
		 	comm_dict[daf][i] = before_dh_dict[(daf, i)]+"<b>"+dh_dict[daf][i]+"</b>"+comm_dict[daf][i]
		 else:
def parse_seasons(driver, player_dict):
    edge_ef_driver = EventFiringWebDriver(driver, LiquipediaNavListener())

    season_titles = []
    link_texts = []
    seasons = []

    # quick hack for cleaning the list... bottom of page contains redundant links!
    link_elements = edge_ef_driver.find_elements_by_partial_link_text("RLCS Season")
    for link_element in link_elements:
        if '-' in link_element.wrapped_element.text:
            # Get season title
            season_title = link_element.wrapped_element.text
            season_titles.append(season_title)
            link_texts.append(link_element.get_attribute("href"))

    season_num = 0
    for link in link_texts:
        is_final = "Finals" == season_titles[season_num].split('-')[1].strip()
        edge_ef_driver.get(link)
        time.sleep(20)

        # Get teams
        teamcards = edge_ef_driver.find_elements_by_class_name("teamcard")
        team_dict = parse_teams(teamcards, season_titles[season_num], player_dict)

        # Get matches
        matches = []
        if not is_final:
            # Group stage
            tables = edge_ef_driver.find_elements_by_class_name("matchlist table table-bordered collapsible")
            for table in tables:
                table_entries = table.find_elements_by_class_name("match-row")
                event = table.find_elements_by_tag_name("th").wrapped_element.text
                for match in table_entries:
                    team1 = team_dict.get(
                        table_entries[0].find_element_by_tag_name("span").get_attribute("data-highlightingclass"))
                    team2 = team_dict.get(
                        table_entries[3].find_element_by_tag_name("span").get_attribute("data-highlightingclass"))
                    team1_wins = table_entries[1].wrapped_element.text.lstrip()
                    team2_wins = table_entries[2].wrapped_element.text.lstrip()

                    if not team1_wins == "W" and not team1_wins == "FF":
                        for num in range(int(team1_wins)):
                            matches.append(Match(team1=team1, team2=team2, victor=team1,
                                                 season_title=season_titles[season_num], event=event))
                        for num in range(int(team2_wins)):
                            matches.append(Match(team1=team1, team2=team2, victor=team2,
                                                 season_title=season_titles[season_num], event=event))

            # Playoffs
            bracket_web_elements = edge_ef_driver.find_elements_by_class_name("bracket-column-matches")
            bracket_headers = [bracket.find_elements_by_class_name("bracket-header") for bracket in bracket_web_elements]
            if re.search(r"Season [789]", season_titles[season_num]):
                bracket_tuples = make_brackets(bracket_web_elements, bracket_headers, True)
            else:
                bracket_tuples = make_brackets(bracket_web_elements, bracket_headers, False)
            get_bracket_matches(season_titles[season_num], team_dict, bracket_tuples, matches)

        else:
            bracket_web_elements = edge_ef_driver.find_elements_by_class_name("bracket-column-matches")
            bracket_headers = [bracket.find_elements_by_class_name("bracket-header") for bracket in bracket_web_elements]

            bracket_tuples = make_brackets(bracket_web_elements, bracket_headers, False)

            get_bracket_matches(season_titles[season_num], team_dict, bracket_tuples, matches)

        season = Season(season_titles[season_num], player_dict, set(list(team_dict.values())), matches)
        seasons.append(season)
        edge_ef_driver.back()
        season_num += 1
        time.sleep(5)

    return seasons
    for line in f:
        line = line.replace("\n", "")
        something = line.replace(" ", "")
        if len(something) > 0:
            if count % 2 == 0:
                dh_dict[i + 3].append(line)
            else:
                rashi_comments[i + 3].append(line)
            count += 1
    f.close()
comments = 0
for i in range(54):
    book[str(i + 3)] = get_text(title_book + "." + AddressTalmud.toStr("en", i + 3))
    lines = len(book[str(i + 3)])
    if len(dh_dict[i + 3]) > 0:
        match_obj = Match(in_order=True, min_ratio=70, guess=False)
        result = match_obj.match_list(dh_dict[i + 3], book[str(i + 3)], "Keritot " + AddressTalmud.toStr("en", i + 3))
        matched += getMatched(result)
        total += getTotal(result)
        guess += getGuesses(result)
        non_match += getNotMatched(result)
        log_info = getLog(i + 3, result, dh_dict, rashi_comments)
        if log_info != []:
            log.append(log_info)
        result_dict = {}
        for key in result:
            line_n = result[key][0]
            if line_n in result_dict:
                result_dict[line_n] += 1
            else:
                result_dict[line_n] = 1
 def link(text):
     return (text &
             Match("<function>(\w*)</function>") >> "<link>\\1</link>")