def setUp(self):
     self.menu = Fake_menu()
     self.game = Game((800, 600), 40, self.menu)
     self.inputqueue = None
     self.display = Mocup_display(0)
     self.clock = Fake_clock()
     self.set_event([(0, -40, "D"), (40, 0, "R")], 200)
Exemple #2
0
    def getOutOfBounds(self, border=10):
        """Gets a Struct containing Rects that are just outside the camera boundaries."""
        bounds = self.getBounds()
        oobleft = Game.Rect(bounds.left-border, bounds.top-border,\
                              border,bounds.height+border*2)
        oobright = Game.Rect(bounds.right, bounds.top-border,\
                              border,bounds.height+border*2)
        oobtop = Game.Rect(bounds.left-border, bounds.top-border,\
                              bounds.width+border*2, border)
        oobbottom = Game.Rect(bounds.left-border, bounds.bottom,\
                              bounds.width+border*2, border)
        l = [r.move(-Game.scroll.x, -Game.scroll.y) for r in \
             oobleft, oobright, oobtop, oobbottom]

        return Struct(left=l[0], right=l[1], top=l[2], bottom=l[3])
Exemple #3
0
    def __init__(self, width=640, height=480, fps=60, scale=1):
        super(World, self).__init__(width, height, fps, scale)

        # camera position (this is a basis position for all drawing)
        self.camera = point.Point(0, 0)
        Game.scroll = Game.camera = self.camera

        # which object is the focus of the camera
        self.focus = None

        # how far away the camera (center of the screen) should be from the focus
        self._focusLead = None

        # how fast the camera should "catch up" to the focus
        self._followSpeed = 1.0

        # the boundaries of camera movement
        self._followMin, self._followMax = None, None

        # SDL uses 16-bit coordinates for drawing, so these are the maximum bounds
        # Range of a 16-bit integer = -32,678 to +32,767 (or -2**15 to 2**15 - 1)
        self._bounds = Game.Rect(-(1 << 15), (1 << 15) - 1, (1 << 16) - 1,
                                 (1 << 16) - 1)

        # the world's stages (game states)
        self._stages = []

        # the currently active stage, or None if no stage is active,
        # or stages are not being used
        self._activeStage = None
Exemple #4
0
 def __init__(self, resolution, block_size):
     self.window_size = resolution
     self.block_size = block_size
     self.display = DrawWindow(self.window_size)
     self.menu = Menu((self.window_size), Eventqueue(
         self.block_size), self.display)
     self.game = Game(self.window_size, self.block_size, self.menu)
Exemple #5
0
    def fromImage(cls, sheet, image, colors, *args, **kwargs):
        """Creates a new tilemap from an image.

           @param sheet: The SpriteSheet to use when creating the TileMap.
           @param image: The image to use as the basis for the TileMap.
           @param colors: A dictionary mapping color values to tile indices.
               Any color that is not in the colors dictionary is treated as
               a blank tile (index -1). The keys in the colors dict should
               be RGB or RGBA tuples.
        """
        if isinstance(image, basestring):
            image = Game.Image.load(image)

        rows = []
        pxarray = Game.PixelArray(image)

        for y in xrange(image.get_height()):
            thisRow = []
            for x in xrange(image.get_width()):
                r,g,b,a = image.unmap_rgb(pxarray[x][y])
                idx = colors.get((r,g,b,a),None)
                if idx is None:
                    idx = colors.get((r,g,b),-1)
                thisRow.append(idx)
            rows.append(thisRow)

        return cls(sheet, rows, *args, **kwargs)
Exemple #6
0
    def __init__(self, *args, **kwargs):
        super(Console, self).__init__(*args, **kwargs)

        self.x += self.width/2
        self.y += self.height/2
        
        self.textbox = text.Text('', size=self.size)
        self.textbox.background = Game.color('black')
Exemple #7
0
 def update(self):
     """Update the console."""
     if self.textbox.dirty > 0:
         rect = Game.Rect(0,max(0,self.textbox.height - self.height),
                          self.width,min(self.rect.height,self.textbox.rect.height))
         self.pixels = self.textbox.pixels.subsurface(rect)
         self.redraw()
         self.textbox.dirty = 0
