Пример #1
0
def _find_moves(state, location, team, type, temp_deleted = []):
	direction = Teams.direction(team)
	if type == CheckerType.king():
		direction = 0

	empty_moves = []
	take_moves = []

	enemy = Teams.opposite(team)
	diagonals = _get_diagonals(location, direction)

	for square in diagonals:
		new_checker = state.get_checker_from_location(tuple(square))

		if new_checker == None or new_checker.location in temp_deleted:
			empty_moves.append(square)
			continue
		elif new_checker.team == enemy:
			dx = square[0] - location[0]
			dy = square[1] - location[1]

			new_square = (square[0] + dx, square[1] + dy)

			if not _valid_square(new_square):
				continue
			if state.get_checker_from_location(new_square) == None:
				take_moves.append(new_square)

	if not len(take_moves) == 0:
		return take_moves, True
	return empty_moves, False
def _find_moves(state, location, team, type, temp_deleted=[]):
    direction = Teams.direction(team)
    if type == CheckerType.king():
        direction = 0

    empty_moves = []
    take_moves = []

    enemy = Teams.opposite(team)
    diagonals = _get_diagonals(location, direction)

    for square in diagonals:
        new_checker = state.get_checker_from_location(tuple(square))

        if new_checker == None or new_checker.location in temp_deleted:
            empty_moves.append(square)
            continue
        elif new_checker.team == enemy:
            dx = square[0] - location[0]
            dy = square[1] - location[1]

            new_square = (square[0] + dx, square[1] + dy)

            if not _valid_square(new_square):
                continue
            if state.get_checker_from_location(new_square) == None:
                take_moves.append(new_square)

    if not len(take_moves) == 0:
        return take_moves, True
    return empty_moves, False
def GetAllTeamsWithTotals(stop_date):
    fixtures = LoadAllData(stop_date)

    teams = {}

    for fixture in fixtures:

        fix = fixtures.get(fixture)

        home_team = fix.hometeam.name
        away_team = fix.awayteam.name

        if home_team not in teams:
            teams[home_team] = Teams.Team(name=home_team)
        if away_team not in teams:
            teams[away_team] = Teams.Team(name=away_team)
        teams[home_team].update(fix.hometeam.goals_scored,
                                fix.hometeam.goals_allowed,
                                fix.hometeam.shots[0],
                                fix.hometeam.shots_on_target[0],
                                fix.hometeam.corners[0])
        teams[away_team].update(fix.awayteam.goals_scored,
                                fix.awayteam.goals_allowed,
                                fix.awayteam.shots[0],
                                fix.awayteam.shots_on_target[0],
                                fix.awayteam.corners[0])

    return teams
Пример #4
0
def init():
    screen = pygame.display.set_mode((1600, 900), pygame.DOUBLEBUF)
    board = GameBoard.GameBoard(screen, (8, 8))
    game_objects.menu = Menu.Menu(["Player vs Player", "Player vs Computer", "Quit"], screen)

    game_objects.board = board

    game_objects.overlay = Overlay.Overlay(screen, game_objects.board, False)
    game_objects.state = BoardState.BoardState(board, game_objects.overlay)

    for i in range(3):
        for j in range(8):

            if (i % 2) == 0:
                if not (j % 2) == 1:
                    add_checker(Teams.black(), (j, i + 5))
                    continue

            if not (i % 2) == 0:
                if (j % 2) == 1:
                    add_checker(Teams.black(), (j, i + 5))
                    continue

            add_checker(Teams.red(), (j, i))
    game_objects.game = Game.Game(game_objects.state, game_objects.board)
    game_objects.game.new_game(GameMode.player_v_player())
    run()
