Esempio n. 1
0
    def __init__(self, evManager, AIList):
        """
        evManager (EventManager): Allows posting messages to the event queue.

        Attributes:
            running (bool): True while the engine is online. Changed via Event_Quit().
            state (StateMachine()): control state change, stack data structure.
            AIList (list.str): all AI name list.
            player (list.player()): all player object.
        """
        self.evManager = evManager
        evManager.RegisterListener(self)

        self.running = False
        self.state = StateMachine()
        self.AIList = AIList
        self.player = []

        self.time = None
        self.preciseTime = None
        self.baseX = None
        self.baseY = None
        self.backgroundType = None
        self.birdType = None
        self.birdState = None
        self.birdX = None
        self.birdY = None
        self.birdVel = None
        self.swingVal = 1
        self.swingDir = 0
        self.swingMax = 16
        self.pipeType = None
        self.pipes = None
        self.score = None
        """
Esempio n. 2
0
    def __init__(self, evManager, AIList):
        """
        evManager (EventManager): Allows posting messages to the event queue.

        Attributes:
            running (bool): True while the engine is online. Changed via Event_Quit().
            state (StateMachine()): control state change, stack data structure.
            AIList (list.str): all AI name list.
            player (list.player()): all player object.
            chunk (list.list.chunk()): all chunk objct.
            TurnTo (int): current player.
        """
        self.evManager = evManager
        evManager.RegisterListener(self)

        self.running = False
        self.state = StateMachine()
        self.AIList = AIList
        self.player = []
        self.chunk = []
        self.TurnTo = 0
        self.floor = 0
        self.pos = None
        self.sh = 0
        self.key = -1

        random.seed(time.time())
Esempio n. 3
0
    def __init__(self, ev_manager, AI_names):
        """
        evManager (EventManager): Allows posting messages to the event queue.

        Attributes:
            running (bool): True while the engine is online. Changed via Event_Quit().
            state (StateMachine()): control state change, stack data structure.
            AIList (list.str): all AI name list.
            players (list.player()): all player object.
            TurnTo (int): current player
        """
        self.ev_manager = ev_manager
        ev_manager.register_listener(self)

        self.running = False
        self.state = StateMachine()
        self.AI_names = AI_names
        self.player_list = []
        self.colors = model_const.colors
        self.cutin_enable = True
        self.pet_list = []
        self.oil_list = []
        self.menu_robot_list = []
        self.menu_oil_list = []
        self.menu_timer = 0
        self.base_list = []
        self.priced_market_list = []
        self.turn_to = 0
        self.timer = 0
        self.items = []
        self.fadacai = False
        self.za_warudo_id = None

        for s in self.AI_names:
            if s == '--debug':
                self.cutin_enable = False
                self.AI_names.remove(s)
        self.init_menu()
        self.init_oil()
        self.init_pet()
        self.init_player()
        self.init_base()
        self.init_markets()

        self.scoreboard = Scoreboard(self.player_list, self.base_list)

        random.seed(time.time())
Esempio n. 4
0
    def __init__(self, evManager, AINames):
        # evManager (EventManager): Allows posting messages to the event queue.
        #
        # Attributes:
        #     running (bool): True while the engine is online. Changed via Event_Quit().
        #     state (StateMachine()): control state change, stack data structure.
        #     AINames (list.str): all AI name list.
        #     player (list.player()): all player object.
        #     TurnTo (int): current player

        self.evManager = evManager
        evManager.RegisterListener(self)

        self.running = False
        self.state = StateMachine()
        self.AINames = AINames
        self.players = []
        self.quaffles = []
        self.barriers = []
        self.goldenSnitch = None
        self.timer = 0
        self.TurnTo = 0

        random.seed(time.time())
Esempio n. 5
0
    def __init__(self, evManager, AINames):
        self.evManager = evManager
        evManager.RegisterListener(self)

        self.running = False
        self.state = StateMachine()
        self.AINames = AINames
        self.TurnTo = 0

        self.player_list = []

        self.wb_list = []
        self.bullet_list = []

        #self item
        ##explsion
        self.item_list = []
        self.ticks = 0
        self.score_list = [0, 0, 0, 0]
        self.endgame_ticks = 0
        self.have_scoreboard = [True] * 4

        self.gamenumber = 1
        self.special_scoreboard = [False] * 4
Esempio n. 6
0
class GameEngine(object):
    """
    Tracks the game state.
    """
    def __init__(self, evManager, AINames):
        """
        evManager (EventManager): Allows posting messages to the event queue.

        Attributes:
            running (bool): True while the engine is online. Changed via Event_Quit().
            state (StateMachine()): control state change, stack data structure.
            AIList (list.str): all AI name list.
            players (list.player()): all player object.
            TurnTo (int): current player
        """
        self.evManager = evManager
        evManager.RegisterListener(self)

        self.running = False
        self.state = StateMachine()
        self.AINames = AINames
        self.players = []
        self.TurnTo = 0

        random.seed(time.time())

    def notify(self, event):
        """
        Called by an event in the message queue. 
        """
        if isinstance(event, Event_EveryTick):
            cur_state = self.state.peek()
            if cur_state == STATE_PLAY:
                self.UpdateObjects()
        elif isinstance(event, Event_StateChange):
            # if event.state is None >> pop state.
            if event.state == None:
                # false if no more states are left
                if not self.state.pop():
                    self.evManager.Post(Event_Quit())
            elif event.state == STATE_RESTART:
                self.state.clear()
                self.state.push(STATE_MENU)
            else:
                # push a new state on the stack
                self.state.push(event.state)
        elif isinstance(event, Event_Move):
            self.SetPlayerDirection(event.PlayerIndex, event.Direction)
        elif isinstance(event, Event_Quit):
            self.running = False
        elif isinstance(event, Event_Initialize) or \
             isinstance(event, Event_Restart):
            self.Initialize()

    def Initialize(self):
        self.SetPlayer()

    def SetPlayer(self):
        # set AI Names List
        # "_" ==> default AI, "~" ==> manual player
        self.players, ManualPlayerNum = [], 0
        for index in range(modelConst.PlayerNum):
            if len(self.AINames) > index:
                PlayerName = self.AINames[index]
                if PlayerName == "~":
                    if ManualPlayerNum < modelConst.MaxManualPlayerNum:
                        ManualPlayerNum += 1
                    else:
                        self.AINames[index] = "_"
            else:
                if ManualPlayerNum < modelConst.MaxManualPlayerNum:
                    ManualPlayerNum += 1
                    self.AINames.append("~")
                else:
                    self.AINames.append("_")

        # init Player object
        for index in range(modelConst.PlayerNum):
            if self.AINames[index] == "~":
                Tmp_P = player("manual", index, False)
            elif self.AINames[index] == "_":
                Tmp_P = player("default", index, True)
            else:
                Tmp_P = player(self.AINames[index], index, True)
            self.players.append(Tmp_P)

    def SetPlayerDirection(self, playerIndex, direction):
        if self.players[playerIndex] != None:
            player = self.players[playerIndex]
            player.direction = direction

    def UpdateObjects(self):
        # Update players
        for player in self.players:
            player.UpdatePos()

    def run(self):
        """
        Starts the game engine loop.

        This pumps a Tick event into the message queue for each loop.
        The loop ends when this object hears a QuitEvent in notify(). 
        """
        self.running = True
        self.evManager.Post(Event_Initialize())
        self.state.push(STATE_MENU)
        while self.running:
            newTick = Event_EveryTick()
            self.evManager.Post(newTick)
Esempio n. 7
0
class GameEngine(object):
    """
    Tracks the game state.
    """
    def __init__(self, evManager, AIList):
        """
        evManager (EventManager): Allows posting messages to the event queue.

        Attributes:
            running (bool): True while the engine is online. Changed via Event_Quit().
            state (StateMachine()): control state change, stack data structure.
            AIList (list.str): all AI name list.
            player (list.player()): all player object.
            chunk (list.list.chunk()): all chunk objct.
            TurnTo (int): current player.
        """
        self.evManager = evManager
        evManager.RegisterListener(self)

        self.running = False
        self.state = StateMachine()
        self.AIList = AIList
        self.player = []
        self.chunk = []
        self.TurnTo = 0
        self.floor = 0
        self.pos = None
        self.sh = 0
        self.key = -1

        random.seed(time.time())

    def __str__(self):
        return "Model"

    def notify(self, event):
        """
        Receive events posted to the message queue.
        """
        if isinstance(event, Event_ColorChange):
            self.key = event.key
        elif isinstance(event, Event_FloorChange):
            self.floor = event.floor
            self.key = event.floor + 8
        elif isinstance(event, Event_ChoosePos):
            if not event.pos:
                self.pos = None
            else:
                self.pos = event.pos
        elif isinstance(event, Event_RenewData):
            #ans = os.system('sh wireless.sh')
            ans = subprocess.check_output(["sh", "wireless.sh"])
            self.sh = 0
            subans = ans[0:-1].decode("utf-8").split(' ')
            if subans[0] == "csie":
                if self.floor == 0:
                    print("-1 {} {} {} {}".format(self.pos[1], self.pos[0],
                                                  subans[1], subans[2]))
                    f_id = -1
                else:
                    print("{} {} {} {} {}".format(self.floor, self.pos[1],
                                                  self.pos[0], subans[1],
                                                  subans[2]))
                    f_id = self.floor
            elif subans[0] == "csie-5G":
                if self.floor == 0:
                    print("-2 {} {} {} {}".format(self.pos[1], self.pos[0],
                                                  subans[1], subans[2]))
                    f_id = -2
                else:
                    print("{} {} {} {} {}".format(self.floor + 7, self.pos[1],
                                                  self.pos[0], subans[1],
                                                  subans[2]))
                    f_id = self.floor + 7

            db = pymysql.connect("10.5.5.198", "nasa", "nasa2017", "nasafinal")
            cursor = db.cursor()
            sql_insert = "INSERT INTO sigblock_history(f_id, x_pos, y_pos, rssi, txrate) VALUES(%d, %d, %d, %f, %f)" % (
                f_id, self.pos[1], self.pos[0], float(
                    subans[1]), float(subans[2]))
            sql_insert2 = "INSERT INTO sigblock(f_id, x_pos, y_pos, rssi, txrate) VALUES(%d, %d, %d, %f, %f)" % (
                f_id, self.pos[1], self.pos[0], float(
                    subans[1]), float(subans[2]))
            sql_select = "SELECT COUNT(*) as count FROM sigblock WHERE f_id=%d AND x_pos=%d AND y_pos=%d" % (
                f_id, self.pos[1], self.pos[0])
            sql_update = "UPDATE sigblock SET rssi=%f, txrate=%f WHERE f_id=%d AND x_pos=%d AND y_pos=%d" % (
                float(subans[1]), float(
                    subans[2]), f_id, self.pos[1], self.pos[0])
            try:
                cursor.execute(sql_insert)
                db.commit()
            except:
                db.rollback()
            cursor.execute(sql_select)
            results = cursor.fetchall()
            if (results[0][0] == 0):
                try:
                    cursor.execute(sql_insert2)
                    db.commit()
                except:
                    db.rollback()
            else:
                try:
                    cursor.execute(sql_update)
                    db.commit()
                except:
                    db.rollback()
            db.close()
        elif isinstance(event, Event_StateChange):
            if not event.state:
                # pop a state
                if not self.state.pop():
                    # false if no more states are left
                    self.evManager.post(Event_Quit())
            else:
                # push a new state on the stack
                self.state.push(event.state)
        elif isinstance(event, Event_Quit):
            self.running = False

    def run(self):
        """
        Starts the game engine loop.

        This pumps a Tick event into the message queue for each loop.
        The loop ends when this object hears a QuitEvent in notify(). 
        """
        self.running = True
        self.evManager.post(Event_Initialize())
        self.state.push(STATE_MENU)
        while self.running:
            newTick = Event_EveryTick()
            self.evManager.post(newTick)
Esempio n. 8
0
class GameEngine(object):
    # Tracks the game state.
    def __init__(self, evManager, AINames):
        # evManager (EventManager): Allows posting messages to the event queue.
        #
        # Attributes:
        #     running (bool): True while the engine is online. Changed via Event_Quit().
        #     state (StateMachine()): control state change, stack data structure.
        #     AINames (list.str): all AI name list.
        #     player (list.player()): all player object.
        #     TurnTo (int): current player

        self.evManager = evManager
        evManager.RegisterListener(self)

        self.running = False
        self.state = StateMachine()
        self.AINames = AINames
        self.players = []
        self.quaffles = []
        self.barriers = []
        self.goldenSnitch = None
        self.timer = 0
        self.TurnTo = 0

        random.seed(time.time())

    def notify(self, event):
        # Called by an event in the message queue.
        if isinstance(event, Event_EveryTick):
            cur_state = self.state.peek()
            if cur_state == STATE_PLAY:
                self.UpdateObjects()
                self.Bump()
        elif isinstance(event, Event_EverySec):
            self.goldenSnitch.decaySpeed()
            cur_state = self.state.peek()
            if cur_state == STATE_PLAY:
                self.timer -= 1
            if self.timer <= 0:
                self.evManager.Post(Event_TimeUp())
        elif isinstance(event, Event_Move):
            self.SetPlayerDirection(event.PlayerIndex, event.Direction)
        elif isinstance(event, Event_ModeChange):
            self.ChangePlayerMode(event.PlayerIndex)
        elif isinstance(event, Event_SkillCard):
            self.ApplySkillCard(event.PlayerIndex, event.SkillIndex)
        elif isinstance(event, Event_Action):
            isConfirmed = self.ApplyAction(event.PlayerIndex,
                                           event.ActionIndex)
            if isConfirmed:
                self.evManager.Post(
                    Event_ConfirmAction(event.PlayerIndex, event.ActionIndex))
        elif isinstance(event, Event_StateChange):
            # if event.state is None >> pop state.
            if event.state == None:
                # false if no more states are left
                if not self.state.pop():
                    self.evManager.Post(Event_Quit())
            elif event.state == STATE_RESTART:
                self.state.clear()
                self.state.push(STATE_MENU)
            else:
                # push a new state on the stack
                self.state.push(event.state)
        elif isinstance(event, Event_TimeUp):
            self.evManager.Post(Event_StateChange(STATE_PRERECORD))
        elif isinstance(event, Event_Initialize) or \
             isinstance(event, Event_Restart):
            self.Initialize()
        elif isinstance(event, Event_Quit):
            self.running = False

    def Initialize(self):
        self.players = []
        self.quaffles = []
        self.barriers = []
        self.SetPlayer()
        self.SetQuaffle()
        self.SetGoldenSnitch()
        self.timer = initTime

    def SetPlayer(self):
        # set AI Names List
        # "_" ==> default AI, "~" ==> manual player
        ManualPlayerNum = 0
        for index in range(PlayerNum):
            if len(self.AINames) > index:
                PlayerName = self.AINames[index]
                if PlayerName == "~":
                    if ManualPlayerNum < MaxManualPlayerNum:
                        ManualPlayerNum += 1
                    else:
                        self.AINames[index] = "_"
            else:
                if ManualPlayerNum < MaxManualPlayerNum:
                    ManualPlayerNum += 1
                    self.AINames.append("~")
                else:
                    self.AINames.append("_")

        # init Player object
        for index in range(PlayerNum):
            if self.AINames[index] == "~":
                Tmp_P = player("manual", index, False)
            elif self.AINames[index] == "_":
                Tmp_P = player("default", index, True)
            else:
                Tmp_P = player(self.AINames[index], index, True)
            self.players.append(Tmp_P)

    def SetQuaffle(self):
        for quaffleId in range(0, numberOfQuaffles):
            quaffleTemp = Quaffle(quaffleId)
            self.quaffles.append(quaffleTemp)

    def SetGoldenSnitch(self):
        self.goldenSnitch = GoldenSnitch(0)

    def UpdateObjects(self):
        # Update players
        for player in self.players:
            player.tickCheck()
        # Update quaffles
        for quaffle in self.quaffles:
            score, playerIndex, minusScore, beShotPlayer = quaffle.tickCheck(
                self.barriers)
            for barrier in self.barriers:
                if beShotPlayer == barrier.playerIndex:
                    barrier.inactive()
            if playerIndex in range(PlayerNum):
                self.players[playerIndex].score += score
            if beShotPlayer in range(PlayerNum):
                self.players[beShotPlayer].score += minusScore
                if self.players[beShotPlayer].score < 0:
                    self.players[beShotPlayer].score = 0
        # Update golden snitch
        self.goldenSnitch.tickCheck(self.players)
        # Update barriers
        for barrier in self.barriers:
            # if barrier is inactive, remove it.
            if not barrier.tickCheck():
                self.barriers.remove(barrier)

    def Bump(self):
        # player to player
        for players in itertools.combinations(self.players, 2):
            lostBalls = players[0].bump(players[1])
            for lostBall in lostBalls:
                self.quaffles[lostBall[0]].deprive(lostBall[1], lostBall[2])
        # player to golden snitch
        distToGoldenSnitch = []
        for player in self.players:
            if player.takeball == -1 and not player.isFreeze and \
               player.mode == 1:
                distSquare = (player.position[0] - self.goldenSnitch.position[0]) ** 2 + \
                             (player.position[1] - self.goldenSnitch.position[1]) ** 2
                distToGoldenSnitch.append((distSquare**(1 / 2), player.index))

        if distToGoldenSnitch:
            dist, playerIndex = min(distToGoldenSnitch)
            if dist < distToCatchGoldenSnitch:
                self.players[playerIndex].takeball = 100
                self.players[playerIndex].score += scoreOfGoldenSnitch
                self.evManager.Post(Event_TimeUp())

        # player to quaffle
        for quaffle in self.quaffles:
            if quaffle.state in [0, 2]:
                distToQuaffle = []
                for player in self.players:
                    if player.takeball == -1 and not player.isFreeze:
                        distSquare = (player.position[0] - quaffle.position[0]) ** 2 + \
                                     (player.position[1] - quaffle.position[1]) ** 2
                        distToQuaffle.append(
                            (distSquare**(1 / 2), player.index))
                if distToQuaffle:
                    dist = min(distToQuaffle)
                    playerIndex = dist[1]
                    if dist[0] < distToCatchQuaffle:
                        self.players[playerIndex].takeball = quaffle.index
                        tmpQuaffleState = quaffle.state
                        hasCaught = quaffle.catch(playerIndex)
                        if not hasCaught:
                            self.players[playerIndex].score += scoreOfQuaffles[
                                tmpQuaffleState]

        # # barrier to player
        # for barrier in self.barriers:
        #     for player in self.players:
        #         if not barrier.playerIndex == player.index and \
        #                 barrier.bump(player, playerSpeed[player.mode]):
        #             player.position[0] -= dirConst[player.direction][0]*playerSpeed[player.mode]
        #             player.position[1] -= dirConst[player.direction][1]*playerSpeed[player.mode]
        # # barrier to quaffle
        # for barrier in self.barriers:
        #     for quaffle in self.quaffles:
        #         if quaffle.state in [0, 2] and barrier.bump(quaffle, quaffle.speed):
        #             if quaffle.isStrengthened:
        #                 barrier.inactive()
        #             else:
        #                 quaffle.state = 0
        #                 quaffle.playerIndex = -1
        #                 if barrier.direction in (1,5):
        #                     quaffle.direction = dirBounce[1][quaffle.direction]
        #                 if barrier.direction in (2,6):
        #                     quaffle.direction = dirBounce[2][quaffle.direction]
        #                 if barrier.direction in (3,7):
        #                     quaffle.direction = dirBounce[0][quaffle.direction]
        #                 if barrier.direction in (4,8):
        #                     quaffle.direction = dirBounce[3][quaffle.direction]

    def SetPlayerDirection(self, playerIndex, direction):
        if self.players[playerIndex] != None and self.players[
                playerIndex].isFreeze != True:
            player = self.players[playerIndex]
            player.direction = direction

    def ChangePlayerMode(self, playerIndex):
        if self.players[playerIndex] != None and self.players[
                playerIndex].power >= modeChangePower and self.players[
                    playerIndex].isFreeze == False:
            player = self.players[playerIndex]
            player.mode = 1 - player.mode
            player.isMask = False
            player.power -= modeChangePower

    def ApplySkillCard(self, playerIndex, skillIndex):
        # 0 = inVisible
        # 1 = empty power
        # 2 = stun all enermy
        # 3 = fake position
        Nowplayer = self.players[playerIndex]
        if skillIndex == 0:
            Nowplayer.isVisible = False
            Nowplayer.invisibleTimer = invisibleTime
            Nowplayer.AI.skill[HIDE] -= 1
        elif skillIndex == 1:
            for player in self.players:
                if player.index != playerIndex:
                    player.power = 0
            Nowplayer.AI.skill[DEMENTOR] -= 1
        elif skillIndex == 2:
            for player in self.players:
                if player.index != playerIndex:
                    player.isFreeze = True
                    player.freezeTimer = 57
            Nowplayer.AI.skill[STUNALL] -= 1
        elif skillIndex == 3:
            Nowplayer.AI.skill[SPECIAL] -= 1

    def ApplyAction(self, playerIndex, actionIndex):
        #ACTION_0 = 0   power throw / barrier
        #ACTION_1 = 1   stun / mask
        #ACTION_2 = 2   general throw
        if self.players[playerIndex] != None and self.players[
                playerIndex].isFreeze != True:
            player = self.players[playerIndex]
            if actionIndex == 0 and player.power >= powerShotPowerCost:
                if player.mode == 0:
                    ballData = self.players[playerIndex].shot()
                    if ballData != -1:
                        self.quaffles[ballData].throw(player.direction,
                                                      player.position, True)
                        player.power -= powerShotPowerCost
                        return True
                elif player.mode == 1 and player.power >= barrierPowerCost:
                    self.players[playerIndex].setBarrier()
                    if playerIndex == 0:
                        self.barriers.append(Barrier(playerIndex, [370, 0], 1))
                    elif playerIndex == 1:
                        self.barriers.append(
                            Barrier(playerIndex, [720, 370], 3))
                    elif playerIndex == 2:
                        self.barriers.append(
                            Barrier(playerIndex, [370, 720], 5))
                    elif playerIndex == 3:
                        self.barriers.append(Barrier(playerIndex, [0, 370], 7))
                    return True

            elif actionIndex == 1:
                if player.mode == 0 and player.power >= stunPowerCost:
                    player.power -= stunPowerCost
                    for playercheck in self.players:
                        if playercheck == player:
                            continue
                        else:
                            distSquare = (playercheck.position[0] - player.position[0]) ** 2 + \
                                    (playercheck.position[1] - player.position[1]) ** 2
                            if distSquare < (stunDistance)**2:
                                if playercheck.isMask == False:
                                    if playercheck.takeball != -1:
                                        ballData = playercheck.takeball
                                        if player.takeball != -1:
                                            playercheck.takeball = -1
                                            self.quaffles[ballData].deprive(
                                                playercheck.direction,
                                                playercheck.position)
                                        else:
                                            playercheck.takeball = -1
                                            player.takeball = ballData
                                            self.quaffles[
                                                ballData].playerIndex = player.index
                                    playercheck.freeze()
                                else:
                                    playercheck.maskTimer = 0
                                    playercheck.isMask = False
                    return True
                elif player.mode == 1 and player.power >= maskPowerCost:
                    player.isMask = True
                    player.maskTimer = maskTime
                    player.power -= maskPowerCost
                    return True
            elif actionIndex == 2 and player.mode == 0:
                ballData = player.shot()
                if ballData != -1:
                    self.quaffles[ballData].throw(player.direction,
                                                  player.position)
                    return True
            return False

    def run(self):
        ##############################################################
        # Starts the game engine loop.

        # This pumps a Tick event into the message queue for each loop.
        # The loop ends when this object hears a QuitEvent in notify().
        ##############################################################
        self.running = True
        self.evManager.Post(Event_Initialize())
        self.state.push(STATE_MENU)
        while self.running:
            newTick = Event_EveryTick()
            self.evManager.Post(newTick)
Esempio n. 9
0
class GameEngine(object):
    """
    Tracks the game state.
    """
    def __init__(self, evManager, AINames):
        self.evManager = evManager
        evManager.RegisterListener(self)

        self.running = False
        self.state = StateMachine()
        self.AINames = AINames
        self.TurnTo = 0

        self.player_list = []

        self.wb_list = []
        self.bullet_list = []

        #self item
        ##explsion
        self.item_list = []
        self.ticks = 0
        self.score_list = [0, 0, 0, 0]
        self.endgame_ticks = 0
        self.have_scoreboard = [True] * 4

        self.gamenumber = 1
        self.special_scoreboard = [False] * 4

    def initialize(self):
        self.grav_index = -1
        self.bombtimer = [-1] * 4
        self.ticks = 0
        self.tmp_score_list = [0, 0, 0, 0]
        self.endgame_ticks = 0
        self.init_wb_list()
        self.init_player_list()
        self.init_body_list()
        self.init_bullet_list()
        self.init_item_list()

    def init_wb_list(self):
        #init wb list
        self.wb_list = []
        for i in range(modelConst.wb_init_num):
            self.wb_list.append(White_Ball(Vec(-2, -2)))

    #init item list
    def init_item_list(self):
        self.item_list = []
        pass
        '''
        self.item_list = []
        for i in range(modelConst.item_init_num):
            rnd = randint(1,3)
            if rnd == 1:
                self.item_list.append(Explosive())
            if rnd == 2:
                self.item_list.append(Multibullet())
            if rnd == 3:
                self.item_list.append(Bigbullet())
        '''

    def init_player_list(self):
        tmp = []
        if len(self.player_list) > 0:
            for i in self.player_list:
                tmp.append(i.score)
        else:
            for i in range(modelConst.PlayerNum):
                tmp.append(0)
        self.player_list = []
        ManualPlayerNum = 0
        for index in range(modelConst.PlayerNum):
            if len(self.AINames) > index:
                PlayerName = self.AINames[index]
                if PlayerName == "~":
                    if ManualPlayerNum < modelConst.MaxManualPlayerNum:
                        ManualPlayerNum += 1
                    else:
                        self.AINames[index] = "_"
            else:
                if ManualPlayerNum < modelConst.MaxManualPlayerNum:
                    ManualPlayerNum += 1
                    self.AINames.append("~")
                else:
                    self.AINames.append("_")

        # init Player object
        for index in range(modelConst.PlayerNum):
            if self.AINames[index] == "~":
                Tmp_P = Head(index, "manual", False)
            elif self.AINames[index] == "_":
                Tmp_P = Head(index, "default", True)
            else:
                Tmp_P = Head(index, 'player' + self.AINames[index], True)
            self.player_list.append(Tmp_P)

    def init_body_list(self):
        # No bodies at start of game
        pass

    def init_bullet_list(self):
        # No bullets at start of game
        self.bullet_list = []

    def create_ball(self):
        # update and see if create new ball
        if len(self.wb_list) < modelConst.wb_max_num and random.randint(
                0, modelConst.wb_born_period * viewConst.FramePerSec) == 0:
            self.wb_list.append(White_Ball())

    def create_item(self):
        # update and see if create new item
        if len(self.item_list) < modelConst.item_max and random.randint(
                0, modelConst.item_born_period * viewConst.FramePerSec) == 0:
            rnd = random.randint(1, 3)
            if rnd == 1:
                self.item_list.append(Explosive(self.evManager))
            if rnd == 2:
                self.item_list.append(Multibullet())
            if rnd == 3:
                self.item_list.append(Bigbullet())

    def create_bullet(self):
        if self.ticks < modelConst.suddendeath_ticks:
            return
        if self.ticks == modelConst.suddendeath_ticks:
            self.evManager.Post(Event_SuddenDeath())
        if random.randint(
                0,
                modelConst.freq *
                int(viewConst.FramePerSec**2 /
                    (self.ticks - modelConst.suddendeath_ticks + 1))) == 0:
            screen_mid = Vec(viewConst.ScreenSize[1] / 2,
                             viewConst.ScreenSize[1] / 2)
            rndtheta = random.random() * 2 * pi
            self.bullet_list.append( Bullet(screen_mid, Vec(cos(rndtheta),sin(rndtheta)), -1, modelConst.bullet_radius,\
                                            modelConst.suddendeath_speed , 0 ) )

    def tick_update(self):
        #update bullets
        for i in range(len(self.bullet_list) - 1, -1, -1):
            item = self.bullet_list[i]
            #update failed means the bullet should become a white ball
            upd = item.update()
            if upd == None:
                for j in range(modelConst.bomb_amount):
                    theta = 2 * pi / modelConst.bomb_amount * j
                    self.bullet_list.append( Bullet(item.pos, Vec(cos(theta),sin(theta)), item.index, modelConst.bullet_radius,\
                                                    modelConst.suddendeath_speed , 0 ) )
                self.bullet_list.pop(i)
            elif not upd:
                self.wb_list.append(White_Ball(item.pos))
                self.bullet_list.pop(i)
        #update white balls
        if self.player_list[0].init_timer == -1:
            self.create_ball()
            self.create_item()
        self.create_bullet()
        #update items
        for item in self.item_list:
            item.update()

        for i in range(len(self.wb_list) - 1, -1, -1):
            item = self.wb_list[i]
            if not item.update(self.player_list):
                self.wb_list.pop(i)
        #update heads
        alive = 0
        for item in self.player_list:
            killed = 0
            if item.is_dash:
                for i in range(modelConst.dash_speed_multiplier):
                    killed |= item.update(self.player_list, self.wb_list,
                                          self.bullet_list, self.item_list,
                                          self.score_list, self.tmp_score_list)
            else:
                killed = item.update(self.player_list, self.wb_list,
                                     self.bullet_list, self.item_list,
                                     self.score_list, self.tmp_score_list)
            if killed == 1:
                self.evManager.Post(Event_PlayerKilled(item.index, item.pos))
            if item.is_alive:
                alive += 1
        if alive <= 1:
            self.endgame_ticks += 1
            if self.endgame_ticks > 300:
                if self.gamenumber == 5:
                    self.evManager.Post(Event_StateChange(STATE_ENDMATCH))
                else:
                    self.evManager.Post(Event_StateChange(STATE_ENDGAME))
                self.gamenumber += 1
        self.ticks += 1
        for i in range(4):
            if self.bombtimer[i] == 0:
                self.bomb(i)
                self.bombtimer[i] = -1
            elif self.bombtimer[i] > 0:
                self.bombtimer[i] -= 1

    def bomb(self, index):
        i = index * 2 + 1
        pos = (viewConst.GameSize[0] + viewConst.GameSize[1] //
               (modelConst.PlayerNum * 2),
               viewConst.GameSize[1] // (modelConst.PlayerNum * 2) * i)
        radius = int(viewConst.GameSize[1] // (modelConst.PlayerNum * 2) * 0.7)
        self.bullet_list.append(
            Bullet(pos, (self.player_list[index].pos - pos).normalize(), index,
                   radius, modelConst.bomb_speed, modelConst.bomb_a))
        self.have_scoreboard[index] = False

    def can_use_skill(self, index):
        player = self.player_list[index]
        return (self.ticks > 200) and player.is_alive and (self.endgame_ticks
                                                           == 0)

    def notify(self, event):
        """
        Called by an event in the message queue. 
        """
        if isinstance(event, Event_EveryTick):
            cur_state = self.state.peek()
            if cur_state == STATE_PLAY:
                # every tick update
                self.tick_update()
        elif isinstance(event, Event_MoveWayChange):
            cur_state = self.state.peek()
            if cur_state == STATE_PLAY:
                self.player_list[event.PlayerIndex].click(
                    self.bullet_list, self.wb_list)
        elif isinstance(event, Event_Skill):
            number = event.number
            player = self.player_list[event.PlayerIndex]
            cur_state = self.state.peek()
            if (cur_state not in [STATE_PLAY, STATE_CUTIN
                                  ]) or not self.can_use_skill(player.index):
                return
            if cur_state == STATE_PLAY:
                self.evManager.Post(Event_CutIn(player.index, number))
                self.state.push(STATE_CUTIN)
            else:
                self.state.pop()
                if number == 1:
                    self.item_list.append(Explosive(self.evManager,
                                                    player.pos))
                elif number == 2:
                    player.always_bigbullet = False
                    player.always_multibullet = True
                elif number == 3:
                    player.always_bigbullet = True
                    player.always_multibullet = False
                elif number == 4:
                    player.blast(self.bullet_list)
                elif number == 5:
                    self.bombtimer[player.index] = modelConst.bombtime
                elif number == 6:
                    player.is_rainbow = True
                    #player.rainbow_mode()
                elif number == 7:
                    self.grav_index = player.index

        elif isinstance(event, Event_StateChange):
            # if event.state is None >> pop state.
            if event.state is None:
                # false if no more states are left
                if self.state.peek() == STATE_ENDGAME:
                    modelConst.next_grav()
                    self.evManager.Post(Event_Initialize())
                if not self.state.pop():
                    self.evManager.Post(Event_Quit())
            elif event.state == STATE_RESTART:
                self.state.clear()
                self.state.push(STATE_MENU)
            elif event.state == STATE_ENDGAME:
                self.state.push(STATE_ENDGAME)
            elif event.state == STATE_ENDMATCH:
                self.state.clear()
                self.state.push(STATE_ENDMATCH)
            else:
                # push a new state on the stack
                self.state.push(event.state)
        elif isinstance(event, Event_Quit):
            self.running = False
        elif isinstance(event, Event_Initialize):
            self.initialize()
        elif isinstance(event, Event_Restart):
            self.initialize()
            self.score_list = [0, 0, 0, 0]
            self.have_scoreboard = [True, True, True, True]
            self.gamenumber = 1

    def run(self):
        """
        Starts the game engine loop.

        This pumps a Tick event into the message queue for each loop.
        The loop ends when this object hears a QuitEvent in notify(). 
        """
        self.running = True
        self.evManager.Post(Event_Initialize())
        self.state.push(STATE_MENU)
        while self.running:
            newTick = Event_EveryTick()
            self.evManager.Post(newTick)
Esempio n. 10
0
class GameEngine(object):
    """
    Tracks the game state.
    """
    def __init__(self, evManager, AIList):
        """
        evManager (EventManager): Allows posting messages to the event queue.

        Attributes:
            running (bool): True while the engine is online. Changed via Event_Quit().
            state (StateMachine()): control state change, stack data structure.
            AIList (list.str): all AI name list.
            player (list.player()): all player object.
        """
        self.evManager = evManager
        evManager.RegisterListener(self)

        self.running = False
        self.state = StateMachine()
        self.AIList = AIList
        self.player = []

        self.time = None
        self.preciseTime = None
        self.baseX = None
        self.baseY = None
        self.backgroundType = None
        self.birdType = None
        self.birdState = None
        self.birdX = None
        self.birdY = None
        self.birdVel = None
        self.swingVal = 1
        self.swingDir = 0
        self.swingMax = 16
        self.pipeType = None
        self.pipes = None
        self.score = None
        """
        TASK 1 & TASK 2 & TASK 3 & TASK 5
        self.size = {'bird': None,
                     'lowerPipe': None}
        self.pos = {'message': {'x': 0, 'y': 0},
                    'base': {'x': 0, 'y': 0},
                    'bird': {'x': 0, 'y': 0},
                    'gameover': {'x': 0, 'y': 0},
                    'lowerPipe': None,
                    'upperPipe': None}
        self.baseShift = 0
        self.vel = 0
        self.score = 0
        """

    def notify(self, event):
        """
        Called by an event in the message queue. 
        """
        if isinstance(event, Event_StateChange):
            # pop request
            if not event.state:
                # false if no more states are left
                if not self.state.pop():
                    self.evManager.Post(Event_Quit())
            else:
                # push a new state on the stack
                self.state.push(event.state)
        elif isinstance(event, Event_EveryTick):
            cur_state = self.state.peek()
            if cur_state == STATE_MENU:
                self.birdY += self.swingVal
                self.swingDir += self.swingVal
                if abs(self.swingDir) >= self.swingMax:
                    self.swingVal = -self.swingVal

                self.updateBase()
                self.updateBird()
                self.time += 1
            elif cur_state == STATE_PLAY:
                if self.checkscore():
                    self.evManager.Post(Event_Score())
                self.birdY += self.birdVel
                self.birdVel = min(self.birdVel + 1, MaxVel)
                self.updateBase()
                self.updateBird()
                self.updatePipe()
                self.time += 1

                if self.checkcrash():
                    self.evManager.Post(Event_Hit())
                    self.evManager.Post(Event_StateChange(None))
                    self.evManager.Post(Event_StateChange(STATE_DEAD))
            elif cur_state == STATE_STOP:
                pass
            elif cur_state == STATE_DEAD:
                if self.birdY + 24 <= self.baseY:
                    self.updateBird()
                    self.birdY += MaxVel
        elif isinstance(event, Event_Jump):
            self.birdVel = FlapVel
        elif isinstance(event, Event_Initialize):
            self.initialize()
        elif isinstance(event, Event_Quit):
            self.running = False
        """
        TASK 2 & TASK 3 & TASK 4 & TASK 5
        """

    def getRandomPipe(self):
        """
        TASK 2
        """
        pass

    def updateBase(self):
        """
        TASK 2
        """
        self.baseX = (self.baseX - MainSpeed) % ScreenSize[0]

    def updatePipe(self):
        """
        TASK 2
        """
        # update pipes
        for i in range(0, len(self.pipes), 2):
            self.pipes[i] -= MainSpeed

        # remove old pipes
        if len(self.pipes) > 0 and self.pipes[0] + PipeWidth < 0:
            self.pipes.remove(self.pipes[0])
            self.pipes.remove(self.pipes[0])

        # insert new pipes
        if len(self.pipes
               ) <= 0 or self.pipes[-2] + PipeWidth + 100 < ScreenSize[0]:
            self.pipes.append(ScreenSize[0])
            self.pipes.append(random.randint(-220, 0))

    def updateBird(self):
        """
        TASK 3
        """
        if self.time % 3 == 0:
            self.birdState = (self.birdState + 1) % 4

    def checkcrash(self):
        """
        TASK 4
        """
        rectBird = pg.Rect(self.birdX, self.birdY, 34, 24)
        for i in range(0, len(self.pipes), 2):
            rectPipe1 = pg.Rect(self.pipes[i], self.pipes[i + 1], PipeWidth,
                                PipeHeight)
            rectPipe2 = pg.Rect(self.pipes[i],
                                self.pipes[i + 1] + PipeHeight + PipeGap,
                                PipeWidth, PipeHeight)

            if rectBird.colliderect(rectPipe1) or rectBird.colliderect(
                    rectPipe2):
                return True

        rectBase1 = pg.Rect(self.baseX, self.baseY, 336, 112)
        rectBase2 = pg.Rect(self.baseX - ScreenSize[0], self.baseY, 336, 112)

        if rectBird.colliderect(rectBase1) or rectBird.colliderect(rectBase2):
            return True

        return False

    def restart(self):
        """
        TASK 4 & TASK 5
        """
        pass

    def checkscore(self):
        """
        TASK 5
        """
        for i in range(0, len(self.pipes), 2):
            if self.birdX + 17 - self.pipes[
                    i] - 26 < 5 and self.birdX + 17 - self.pipes[i] - 26 > 0:
                self.score += 1
                return True

        return False

    def initialize(self):
        """
        init pygame event
        """
        """
        TASK 1 & TASK 2 & TASK 3
        """
        self.time = 1
        self.preciseTime = 22.09
        self.baseX = 0
        self.baseY = ScreenSize[1] * 0.8
        self.backgroundType = random.randint(0, 1)
        self.birdType = random.randint(0, 2)
        self.birdState = 0
        self.birdX = 40
        self.birdY = 244
        self.birdVel = 0
        self.pipeType = random.randint(0, 1)
        self.pipes = []
        self.score = 0

    def run(self):
        """
        Starts the game engine loop.

        This pumps a Tick event into the message queue for each loop.
        The loop ends when this object hears a QuitEvent in notify(). 
        """
        self.running = True
        self.evManager.Post(Event_Initialize())
        self.state.push(STATE_MENU)
        while self.running:
            newTick = Event_EveryTick()
            self.evManager.Post(newTick)
Esempio n. 11
0
class GameEngine(object):
    """
    Tracks the game state.
    """
    def __init__(self, ev_manager, AI_names):
        """
        evManager (EventManager): Allows posting messages to the event queue.

        Attributes:
            running (bool): True while the engine is online. Changed via Event_Quit().
            state (StateMachine()): control state change, stack data structure.
            AIList (list.str): all AI name list.
            players (list.player()): all player object.
            TurnTo (int): current player
        """
        self.ev_manager = ev_manager
        ev_manager.register_listener(self)

        self.running = False
        self.state = StateMachine()
        self.AI_names = AI_names
        self.player_list = []
        self.colors = model_const.colors
        self.cutin_enable = True
        self.pet_list = []
        self.oil_list = []
        self.menu_robot_list = []
        self.menu_oil_list = []
        self.menu_timer = 0
        self.base_list = []
        self.priced_market_list = []
        self.turn_to = 0
        self.timer = 0
        self.items = []
        self.fadacai = False
        self.za_warudo_id = None

        for s in self.AI_names:
            if s == '--debug':
                self.cutin_enable = False
                self.AI_names.remove(s)
        self.init_menu()
        self.init_oil()
        self.init_pet()
        self.init_player()
        self.init_base()
        self.init_markets()

        self.scoreboard = Scoreboard(self.player_list, self.base_list)

        random.seed(time.time())
        

    def notify(self, event):
        """
        Called by an event in the message queue. 
        """
        if isinstance(event, EventEveryTick):
            cur_state = self.state.peek()
            if cur_state == STATE_MENU:
                self.update_menu()
            elif cur_state == STATE_PLAY:
                self.update_objects()
            elif cur_state == STATE_CUTIN:
                self.update_cutin()
            
        elif isinstance(event, EventStateChange):
            # if event.state is None >> pop state.
            if event.state is None:
                # false if no more states are left
                if not self.state.pop() or event.state == STATE_ENDGAME:
                    self.ev_manager.post(EventQuit())
            elif event.state == STATE_RESTART:
                self.state.clear()
                self.state.push(STATE_MENU)
            else:
                # push a new state on the stack
                self.state.push(event.state)
        elif isinstance(event, EventMove):
            # Deal with Za Warudo
            if self.za_warudo_id is None or self.za_warudo_id == event.player_index:
                self.set_player_direction(event.player_index, event.direction)
        elif isinstance(event, EventTriggerItem):
            cur_state = self.state.peek()
            if cur_state != STATE_CUTIN:
                player = self.player_list[event.player_index]
                if player.item is not None:
                    player.use_item(self.ev_manager)
                else:
                    player.buy(self.priced_market_list)
        elif isinstance(event, EventObtainFaDaCai):
            cur_state = self.state.peek()
            if cur_state != STATE_CUTIN:
                self.items.append(FaDaCai(self.player_list, self.oil_list, self.base_list, event.player_index))
                self.items[0].trigger(self.ev_manager)
                player = self.player_list[event.player_index]
        elif isinstance(event, EventQuit):
            self.running = False
        elif isinstance(event, (EventInitialize, EventRestart)):
            pass  # self.initialize()
        elif isinstance(event, EventFaDaCaiStart):
            self.fadacai = True
        elif isinstance(event, EventFaDaCaiStop):
            self.fadacai = False
        elif isinstance(event, EventTheWorldStart):
            self.za_warudo_id = event.player_index
        elif isinstance(event, EventTheWorldStop):
            self.za_warudo_id = None
        elif self.cutin_enable and isinstance(event, EventCutInStart):
            self.cutin_timer = model_const.cutin_time
            self.state.push(STATE_CUTIN)

    def get_team_index(self, name):
        #getting the team_index of name
        if name == "master":
            return 11
        try:
            val = int(name)
        except ValueError:
            return 0
        if 1 <= val <= 10:
            return val
        return 0
    
    def init_player(self):
        # set AI Names List
        # "_" ==> default AI, "~" ==> manual player
        self.player_list, manual_player_num = [], 0
        for index in range(model_const.player_number):
            if len(self.AI_names) > index:
                PlayerName = self.AI_names[index]
                if PlayerName == "~":
                    if manual_player_num < model_const.max_manual_player_num:
                        manual_player_num += 1
                    else:
                        self.AI_names[index] = "_"
            else:
                if manual_player_num < model_const.max_manual_player_num:
                    manual_player_num += 1
                    self.AI_names.append("~")
                else:
                    self.AI_names.append("_")

        # init Player object
        for index in range(model_const.player_number):
            if self.AI_names[index] in ["~" or "Error"]:
                Tmp_P = Player("manual", index, 0, self.pet_list, model_const.default_equipments[index])
            elif self.AI_names[index] == "_":
                Tmp_P = Player("default", index, 0, self.pet_list, is_AI = True)
            else:
                Tmp_P = Player(self.AI_names[index], index, self.get_team_index(self.AI_names[index]), self.pet_list, is_AI = True)
            self.player_list.append(Tmp_P)
            
    def init_pet(self):
        self.pet_list = []
        for index in range(model_const.player_number):
            self.pet_list.append(Pet(index, model_const.base_center[index]))

    def init_markets(self):
        self.priced_market_list = [ Market(position, self.ev_manager) for position in model_const.priced_market_positions ]

    def set_player_direction(self, player_index, direction):
        if self.player_list[player_index] is not None:
            player = self.player_list[player_index]
            player.direction = Vec(model_const.dir_mapping[direction]) 
            if direction > 0:
                player.direction_no = direction

    def init_menu(self):
        robot = Menu_robot(100)
        menu_oil = Menu_oil(100)
        self.menu_robot_list.append(robot)
        self.menu_oil_list.append(menu_oil)

    def update_objects(self):
        if self.za_warudo_id is not None:
            pet = self.pet_list[self.za_warudo_id]
            pet.update(self.player_list, self.base_list) 
            player = self.player_list[self.za_warudo_id]
            player.update(self.oil_list, self.base_list, self.player_list, self.ev_manager)
            for player in self.player_list:
                player.update_collision(self.player_list, self.ev_manager)
        else:
            for item in self.items:
                item.update(self.ev_manager)
            self.try_create_oil()
            for player in self.player_list:
                player.update(self.oil_list, self.base_list, self.player_list, self.ev_manager)
            for player in self.player_list:
                player.update_collision(self.player_list, self.ev_manager)
            if self.timer % 2400 == 1000:
                for pet in self.pet_list:
                    pet.change_status(1)
            for pet in self.pet_list:
                pet.update(self.player_list, self.base_list)

            for oil in self.oil_list:
                oil.update()
            self.try_create_oil()

            for market in self.priced_market_list:
                market.update(self.player_list, self.oil_list, self.base_list, None)

            self.scoreboard.update()

            self.timer -= 1
            if self.timer == 0:
                self.ev_manager.post(EventStateChange(STATE_ENDGAME))

    def update_cutin(self):
        self.cutin_timer -= 1
        if self.cutin_timer == 0:
            self.state.pop()  # pop out STATE_CUTIN

    def update_menu(self):
        self.menu_timer += 1
        if self.menu_oil_list:
            self.menu_robot_list[0].pick(self.menu_oil_list)
        else:
            self.menu_robot_list[0].go_home()
        if self.menu_timer % 1200 == 0:
            self.menu_oil_list.append(Menu_oil(100))

    def init_oil(self):
        for _ in range(model_const.init_oil_number):
            self.create_oil()

    def create_oil(self):
        self.oil_list.append(new_oil())

    def try_create_oil(self):
        p = model_const.fadacai_oil_probability if self.fadacai else model_const.oil_probability
        max_oil_num = model_const.fadacai_max_oil_num if self.fadacai else model_const.max_oil_num
        p *= 2 * (max(max_oil_num - len(self.oil_list), 0)) / max_oil_num
        if random.random() < p:
            self.create_oil()

    def init_base(self) :
        # todo
        for index in range(model_const.player_number) :
            self.base_list.append(Base(index, model_const.base_center[index]))
    

    def run(self):
        """
        Starts the game engine loop.

        This pumps a Tick event into the message queue for each loop.
        The loop ends when this object hears a QuitEvent in notify(). 
        """
        self.running = True
        self.ev_manager.post(EventInitialize())
        self.state.push(STATE_MENU)
        self.timer = model_const.game_length
        while self.running:
            newTick = EventEveryTick()
            self.ev_manager.post(newTick)
Esempio n. 12
0
class GameEngine(object):
    """
    Tracks the game state.
    """
    def __init__(self, evManager, AINames):
        """
        evManager (EventManager): Allows posting messages to the event queue.

        Attributes:
            running (bool): True while the engine is online. Changed via Event_Quit().
            state (StateMachine()): control state change, stack data structure.
            AIList (list.str): all AI name list.
            players (list.player()): all player object.
            TurnTo (int): current player
        """
        self.evManager = evManager
        evManager.RegisterListener(self)

        self.running = False
        self.state = StateMachine()
        self.AINames = AINames
        self.players = []
        self.TurnTo = 0
        self.balls = set()

        random.seed(time.time())

    def notify(self, event):
        """
        Called by an event in the message queue. 
        """
        if isinstance(event, Event_EveryTick):
            cur_state = self.state.peek()
            if cur_state == STATE_PLAY:
                self.UpdateObjects()
        elif isinstance(event, Event_StateChange):
            # if event.state is None >> pop state.
            if event.state is None:
                # false if no more states are left
                if not self.state.pop():
                    self.evManager.Post(Event_Quit())
            elif event.state == STATE_RESTART:
                self.state.clear()
                self.state.push(STATE_MENU)
            else:
                # push a new state on the stack
                self.state.push(event.state)
        elif isinstance(event, Event_Move):
            self.SetPlayerDirection(event.PlayerIndex, event.Direction)
        elif isinstance(event, Event_Quit):
            self.running = False
        elif isinstance(event, Event_Initialize) or \
             isinstance(event, Event_Restart):
            self.Initialize()

    def Initialize(self):
        self.SetPlayer()
        self.SetBall()

    def SetPlayer(self):
        # set AI Names List
        # "_" ==> default AI, "~" ==> manual player
        self.players, ManualPlayerNum = [], 0
        for index in range(modelConst.PlayerNum):
            if len(self.AINames) > index:
                PlayerName = self.AINames[index]
                if PlayerName == "~":
                    if ManualPlayerNum < modelConst.MaxManualPlayerNum:
                        ManualPlayerNum += 1
                    else:
                        self.AINames[index] = "_"
            else:
                if ManualPlayerNum < modelConst.MaxManualPlayerNum:
                    ManualPlayerNum += 1
                    self.AINames.append("~")
                else:
                    self.AINames.append("_")

        # init Player object
        for index in range(modelConst.PlayerNum):
            if self.AINames[index] == "~":
                Tmp_P = player("manual", index, False)
            elif self.AINames[index] == "_":
                Tmp_P = player("default", index, True)
            else:
                Tmp_P = player(self.AINames[index], index, True)
            self.players.append(Tmp_P)

    def SetPlayerDirection(self, playerIndex, direction):
        if self.players[playerIndex] != None:
            player = self.players[playerIndex]
            player.direction = direction

    def SetBall(self):
        for _ in range(5):
            self.balls.add(Ball())

    def UpdateObjects(self):
        # Update players
        for player in self.players:
            player.UpdatePos()
        # Update balls
        for ball in self.balls:
            ball.UpdatePos()

        #manage catch the ball and send balls to destination
        for player in self.players:
            for ball in self.balls:
                if (player.pos[0] - ball.pos[0])** 2 + (player.pos[1] - ball.pos[1])** 2 \
                    <= (viewConst.playerRadius + viewConst.ballRadius)** 2:
                    if not player.full():
                        player.own_balls.append(ball)
                        self.calcBallScore(ball)
                    self.balls.remove(ball)
                    self.balls.add(Ball())

            for ball in player.own_balls:
                if abs(player.pos[0] - viewConst.destination[ball.color][0]) <= viewConst.destination[ball.color][2] \
                    and abs(player.pos[1] - viewConst.destination[ball.color][1]) <= viewConst.destination[ball.color][3]:
                    player.score += ball.score
                    player.own_balls.remove(ball)

    def calcBallScore(self, ball):
        destination = viewConst.destination[ball.color]
        ball.score = int(
            abs(destination[0] - ball.pos[0]) +
            abs(destination[1] - ball.pos[1]))
        if ball.level == 'triangle':
            ball.score *= 2
        elif ball.level == 'square':
            ball.score *= 3

    def run(self):
        """
        Starts the game engine loop.

        This pumps a Tick event into the message queue for each loop.
        The loop ends when this object hears a QuitEvent in notify(). 
        """
        self.running = True
        self.evManager.Post(Event_Initialize())
        self.state.push(STATE_MENU)
        while self.running:
            newTick = Event_EveryTick()
            self.evManager.Post(newTick)