Exemple #8
0
    def __init__(self, *args, **kwargs):
        # set a click handler, if we get one
        if 'click' in kwargs:
            self.click = kwargs['click']

        # text label
        # TODO: add more options?
        self.text = text.Text(kwargs.get('label',''),
                              color=kwargs.get('labelColor',Game.color('black')),
                              )

        # graphics
        self.graphic = kwargs.get('graphic',None)
        if isinstance(self.graphic, basestring):
            self.graphic = Image().load(self.graphic)

        # background
        self.bgColor = kwargs.get('bgColor', 'gray70')
        if isinstance(self.bgColor, basestring):
            self.bgColor = Game.color(self.bgColor)

        # border
        self.border = kwargs.get('border',8)

        # border color
        self.borderColor = kwargs.get('borderColor', None)

        # if we don't get a size, figure one out
        # TODO: if we get a graphic and text, make it the bigger of the two
        if 'size' not in kwargs:
            if self.graphic is not None:
                kwargs['size'] = self.graphic.size
            elif self.text is not None:
                kwargs['size'] = self.text.size
            else:
                kwargs['size'] = (0,0)

        kwargs['size'] += (self.border,self.border)

        super(Button, self).__init__(*args, **kwargs)

        self.pixels = Game.Surface((self.width,self.height),Game.Constants.SRCALPHA)
        self.pixels.fill(self.bgColor)
        self._drawBorder()
Exemple #9
0
    def __init__(self, items, depth=8, bounds=None):
        # the four sub trees
        self.nw = self.ne = self.se = self.sw = None

        # change a Group to a list
        # this can be useful when using World.getEntities()
        if isinstance(items, Game.Sprite.Group):
            items = items.sprites()

        depth -= 1
        if depth == 0 or not items:
            self.items = items
            return

        if bounds:
            bounds = Game.Rect(bounds)
        else:
            bounds = items[0].rect
            bounds = bounds.unionall([i.rect for i in items[1:]])

        cx = self.cx = bounds.centerx
        cy = self.cy = bounds.centery

        self.items = []
        nw_items = []
        ne_items = []
        se_items = []
        sw_items = []

        for item in items:
            # Which of the sub-quadrants does the item overlap?
            in_nw = item.rect.left <= cx and item.rect.top <= cy
            in_sw = item.rect.left <= cx and item.rect.bottom >= cy
            in_ne = item.rect.right >= cx and item.rect.top <= cy
            in_se = item.rect.right >= cx and item.rect.bottom >= cy

            # If it overlaps all 4 quadrants then insert it at the current
            # depth, otherwise append it to a list to be inserted under every
            # quadrant that it overlaps.
            if in_nw and in_ne and in_se and in_sw:
                self.items.append(item)
            else:
                if in_nw: nw_items.append(item)
                if in_ne: ne_items.append(item)
                if in_se: se_items.append(item)
                if in_sw: sw_items.append(item)

        # Create the sub-quadrants, recursively.
        if nw_items:
            self.nw = QuadTree(nw_items, depth, (bounds.left, bounds.top, cx, cy))
        if ne_items:
            self.ne = QuadTree(ne_items, depth, (cx, bounds.top, bounds.right, cy))
        if se_items:
            self.se = QuadTree(se_items, depth, (cx, cy, bounds.right, bounds.bottom))
        if sw_items:
            self.sw = QuadTree(sw_items, depth, (bounds.left, cy, cx, bounds.bottom))
Exemple #10
0
 def __init__(self, screen):
     
     self.game = Game(screen)
     self.screen = screen
     self.image = image_util.load_image("mainmenu.png")
     
     self.index = 0
 
     self.play_rect = Rect(275,200,245,70)
     self.controls_rect = Rect(275,290,245,70)
     self.quit_rect = Rect(275,380,245,70)
     
     self.credits_rect = Rect(610, 530, 180, 60)
     
     self.controlScreen = ControlScreen(self.game)
     self.creditsScreen = CreditsScreen(self.game)
     
     self.pressed = []
     for key in pygame.key.get_pressed():
         self.pressed.append( True )
Exemple #11
0
    def _render_text(self):
        """This is a helper method to render text to a surface with wrapping."""
        if self._autowidth:
            # "autowidth" means one line, no wrapping, and the left edge
            # stays in the same place
            textlines = [self.text]
            textheight = self.font.get_linesize()
            oldleft = self.left
            self.width = self.font.size(self.text)[0]
            self.x = oldleft + self.width / 2.
        else:
            textlines = self._wrap(self.text)
            textheight = len(textlines) * self.font.get_linesize()

        textwidth = self.width
        self.height = textheight

        # fix in case we're drawing black text
        if self.background is None and self.color == Game.rgb(0, 0, 0):
            ALPHA = Game.Constants.SRCALPHA
        else:
            ALPHA = 0

        surf = Game.Surface((textwidth, textheight), ALPHA)

        for lineno, line in enumerate(textlines):
            if self.background is not None:
                r = self.font.render(line, self.antialias, self.color,
                                     self.background)
            else:
                r = self.font.render(line, self.antialias, self.color)
            surf.blit(r, (0, lineno * self.font.get_linesize()))

        self.pixels = surf

        if self.background is None:
            # per-pixel alphas override colorkeys, so this line won't do anything
            # if the text is black
            self.pixels.set_colorkey((0, 0, 0), Game.Constants.RLEACCEL)

        self.redraw()