Пример #5
0
 def createTeam(self, requested_team_name, play_offense):
   """ Given a team name, returns the team object. """
   teams_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'teams')
   if requested_team_name == 'helios':
     print('Creating team Helios')
     team_name = 'HELIOS_' + ('left' if play_offense else 'right')
     team_dir = os.path.join(teams_dir, 'helios', 'helios-13Eindhoven')
     lib_dir = os.path.join(teams_dir, 'helios', 'local', 'lib')
     return Teams.Helios(team_name, team_dir, lib_dir,
                         binaryName='helios_player', host='localhost',
                         port=self._serverPort)
   elif requested_team_name == 'base':
     print('Creating team Agent2d (base)')
     team_name = 'base_' + ('left' if play_offense else 'right')
     team_dir = os.path.join(teams_dir, 'base')
     lib_dir = None
     return Teams.Agent2d(team_name, team_dir, lib_dir,
                          binaryName='sample_player', logDir=self._logDir,
                          record=self._record, host='localhost',
                          port=self._serverPort)
   elif requested_team_name == 'robocin':
     print('Creating team RoboCIN2d')
     team_name = 'RoboCIn_' + ('left' if play_offense else 'right')
     team_dir = os.path.join(teams_dir, 'robocin', 'src')
     lib_dir = None
     return Teams.RoboCIn(team_name, team_dir, lib_dir,
                          binaryName='robocin_player', logDir=self._logDir,
                          record=self._record, host='localhost',
                          port=self._serverPort)
   else:
     print('Unknown team requested: ' + requested_team_name)
     sys.exit(1)
Пример #6
0
    def right_click(self):
        if self._is_human_player():
            if len(self.current_clicks) <= 1:
                return

            deleted = GameAnalyser.check_move_is_valid(self.current_clicks,  self._state, self.current_team)

            if deleted == False:
                print "Invalid Move"
                self.current_clicks = []
                self._board_ui.clear_highlighted()
                return

            while (len(self.current_clicks)) > 1:
                start = self.current_clicks[0]
                end = self.current_clicks[1]

                if len(deleted) > 0:
                    self._state.move_checker(start, end)
                    self._state.remove_checker(deleted[0])
                    del deleted[0]
                else:
                    self._state.move_checker(start, end)

                del self.current_clicks[0]

            if not deleted == False:
                self.current_team = Teams.opposite(self.current_team)
            self.current_clicks = []
            self._board_ui.clear_highlighted()
Пример #7
0
    def __init__(self, state, board):
        self.mode = None
        self._state = state
        self._board_ui = board

        self.current_clicks = []
        self.current_team = Teams.black()
Пример #8
0
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowTitle('Auction Draft App')
        self.move(50, 25)

        self.teamNum = 0
        self.teamNames = []
        # ask for user to create or load draft
        self.choice = self.startDlg()

        if self.choice == 'Create':
            self.teamNum = self.getTeamNum()
            self.teamNames = self.getTeamNames(self.teamNum)
        elif self.choice == 'Load':
            self.teamNames = self.loadTeams()
            self.teamNum = len(self.teamNames)

        # creates object for Team.py and passes along variables to set up table
        self.teamObj = Teams.TeamView(self.choice, self.teamNum, self.teamNames)

        self.pld = Database(self.choice)

        # Window frames and positioning frames in grid
        self.search = Search()
        self.topPlayers = TopPlayers()
        self.display = Display()
        self.options = Options()
        self.bidding = Bidding()

        self.centralWidget = QWidget()
        self.centralLayout = QGridLayout()

        self.centralLayout.addWidget(self.topPlayers, 0, 0, 1, 3)
        self.centralLayout.addWidget(self.search, 1, 0, 1, 1)
        self.centralLayout.addWidget(self.display, 1, 1, 2, 2)
        self.centralLayout.addWidget(self.options, 3, 0, 1, 3)
        self.centralLayout.addWidget(self.bidding, 1, 0, 2, 1)
        self.centralLayout.addWidget(self.teamObj, 0, 0)
        self.centralWidget.setLayout(self.centralLayout)

        # Connecting frame buttons to methods
        self.search.searchBtn.clicked.connect(self.on_search_click)
        self.options.select.clicked.connect(self.on_select_click)
        self.options.start.clicked.connect(self.on_start_click)
        self.options.cancel.clicked.connect(self.on_reset_click)
        self.options.save.clicked.connect(self.on_save_click)
        self.bidding.winner.clicked.connect(self.on_winner_click)

        self.setStyleSheet("""
            QWidget {
                background-color: rgb(43, 45, 47);
                color: rgb(242, 243, 244);
            }
        """)

        self.setCentralWidget(self.centralWidget)
        self._createMenu()
        self._createToolBar()
