当前位置: 首页>>代码示例>>Python>>正文


Python Simulation.simtick方法代码示例

本文整理汇总了Python中simulation.Simulation.simtick方法的典型用法代码示例。如果您正苦于以下问题:Python Simulation.simtick方法的具体用法?Python Simulation.simtick怎么用?Python Simulation.simtick使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在simulation.Simulation的用法示例。


在下文中一共展示了Simulation.simtick方法的2个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: Game

# 需要导入模块: from simulation import Simulation [as 别名]
# 或者: from simulation.Simulation import simtick [as 别名]

#.........这里部分代码省略.........
    def mainLoop(self, ):
        """The main loop of the game.
        """
        while self.run:
            self.handleEvents()
            self.updateGameState()
            self.clock.tick(60)
            self.draw()

    def draw_text(self, text, x, y):
        text_s = self.subfont.render(text, True, (255,255,255))
        text_r = text_s.get_rect()
        text_r.x = x
        text_r.y = y
        self.screen.blit(text_s, text_r)
        return text_r.bottom

    def draw(self):
        """
        """
        self.screen.blit(self.background, (0,0))
        self.screen.blit(self.goal.image, self.goal.getRect())
        if self.DEBUG:
            rect2 = pygame.Rect(0,0, 5*self.PPU, 2*self.PPU)
            rect2.center = self.goal.position
            pygame.draw.rect(self.screen, (255,0,0), rect2, 1)
        for entity in self.dogs:
            rect = entity.getRect()
            self.screen.blit(entity.image, rect)
            if self.DEBUG:
                dogsize = self.simulation.DOG_SIZE
                rect2 = pygame.Rect(0,0, dogsize[0]*self.PPU, dogsize[1]*self.PPU)
                rect2.center = entity.position
                pygame.draw.rect(self.screen, (255,0,0), rect2, 1)
        catrect = self.cat.getRect()
        self.screen.blit(self.cat.image, catrect)
        pygame.draw.circle(self.screen, (255,0,0), catrect.center,
                           int(round(self.simulation.CAT_RADIUS*self.PPU)), 1)

        next_y = self.draw_text("Wins: %d" % self.wins, 5, 5)
        next_y = self.draw_text("Losses: %d" % self.losses, 5, next_y)
        self.draw_text("Interest: %.8f" % self.interest, 5, next_y)
        pygame.display.flip()


    def handleEvents(self):
        """
        """
        for event in pygame.event.get():
            if event.type == QUIT:
                self.run = False
            elif event.type == KEYDOWN:
                if event.key in DIR_MAP:
                    self.input.keydown(DIR_MAP[event.key])
                elif event.key == K_ESCAPE:
                    self.run = False
            elif event.type == KEYUP:
                if event.key in DIR_MAP:
                    self.input.keyup(DIR_MAP[event.key])
        self.simulation.setCatMove(self.input.getDirection())


    def updateGameState(self):
        """
        """
        subtick = self.tickcount % self.TICKFACTOR
        percentage = subtick/self.TICKFACTOR

        # We're done with one round of game ticks, time for next sim tick
        if subtick == 0:
            # If simulation has not finished yet, keep ticking the simulation,
            # otherwise set game's gameover flag and update all entities to
            # final position, as we are on the final tick of this game
            if self.simstate["gameover"] == False:
                self.simstate = self.simulation.simtick()
                self.logger.gameTicked(self.simstate)
                self.cat.updateTarget(self._simToGamePosition(self.simstate["cat"]))
                for simdog, gamedog in zip(self.simstate["dogs"], self.dogs):
                    gamedog.updateTarget(self._simToGamePosition(simdog))
            else:
                self.gameover = True
                self.cat.updatePosition(1.0)
                for dog in self.dogs:
                    dog.updatePosition(1.0)

        if not self.gameover:
            self.cat.updatePosition(percentage)
            for dog in self.dogs:
                dog.updatePosition(percentage)

            self.tickcount += 1
        else:
            self.logger.gameEnded(self.simstate["win"])
            N, wins, interest = self.logger.getStats(1.0, 1.0, 1.0)

            self.wins = wins
            self.losses = N-wins
            self.interest = interest
            self.simulationInit()
            self.entityInit()