Exemple #12
0
    def followBounds(self, followMin=None, followMax=None):
        """Sets the range in which the camera is allowed to move.

           If both parameters, C{followMin} and C{followMax}, are None,
           then the game world's extents are set to be the same as the screen.
           
           @param followMin: The top-left corner of the game world.
           @param followMax: The bottom-right corner of the game world.
        """
        if followMin is None:
            followMin = point.Vector(0, 0)
        if followMax is None:
            followMax = point.Vector(self.width, self.height)

        # The minimum follow value is the top-left corner of the game world,
        # and the maximum is the bottom-right. We can just use followMin as is,
        # but we have to adjust followMax to take into account the size of the
        # screen. We do this _after_ setting the world boundaries, though,
        # because it saves typing and it might be slightly faster.
        self._followMin = point.Vector(followMin)
        self._followMax = point.Vector(followMax)
        self._bounds = Game.Rect(followMin, self._followMax - self._followMin)
        self._followMax -= (self.width, self.height)
        self._doCameraFollow()
Exemple #13
0
 def play(self):
     self.game.gameloop()
     if self.game.isGameOver:
         self.game = Game(self.screen)
     for x in xrange(len(self.pressed)):
         self.pressed[x] = True
class Tests(unittest.TestCase):
    def setUp(self):
        self.menu = Fake_menu()
        self.game = Game((800, 600), 40, self.menu)
        self.inputqueue = None
        self.display = Mocup_display(0)
        self.clock = Fake_clock()
        self.set_event([(0, -40, "D"), (40, 0, "R")], 200)

    def set_event(self, events, loops):
        self.inputqueue = Mocup_eventqueue(40, loops, events)

    def test_gameloop_runs_and_quits(self):
        self.game.game_loop(self.display, self.inputqueue, self.clock, None)

    def test_gameloop_runs_and_quits_if_snake_collides(self):
        event0 = (0, -40, "D")
        event1 = (-40, 0, "L")
        event2 = (0, 40, "U")
        event3 = (40, 0, "R")
        event4 = (0, -40, "D")
        events = [event0, event1, event2, event3, event4]
        self.set_event(events, None)
        self.game.game_loop(self.display, self.inputqueue, self.clock, None)
        game_state = self.menu.return_status()
        self.assertEqual(0, game_state)

    def test_game_loop_monitors_the_boarders_x_axis(self):
        test_status = True
        event0 = [(40, 0, "L")]
        self.set_event(event0, 1000)
        self.game.game_loop(self.display, self.inputqueue, self.clock, None)
        sprites = self.display.return_sprites()
        for group in sprites:
            for sprite in group:
                location = sprite.rect.center
                if location[0] not in range(20, 781):
                    test_status = False
        self.assertEqual(True, test_status)

    def test_game_loop_monitors_the_boarders_y_axis(self):
        test_status = True
        event0 = [(0, -40, "U")]
        self.set_event(event0, 1000)
        self.game.game_loop(self.display, self.inputqueue, self.clock, None)
        sprites = self.display.return_sprites()
        for group in sprites:
            for sprite in group:
                location = sprite.rect.center
                if location[1] not in range(20, 581):
                    test_status = False
        self.assertEqual(True, test_status)

    def test_game_loop_collisions_grow_points(self):
        test = False
        event0 = [(-40, 0, "L")]
        rewards_group = pygame.sprite.Group(Coin(), Coin(), Coin(), Coin())
        i = 20
        for sprite in rewards_group:
            sprite.rect.center = (i, 340)
            i += 40
        self.display = Mocup_display(1)
        self.set_event(event0, 500)
        self.game.game_loop(self.display, self.inputqueue, self.clock,
                            rewards_group)
        game_state = self.menu.return_status()
        if game_state in range(4, 6):
            test = True
        self.assertEqual(True, test)
Exemple #15
0
from random import choice
from gomoku_env import GomokuEnv
from gameloop import Game

try:  # python3 compatibility
    input = raw_input
except NameError:
    pass


def player1_turn(state):
    return choice(state.available_turns())


def player1_human_turn(state):
    _ = input("Type your turn as x,y: ")
    x, y = _.split(",")
    x, y = int(x.strip()), int(y.strip())
    return x, y