def LoadTeamData(stop_date, input_team):
    CONST = _Const()
    data = Teams.csvopen(CONST.INPUT_FILE)
    next(data)

    fixtures = {}

    for row in data:
        date = dt.datetime.strptime(row[1], '%d/%m/%y')
        if date > stop_date:
            break
        fixture_date = dt.datetime.strptime(row[1], '%d/%m/%y').date()
        home_team = row[2]
        away_team = row[3]
        home_goals = int(row[4])
        away_goals = int(row[5])
        home_shots = int(row[11])
        away_shots = int(row[12])
        home_sht = int(row[13])
        away_sht = int(row[14])
        home_corners = int(row[17])
        away_corners = int(row[18])
        if row[6] == 'H': winner = 2
        elif row[6] == 'A': winner = -1
        elif row[6] == 'D': winner = 1

        if (home_team == input_team or away_team == input_team):
            id_value = home_team + '_' + away_team

            if id_value not in fixtures:
                fixtures[id_value] = Teams.Fixture(name=id_value,
                                                   fixture_date=fixture_date,
                                                   winner=winner)

            fixtures[id_value].hometeam = Teams.Team(name=home_team)
            fixtures[id_value].awayteam = Teams.Team(name=away_team)

            fixtures[id_value].hometeam.update(home_goals, away_goals,
                                               home_shots, home_sht,
                                               home_corners)
            fixtures[id_value].awayteam.update(away_goals, home_goals,
                                               away_shots, away_sht,
                                               away_corners)

    return fixtures
Пример #10
0
def add_checker(team, location):
    if location == (4, 0) or location == (7, 0):
        return
    red_checker = Resource.Resource("res/checker_red.png")
    black_checker = Resource.Resource("res/checker_black.png")
    res = None

    if team == Teams.red():
        res = red_checker
    else:
        res = black_checker

    checker = Checker.Checker(pygame.display.get_surface(), game_objects.board, res)
    checker.location = location
    checker.team = team
    checker.type = CheckerType.men()
    game_objects.state.add_checker(checker)
Пример #11
0
    def _draw_team_sidebar(self, team):
        text_title = None
        text_title_rendered = None
        stats = None

        if team == Teams.red():
            text_title = "Red Team"
            stats = self._red_stats
            start_x = self._board.get_padding()[0] + self._board.get_dimentions()[0]
        else:
            text_title = "Black Team"
            stats = self._black_stats
            start_x = 0

        text = ["Men     {}".format(stats[0]), "Kings   {}".format(stats[1]), "Score   {}".format(stats[2])]

        # Render ALL the things
        black = (0x00, 0x00, 0x00)
        grey = (0x44, 0x44, 0x44)

        title_rendered = self._sidebar_font_large.render(text_title, 1, black)
        text_rendered = []

        for item in text:
            text_rendered.append(self._sidebar_font.render(item, 1, grey))

            # Calculate the coordinates for everything
        text_padding = 10
        title_text_size = self._sidebar_font_large.size(text_title)
        total_height = sum(map(get_second, map(self._sidebar_font.size, text)))
        total_height += title_text_size[1]
        total_height += text_padding * (len(text) + 1)

        total_width = title_text_size[0]

        top_x = start_x + int(0.1 * self._board.get_padding()[0])
        top_y = (self._board.get_dimentions()[1] - total_height) / 2
        self._screen.blit(title_rendered, (top_x, top_y))

        curr_y = top_y + title_text_size[1] + text_padding
        height = self._sidebar_font.size("aa")[1]

        for item in text_rendered:
            self._screen.blit(item, (top_x, curr_y))

            curr_y += text_padding + height