开发者ID:ircubic,项目名称:Master-Thesis,代码行数:104,代码来源:__init__.py

示例2: TestSimulation

# 需要导入模块: from simulation import Simulation [as 别名]
# 或者: from simulation.Simulation import simtick [as 别名]
class TestSimulation(unittest.TestCase):
    """Tests for the Simulation class
    """

    class mock_ai(object):
        """A mock AI callable for testing
        """

        def __init__(self, ):
            self.calls = 0
            self.cat = []
            self.goal = []
            self.dogs = []

        def __call__(self, current, cat, dogs, goal):
            """AI call. Stores data about the call and returns a default direction.

            Arguments:
            - `cat`: The cat position
            - `dogs`: The dog positions
            - `goal`: The goal position
            """
            self.dogs.append(dogs)
            self.cat.append(cat)
            self.goal.append(goal)
            self.calls += 1
            return "left"

    def setUp(self, ):
        """Set up a default starting state
        """
        self.cat_ai = self.mock_ai()
        self.dog_ai = self.mock_ai()
        self.DOGS = 5
        self.FIELDSIZE = (16,16)
        self.sim = Simulation(self.cat_ai, self.dog_ai,
                              field_size=self.FIELDSIZE, num_dogs=self.DOGS)

    def _all_in_stage(self, state):
        self.assertTrue(self._in_stage(state["cat"], self.sim.CAT_SIZE))
        for dog in state["dogs"]:
            self.assertTrue(self._in_stage(dog, (self.sim.DOG_RADIUS*2,
                                                 self.sim.DOG_RADIUS*2)))
        self.assertTrue(self._in_stage(state["goal"], self.sim.GOAL_SIZE))

    def _in_stage(self, x, size):
        return (x[0]-(size[0]*0.5) >= 0 and
                x[0]+(size[0]*0.5) <= self.FIELDSIZE[0] and
                x[1]-(size[1]*0.5) >= 0 and
                x[1]+(size[1]*0.5) <= self.FIELDSIZE[1])


    def testGetState(self, ):
        """Tests the getState function.

        Checks that the correct members exist in the state, and that they are of
        correct type.
        """

        state = self.sim.getState()
        self.assertItemsEqual(state.keys(), ["cat", "dogs", "gameover", "win", "updated", "goal"])
        self.assertTrue(isinstance(state["cat"], tuple))
        self.assertTrue(isinstance(state["dogs"], list))
        for dog in state["dogs"]:
            self.assertTrue(isinstance(dog, tuple))
        self.assertTrue(isinstance(state["goal"], tuple))
        self.assertTrue(isinstance(state["gameover"], bool))
        self.assertTrue(isinstance(state["win"], bool))
        self.assertTrue(isinstance(state["updated"], datetime))


    def testInit(self, ):
        """Test that the simulation is initialized correctly
        """

        state = self.sim.getState()
        self.assertEqual(len(state["dogs"]), self.DOGS)
        self.assertEqual(state["gameover"], False)
        self.assertEqual(state["win"], False)
        self._all_in_stage(state)


    def testSimtickWin(self, ):
        """Test the simtick method for a winning move
        """
        # Move cat to the right of the goal (so the ai moving left will win)
        goalright = self.sim._goal.getPosition()[0]+self.sim.GOAL_SIZE[0]*0.5
        self.sim._cat.setPosition([goalright+self.sim.CAT_SIZE[0]*0.5,0])
        old_state = self.sim.getState()
        new_state = self.sim.simtick()
        self.assertGreater(new_state["updated"], old_state["updated"])
        self.assertTrue(new_state["gameover"])
        self.assertTrue(new_state["win"])

        # Make sure it stops ticking after game is over
        done_state = self.sim.simtick()
        self.assertEqual(new_state, done_state)


    def testSimtickLose(self, ):
#.........这里部分代码省略.........
开发者ID:ircubic,项目名称:Master-Thesis,代码行数:103,代码来源:tests.py


注:本文中的simulation.Simulation.simtick方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。