def player2_turn(state):
    return choice(state.available_turns())


env = GomokuEnv(board_size=15, win_len=5)
game = Game(env, player1_turn, player2_turn)
game.loop()
Exemple #16
0
from gameloop import Game

if __name__ == '__main__':
    # This is the games main-function.
    # This is the first function the game runs.

    # In this main-function, we simply create an instance of the Game()-class.
    game = Game()
Exemple #17
0
class MenuScreen:
    
    def __init__(self, screen):
        
        self.game = Game(screen)
        self.screen = screen
        self.image = image_util.load_image("mainmenu.png")
        
        self.index = 0
    
        self.play_rect = Rect(275,200,245,70)
        self.controls_rect = Rect(275,290,245,70)
        self.quit_rect = Rect(275,380,245,70)
        
        self.credits_rect = Rect(610, 530, 180, 60)
        
        self.controlScreen = ControlScreen(self.game)
        self.creditsScreen = CreditsScreen(self.game)
        
        self.pressed = []
        for key in pygame.key.get_pressed():
            self.pressed.append( True )
    
    def get_input(self):
        self.getEvents()
        self.getButtonPresses()
    
    def getEvents(self):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
            elif event.type == MOUSEBUTTONUP:
                pos = pygame.mouse.get_pos()
                if self.play_rect.collidepoint(pos):
                    self.index = PLAY
                    self.draw()
                    self.play()
                elif self.controls_rect.collidepoint(pos):
                    self.index = CONTROLS
                    self.draw()
                    self.controls()
                elif self.quit_rect.collidepoint(pos):
                    self.index = QUIT
                    self.quit()
                elif self.credits_rect.collidepoint(pos):
                    self.credits()
    
    def getButtonPresses(self):
        keys = pygame.key.get_pressed()

        # select
        if(keys[K_SPACE]):
            if not self.pressed[K_SPACE]:
                self.pressed[K_SPACE] = True
                self.select()
        else:
            self.pressed[K_SPACE] = False

        if(keys[K_RETURN]):
            if not self.pressed[K_RETURN]:
                self.pressed[K_RETURN] = True
                self.select()
        else:
            self.pressed[K_RETURN] = False
    
        # move
        if(keys[K_UP]):
            if not self.pressed[K_UP]:
                self.pressed[K_UP] = True
                self.up()
        else:
            self.pressed[K_UP] = False
        
        if(keys[K_DOWN]):
            if not self.pressed[K_DOWN]:
                self.pressed[K_DOWN] = True
                self.down()
        else:
            self.pressed[K_DOWN] = False
        
        if(keys[K_w]):
            if not self.pressed[K_w]:
                self.pressed[K_w] = True
                self.up()
        else:
            self.pressed[K_w] = False
    
        if(keys[K_s]):
            if not self.pressed[K_s]:
                self.pressed[K_s] = True
                self.down()
        else:
            self.pressed[K_s] = False

    def play(self):
        self.game.gameloop()
        if self.game.isGameOver:
            self.game = Game(self.screen)
        for x in xrange(len(self.pressed)):
            self.pressed[x] = True
    
    def controls(self):
        self.controlScreen.loop()
        for x in xrange(len(self.pressed)):
            self.pressed[x] = True
    
    def quit(self):
        sys.exit()

    def credits(self):
        self.creditsScreen.loop()
        for x in xrange(len(self.pressed)):
            self.pressed[x] = True

    def up(self):
        self.index -= 1
        if self.index < 0:
            self.index = MAX_INDEX
            
        self.draw()
    
    def down(self):
        self.index += 1
        if self.index > MAX_INDEX:
            self.index = 0
            
        self.draw()
    
    def select(self):
        if self.index is PLAY:
            self.play()
        elif self.index is CONTROLS:
            self.controls()
        elif self.index is QUIT:
            self.quit()

    def draw(self):
        self.screen.blit(self.image, (0,0))
        
        if self.index is PLAY:
            pygame.draw.rect(self.screen, (255,255,0), self.play_rect, 5)
        elif self.index is CONTROLS:
            pygame.draw.rect(self.screen, (255,255,0), self.controls_rect, 5)
        elif self.index is QUIT:
            pygame.draw.rect(self.screen, (255,255,0), self.quit_rect, 5)
            
        pygame.display.flip()
    
    def loop(self):
        while True:
            self.draw()
            self.get_input()
Exemple #18
0
 def getScreenRect(self):
     """Returns a Rect object containing the bounds of the screen."""
     if self.screen is not None:
         return self.screen.get_rect()
     else:
         return Game.Rect(0, 0, self.width, self.height)