Пример #12
0
    def _draw_current_team(self):
        size = None
        text = None

        if self.current_team == Teams.black():
            size = self._size_black_turn
            text = self._turn_black_text
        else:
            size = self._size_red_turn
            text = self._turn_red_text

        padding = self._board.get_padding()[1]

        x = (self._screen.get_size()[0] - size[0]) / 2
        y = self._board.get_dimentions()[1] + padding + (size[1] - padding) / 2

        self._screen.blit(text, (x, y))
Пример #13
0
    def __init__(self, screen, board, timer_in_use):
        self._screen = screen

        # Stats are in the form men, king, score
        self._black_stats = [0, 0, 0]
        self._red_stats = [0, 0, 0]

        @property
        def current_team(self):
            return self.current_team

        self.current_team = Teams.black()
        self._timer_in_use = timer_in_use

        self._timer_black = None
        self._timer_red = None
        self._board = board

        self._init_font()
Пример #14
0
	def king_checker(self, location):
		index = self._get_checker_index_from_location(location)
		checker = self.get_checker_from_location(location)
		if not checker:
			raise ValueError('No checker exists at given location')

		if checker.type == CheckerType.king():
			return

		if checker.team == Teams.red():
			self.red_kings += 1
		else:
			self.black_kings += 1

		checker.type = CheckerType.king()
		current_res = checker.res.res
		new_res = Resource.Resource(current_res.replace(".png", "_king.png"))
		checker.res = new_res
		checker._load_resource()
		self.checkers[index] = checker
    def __init__(self, teams=Teams.MLB, year='2015', playoffs=False, csv_mode=''):
        """ Prep class for scrapping for information.
        """
        if teams in Teams.LEAGUES:
            teams = Teams.TEAMS[teams](year)
        else:
            if not Teams.valid_teams_subset(year, teams):
                raise ValueError('{} contains one or more invalid entries.'
                                 .format(teams))
        self.year = year
        self.teams = teams
        self.playoffs = playoffs

        self.base_url = 'http://www.baseball-reference.com/'
        self.team_post = '-schedule-scores.shtml'

        self.csv = 'CSV'
        if csv_mode not in CSV:
            raise ValueError('{} is not found in {}.'
                             .format(csv_mode, CSV))
        self.csv_mode = csv_mode
        self.delimiter = ';'
Пример #16
0
	def _run_event(self, event):
		if not event.delete_pos:
			checker = self.get_checker_from_location(event.start)
			checker.animation_done_callback = self.event_completed

			if not event.start or not event.end:
				raise InvalidGameEventError("Event must be a delete event or move event")

			checker = self.get_checker_from_location(event.start)
			checker.animate_move(event.end)
			self.event_running = True

		else:
			index = self._get_checker_index_from_location(event.delete_pos)

			if self.checkers[index].team == Teams.red():
				self.red_checkers -= 1
			else:
				self.black_checkers -= 1

			del self.checkers[index]
			self.event_completed()

		self.update_stats()
Пример #17
0
 def new_game(self, mode):
     self.mode = mode
     self.current_team = Teams.black()
Пример #18
0
    def set_stats(self, team, stats):

        if Teams.black() == team:
            self._black_stats = stats
        else:
            self._red_stats = stats
Пример #19
0
 def render(self):
     self._draw_current_team()
     self._draw_team_sidebar(Teams.red())
     self._draw_team_sidebar(Teams.black())
Пример #20
0
    def _is_human_player(self):
        if self.current_team == Teams.black():
            return True

        # Previous condition => the team is red -> only human if in PvP
        return self.mode == GameMode.player_v_player()
Пример #21
0
	def __str__(self):
		return "{} Checker {}".format(Teams.to_string(self.team)[0].upper(), self.location)
Пример #22
0
	def team(self, team):
		if team != Teams.red() and team != Teams.black():
			raise ValueError('Team must be provided')

		self.team = team
Пример #23
0
# Inputs
input_date = input("Date (dd/mm/yy format): ")
avg_window_sz = input("Window size for rolling average: ")
stop_date = dt.datetime.strptime(input_date, '%d/%m/%y')

avg_window = int(avg_window_sz)

# Load the data
teams = dataLoader.GetAllTeamsWithTotals(stop_date)

# Calculate and build the graph
for team in teams.keys():
    print(team)
    input_team = team
    avg_shots = teams.get(input_team, None).shots
    avg_sht = teams.get(input_team, None).shots_on_target
    avg_corners = teams.get(input_team, None).corners
    shots_mov_avg = Teams.mov_avg(avg_shots, avg_window)
    sht_mov_avg = Teams.mov_avg(avg_sht, avg_window)
    corners_mov_avg = Teams.mov_avg(avg_corners, avg_window)
    plt.plot(shots_mov_avg, label="Shots on goal")
    plt.plot(sht_mov_avg, label="Shots on target")
    plt.plot(corners_mov_avg, label="Corners")
    plt.axis([0, 35, 0, 25])
    plt.title("Rolling average")
    plt.xlabel("Number of matches")
    plt.ylabel("Average value")
    plt.legend()
    plt.savefig(CONST.OUTPUT_PATH + team + '_avg.jpg')
    plt.clf()
Пример #24
0
teams = {}

fixtures = dataLoader.LoadAllData(dt.datetime.now())
output = open(CONST.OUTPUT_PATH + 'Parameters.txt','w')

for fixture in fixtures:
    
    fix = fixtures.get(fixture)
    
    home_team = fix.hometeam.name
    away_team = fix.awayteam.name
    home_goals = fix.hometeam.goals_scored
    away_goals = fix.awayteam.goals_scored

    if home_team not in teams:
        teams[home_team] = Teams.Team(name = home_team)
    if away_team not in teams:
        teams[away_team] = Teams.Team(name = away_team)
    teams[home_team].scored(home_goals)
    teams[away_team].scored(away_goals)

for team in teams.keys():
    input_team = team
    goal_list = []
    prob = []
    prob_err = []
    goal_no = []
    no_of_goals = []
    i = 0
    goal_list = teams.get(input_team).goals
    goal_list.sort()
Пример #25
0
                                    'react_time', 'user'
                                ]
                                messagewriter = csv.writer(
                                    csvfile,
                                    delimiter=';',
                                    quotechar='|',
                                    quoting=csv.QUOTE_MINIMAL)
                                messagewriter.writerow(fieldnames)
                                csvfile.close()

                            LogBuilder.crialogtotal(pathMulti, pathModule,
                                                    levelDBPath)

                            arrayContactos = Contacts.geraContactos(pathMulti)

                            Teams.criacaoDeEquipas(pathMulti)
                            arrayReturn = Teams.criarObjetosDeCriacaoDeEquipas(
                                pathMulti, arrayContactos)
                            arrayContactos = arrayReturn["contacts"]
                            dictionaryConversationDetails = arrayReturn[
                                "teams"]
                            arrayReturn.clear()

                            Calls.extrairEventCallsToFile(pathMulti)
                            arrayEventCall = Calls.criarObjetosDeEventCalls(
                                pathMulti, arrayContactos)

                            arrayReturn = Messages.findpadrao(
                                pathMulti, arrayContactos, user, tmCSV)
                            arrayMensagens = arrayReturn["mensagem"]
                            arrayCallOneToOne = arrayReturn["callOneToOne"]
Пример #26
0
	def update_stats(self):
		self.overlay.set_stats(Teams.red(), [self.red_checkers, self.red_kings, self.max_checkers_per_side - self.black_checkers])
		self.overlay.set_stats(Teams.black(), [self.black_checkers, self.black_kings, self.max_checkers_per_side - self.red_checkers])