コード例 #1
0
 def __init__(self, imagen, x, y):
     super().__init__(imagen, x, y)
     self.velocidad = Vector2(-200, 0)
     self.velocidad2 = Vector2(0, 200)
     self.contador = 0
     self.dir = choice([-1, 1])
     self.dir2 = choice([-1, 1])
コード例 #2
0
    def move(self):
        """El movimiento de Quetzalcoatl debe parte de la dirección que el jugador le da, esta dirección partirá de la 
        cabeza y cada segmento delcuerpo deberá seguir este movimiento.

        Args:
            offset (float): diferencia de distancia que se da de un lado a otro.
        """
        if self.direction != BasicCharacter.STOP:
            mov_x = self.position[0]
            mov_y = self.position[1]

            indices = range(len(self.body))
            for idx in indices[:0:-1]:
                self.body[idx].position = self.body[idx - 1].position
                self.body[idx].direction = self.body[idx - 1].direction
                self.body[idx].cshape.center = Vector2(self.body[idx].position[0], self.body[idx].position[1])

            self.body[0].position = self.position
            self.body[0].direction = self.direction
            self.body[0].cshape.center= Vector2(mov_x, mov_y)

            if self.direction == key.LEFT:
                mov_x -= self.width
            elif self.direction == key.RIGHT:
                mov_x += self.width
            elif self.direction == key.UP:
                mov_y += self.height
            elif self.direction == key.DOWN:
                mov_y -= self.height
                
            self.position = mov_x, mov_y
            self.cshape.center= Vector2(mov_x, mov_y)
コード例 #3
0
    def __init__(self):
        Layer.__init__(self)
        self.anchor = Vector2()
        self.add(
            Sprite(image=pyglet.resource.image('background-tetris.png'),
                   anchor=self.anchor))  # Background Image

        self.game_controller = game_controller.game_controller
        self.c_manager = self.game_controller.c_manager  # obtem instancia do gerenciador de colisao

        tmp_block = Block(Vector2(),
                          '')  # para obter as dimencoes da imagem do bloco
        init_pos_x = 250  # meio eixo x da tela
        init_pos_y = tmp_block.height / 2

        for i in range(23):
            blk = Block((init_pos_x - tmp_block.width, init_pos_y +
                         (i * tmp_block.height)),
                        block_color=BLOCK_WALL,
                        b_type="Left_Wall")
            blk.anchor = (blk.width / 2, blk.height / 2)
            self.add(blk)

            blk = Block((init_pos_x + (tmp_block.width * 16), init_pos_y +
                         (i * tmp_block.height)),
                        block_color=BLOCK_WALL,
                        b_type="Right_Wall")
            blk.anchor = (blk.width / 2, blk.height / 2)
            self.add(blk)

        #cria retangulo de colisao para paredes esquerda e direita
        self.c_manager.add(
            Collision_Rect(init_pos_x - tmp_block.width * 1.5,
                           tmp_block.width,
                           init_pos_y,
                           23 * tmp_block.height,
                           b_type="Left_Wall"))
        self.c_manager.add(
            Collision_Rect(init_pos_x - tmp_block.width / 2 +
                           (tmp_block.width * 16),
                           tmp_block.width,
                           init_pos_y,
                           23 * tmp_block.height,
                           b_type="Right_Wall"))

        for i in range(16):
            blk = Block((init_pos_x + (i * tmp_block.width), init_pos_y),
                        block_color=BLOCK_WALL,
                        b_type="Base_Floor")
            blk.anchor = (blk.width / 2, blk.height / 2)
            self.add(blk)

        #cria retangulo de colisao para chao
        self.c_manager.add(
            Collision_Rect(init_pos_x - tmp_block.width / 2,
                           16 * tmp_block.width,
                           init_pos_y - tmp_block.height / 2,
                           tmp_block.height,
                           b_type="Base_Floor"))
コード例 #4
0
    def __init__(self):
        Layer.__init__(self)

        self.position = Vector2()  # posicao fixa da layer
        self.anchor = Vector2()

        self.same_line_blks = {
        }  # vai armazenar lista de blocos com mesma altura ( para remover quando completar a linha)

        self.game_controller = game_controller.game_controller
        self.c_manager = self.game_controller.c_manager  # obtem instancia do gerenciador de colisao
コード例 #5
0
    def __init__(self):
        Layer.__init__(self)

        self.position = Vector2()  ## posicao fixa da layer
        self.anchor = Vector2()

        self.score_label = Label(
            "0",
            position=(880, 350),
            font_name="Ravie",
            align="center",
            anchor_x="center")  # texto onde mostra o score atual
        self.add(self.score_label)

        self.pause_label = Label("( ESC )",
                                 position=(820, 190),
                                 font_name="Ravie",
                                 align="center",
                                 anchor_x="center")
        self.add(self.pause_label)

        self.pause_label = Label("Sair",
                                 position=(885, 190),
                                 font_name="Ravie",
                                 align="center",
                                 anchor_x="center",
                                 color=(214, 178, 152, 255))
        self.add(self.pause_label)

        self.pause_label = Label("( P )",
                                 position=(820, 210),
                                 font_name="Ravie",
                                 align="center",
                                 anchor_x="center")
        self.add(self.pause_label)

        self.pause_label = Label(" Pause",
                                 position=(880, 210),
                                 font_name="Ravie",
                                 align="center",
                                 anchor_x="center",
                                 color=(214, 178, 152, 255))
        self.add(self.pause_label)

        self.time_label = Label(
            "00:00",
            position=(880, 250),
            font_name="Ravie",
            align="center",
            anchor_x="center")  # texto onde mostra o score atual
        self.add(self.time_label)

        self.next_piece = Piece(POS_NX_PIECE)
コード例 #6
0
ファイル: actor.py プロジェクト: maccuinn/robot-warz
    def __init__(self, config, position, debug_label=None):
        """
        :param config: values from game_config.py
        :param position: (int, int). the x and y coordinates

        big: boolean. true if actor currently enlarged, false if actor currently small
        dirty: boolean. true if they need to be redrawn, false if not.
        owner: Actor. if actor is a projectile, owner will be set to the actor that shoots the projectile
        size: size of actor on the screen at the near plane.
        scale_x: double. the ratio between the player size and the texture size (for x)
        scale_y: double. the ratio between the player size and the texture size (for y)
        coord: Vector3. game coordinates of actor
        velocity: Vector3. Starts out at 0, 0, 0
        cshape: the collision shape
        """
        texture_name = '/'.join(
            ['assets', 'textures', config['type'], config['texture']])
        self.big = False
        self.dirty = True
        self.owner = None
        self.debug_label = debug_label
        super().__init__(texture_name)
        self.size = config["size"]
        rect = self.get_rect()
        self.scale_x = self.size[0] / rect.width
        self.scale_y = self.size[1] / rect.height
        self.coord = Vector3(*position)
        self.velocity = Vector3()
        self.do(PhysicsAction())
        self.cshape = CircleShape(Vector2(*self.coord.xy), self.size[0] / 2)
コード例 #7
0
ファイル: piece.py プロジェクト: robsonfj/python-tetris
    def __init__(self, position: Vector2, p_type=None):
        Sprite.__init__(self,
                        pyglet.resource.image("block_template.png"),
                        opacity=0)
        self.position = position
        self.anchor = Vector2()

        try:
            self.p_type = p_type == None and sort_new_piece() or p_type
            blocks_offsets = Pieces[self.p_type][
                0]  # De acordo com o tipo retorna lista com ofsets dos blocos para formar a peca
        except Exception as e:
            game_controller.pieces_generated["Square"] += 1
            self.p_type = "Square"  # peca padrao caso valor passado seja incorreto
            blocks_offsets = Pieces[self.p_type][0]

        self.is_stopped = True  # Booleano para checar se a peca ja parou de cair

        # Inicializa os blocos nas posicoes obtidas do dicionario de pecas
        for offset in blocks_offsets:
            blk_pos = getPosition(offset)
            block = Block(blk_pos,
                          block_color=Pieces[self.p_type][1],
                          b_type='Piece')
            self.add(block)
            block.update_cshape_center(
                blk_pos)  # realinha o centro do retangulo de colisao
コード例 #8
0
    def __init__(self,
                 image,
                 position=(0, 0),
                 rotation=0,
                 scale=1,
                 opacity=255,
                 color=(255, 255, 255),
                 anchor=None,
                 **kwargs):
        """
        [summary]

        Args:
            image ([type]): [description]
            position (tuple, optional): [description]. Defaults to (0,0).
            rotation (int, optional): [description]. Defaults to 0.
            scale (int, optional): [description]. Defaults to 1.
            opacity (int, optional): [description]. Defaults to 255.
            color (tuple, optional): [description]. Defaults to (255,255,255).
            anchor ([type], optional): [description]. Defaults to None.
        """
        super().__init__(image,
                         position=position,
                         rotation=rotation,
                         scale=scale,
                         opacity=opacity,
                         color=color,
                         anchor=anchor,
                         **kwargs)
        self.speed = Vector2(0, 0)
コード例 #9
0
    def __init__(self):
        super(Ship, self).__init__(
            image.load(os.path.normpath(r'../assets/Graphics/BookCraft.png')))

        self.drawModules()

        self.position = (250, 250)
        self.heath = 100
        self.bulletList = []
        self.centerPoint = self.get_rect().center
        self.midline = (self.centerPoint, self.get_rect().midtop)
        self.cshape = CircleShape(
            Vector2(self.centerPoint[0], self.centerPoint[1]), self.width / 2)

        # Constants for craft movement
        self.CRAFT_MAX_VELOCITY = 1000
        self.CRAFT_ACCELERATION = 100
        self.CRAFT_MAX_TURNRATE = 1

        # Keep track of the current move speed of the ship. These are accessed
        # directly by the scene controlling the ship
        self.craftMovingUp = False
        self.craftMovingDown = False
        self.craftMovingRight = False
        self.craftMovingLeft = False
        self.craft_x_velocity = 0
        self.craft_y_velocity = 0
コード例 #10
0
 def __init__(self, x, width, y, height, b_type):
     self.x = x
     self.width = width
     self.y = y
     self.height = height
     self.b_type = b_type
     self.cshape = cocos.collision_model.AARectShape(
         Vector2(x + width / 2, y + height / 2), width / 2, height / 2)
コード例 #11
0
ファイル: main_game.py プロジェクト: robsonfj/python-tetris
    def key_action(self, time_elapsed, key_string):# para cada tecla executa a acao especifica
        
        if(key_string ==  'P' or key_string ==  'ESCAPE'):
            self.on_pause()

        if(not self.is_colliding_base and key_string == 'DOWN'):
            self.unschedule(self.currPiece.do_fall)
            self.schedule_interval(self.currPiece.do_fall, 0.03)

        if(not self.is_colliding_left and key_string == 'LEFT'):
            self.currPiece.move(Vector2(-25,0))

        if(not self.is_colliding_right and key_string == 'RIGHT'):
            self.currPiece.move(Vector2(25,0))

        if(key_string == 'SPACE'):
            self.currPiece.rotate()
コード例 #12
0
 def process_piece(self, piece):
     for _ in range(0, len(piece.children)):
         block = piece.children[0][1]
         piece.remove(block)
         block.anchor = Vector2()
         pos = piece.point_to_world(block.position)
         block.position = self.point_to_local(pos)
         self.add_to_wall(block)
     self.remove(piece)
コード例 #13
0
ファイル: actor.py プロジェクト: ZoroOP/python-game-book
    def __init__(self, image, pos, maplayer):
        Sprite.__init__(self, image)
        RectMapCollider.__init__(self)

        x, y = pos
        self.position = Vector2(x, y)
        self.cshape = AARectShape(self.position, self.width/2, self.height/2)

        self.maplayer = maplayer
コード例 #14
0
ファイル: heart.py プロジェクト: franciscolevim/Quetzalcoatl
    def __init__(self, x_pos: float, y_pos: float):
        """La comida de Quetzalcoatl debe aparecer en una posición aleatoria dentro del escenario.

        Args:
            x_pos (float): posición inicial del objeto sobre el escenario en el eje horizontal.
            y_pos (float): posición inicial del objeto sobre el escenario en el eje vertical.
        """
        super().__init__(image=Resources.get_heart_animation())
        self.position = x_pos, y_pos
        self.cshape = cm.CircleShape(Vector2(x_pos, y_pos), self.width / 2)
コード例 #15
0
    def move(self, offset: Vector2):
        """
        [summary]

        Args:
            offset ([type]): [description]
        """
        mov_x = self.position[0] + offset.x * self.speed.x
        mov_y = self.position[1] + offset.y * self.speed.y
        self.position = Vector2(mov_x, mov_y)
コード例 #16
0
ファイル: square.py プロジェクト: franciscolevim/levbogames
 def __init__(self, position=(100, 320)):
     """
     [summary]
     """
     super().__init__(
         LevboSprite.resources.get_image(
             file_name='green_circle_small.png'))
     self.position = position
     self.scale = 0.5
     self.speed = Vector2(530, 530)
コード例 #17
0
 def __init__(self, pos, angle):
     super(Pellet, self).__init__(
         image.load(os.path.normpath(r'../assets/Graphics/Pellet.png')))
     self.initialPosition = pos
     self.position = (pos)
     self.angle = angle
     self.time_alive = 0
     self.cshape = CircleShape(
         Vector2(self.get_rect().center[0],
                 self.get_rect().center[1]), self.width / 2)
コード例 #18
0
 def __init__(self, pos, angle, speed):
     super(Enemy, self).__init__(
         image.load(os.path.normpath(r'../assets/Graphics/IAmABall.png')))
     self.position = pos
     self.health = 100
     self.angle = angle
     self.speed = speed
     self.time_alive = 0
     self.cshape = CircleShape(
         Vector2(self.get_rect().center[0],
                 self.get_rect().center[1]), self.width / 1.5)
コード例 #19
0
ファイル: ranking.py プロジェクト: robsonfj/python-tetris
    def __init__(self, is_game_over=False):
        Layer.__init__(self)
        self.position = Vector2()
        self.anchor = Vector2()

        self.fs = file_saver.File_Saver(
            "rankings.txt")  #nome para o arquivo de ranking
        self.rank_dict = {}

        menu = Menu("")
        menu_items = []

        item = MenuItem('Voltar', self.on_quit)
        menu_items.append(item)
        item.position = (0, -210)
        if (is_game_over):
            menu.title = "GAME OVER"
            black_lyr = ColorLayer(0, 0, 0, 0)
            self.add(black_lyr)
            black_lyr.width = int(director.window.width)
            black_lyr.height = int(director.window.height)
            black_lyr.position = (0, 0)
            black_lyr.opacity = 120
            input_item = EntryMenuItem('Insira o nome:', self.on_text, "", 6)
            menu_items.append(input_item)
            input_item.position = (0, -90)

        else:
            menu.title = "RANKING"

        menu.font_title["font_name"] = "Tetrominoes"
        menu.font_title["color"] = (214, 178, 152, 255)
        menu.font_item["font_name"] = "Ravie"
        menu.font_item["font_size"] = 19
        menu.font_item_selected["font_name"] = "Ravie"
        menu.font_item_selected["font_size"] = 22

        menu.create_menu(menu_items)
        menu.on_quit = self.on_quit

        self.add(menu)
コード例 #20
0
 def __init__(self, x, y, half_width, half_height, c=0):
     '''初始化需要位置(x,y),高度(hw),宽度(hh),图像位置修正值(c)'''
     super().__init__()
     # 产生用于判断的矩形和位置
     self.cshape01 = AARectShape(Vector2(x, y), half_width, half_height)
     self.cshape23 = AARectShape(Vector2(x, y), half_height, half_width)
     self.direction = 3  # 方向为上(0),下(1),左(2),右(3)
     self.cshape = self.cshape01
     self.cshape_x = x
     self.cshape_y = y
     # 设置图片显示的位置
     self.c = c
     pos = coordinate_trans(x, y)
     self.x = pos[0]
     self.y = pos[1] + c
     self.z = 1 / (x + y + 1)
     # 其他属性
     self.can_move = [1, 1, 1, 1]  # 在上下左右四个方向能否移动
     self.hw = half_width
     self.hh = half_height
     self.schedule(self.update_cshape)
コード例 #21
0
    def update(self, delta_t):
        """
        [summary]

        Args:
            delta_t ([type]): [description]
        """
        mov_x = LevboLayer.keys_pressed[key.RIGHT] - LevboLayer.keys_pressed[key.LEFT]
        mov_y = LevboLayer.keys_pressed[key.UP] - LevboLayer.keys_pressed[key.DOWN]                
        if mov_x != 0 or mov_y != 0:
            movement = Vector2(mov_x * delta_t, mov_y * delta_t)
            self.__square.move(movement)
コード例 #22
0
ファイル: hello_world.py プロジェクト: East196/hello-cocos2d
    def __init__(self):
        super(HelloWorld, self).__init__()

        # a cocos.text.Label is a wrapper of pyglet.text.Label
        # with the benefit of being a cocosnode
        label = cocos.text.Label('Hello, World!',
                                 font_name='Times New Roman',
                                 font_size=32,
                                 anchor_x='center',
                                 anchor_y='center')

        label.position = 320, 240
        self.add(label)
        circle = cocos.draw.Circle(Vector2(100.0, 100.0), 10.0)
コード例 #23
0
 def __init__(self):
     super(AtomicShip, self).__init__()
     self.name = "Spaceship"
     self._acceleration = 1000.0 * 0.5
     self._turnspeed = 300.0
     self._velocity = Vector2(0, 0)
     self._spin = 0
     self._thrust = 0
     self._braking = 0
     self._max_speed = 800.0 * 0.5
     # sort of required not to break the physics sim
     # idea if we want to preserve the space feel:
     # set the max speed very high (but at some point where we can still reliably do collisions)
     # when at 50% of the max speed, you start taking damage, and you'll never be able to reach 100%.
     self.alive = True
コード例 #24
0
    def __init__(self, x_pos:float, y_pos:float):
        """La creación de Quetzalcoatl será solo de la cabeza ubicado en el centro del escenario.

        Args:
            x_pos (float): posición inicial del objeto sobre el escenario en el eje horizontal.
            y_pos (float): posición inicial del objeto sobre el escenario en el eje vertical.
        """
        super().__init__(image = Resources.get_head_image())
        self.position = x_pos, y_pos
        self.cshape = cm.AARectShape(Vector2(x_pos, y_pos), self.width * 0.5, self.height * 0.5)

        self.body = []
        for _ in range(3):
            position = self.position[0] + 0, self.position[1] - (self.height * (len(self.body) + 1))
            segment = Segment(position, 0)
            self.body.append(segment)
コード例 #25
0
    def grow(self):
        """[summary]
        """
        mov_x, mov_y = self.position[0], self.position[1]
        self.body.insert(0, Segment(position = (mov_x, mov_y), direction = self.direction))

        if self.direction == key.LEFT:
            mov_x -= self.width
        elif self.direction == key.RIGHT:
            mov_x += self.width
        elif self.direction == key.UP:
            mov_y += self.height
        elif self.direction == key.DOWN:
            mov_y -= self.height

        self.position = mov_x, mov_y
        self.cshape.center= Vector2(mov_x, mov_y)
コード例 #26
0
ファイル: actor.py プロジェクト: jamie-pate/robot-warz
 def __init__(self, config, position, debug_label=None):
     """
     :param config: values from game_config.py
     :param position: (int, int). the x and y coordinates
     """
     texture_name = '/'.join(
         ['assets', 'textures', config['type'], config['texture']])
     self.big = False
     self.dirty = True
     self.owner = None
     self.debug_label = debug_label
     super().__init__(texture_name)
     self.size = config["size"]
     rect = self.get_rect()
     self.scale_x = self.size[0] / rect.width
     self.scale_y = self.size[1] / rect.height
     self.coord = Vector3(*position)
     self.velocity = Vector3()
     self.do(PhysicsAction())
     self.cshape = CircleShape(Vector2(*self.coord.xy), self.size[0] / 2)
コード例 #27
0
    def update(self, delta_t):
        x = 0
        y = 12
        pulsar = Personaje.pulsar_tecla

        if pulsar[key.SPACE] and self.esta_lanzado == False:
            self.image = load('Personaje.png')
            self.esta_lanzado = True
        elif self.esta_lanzado == True:
            self.move_ver(Vector2(x, y))
        else:
            movimiento = pulsar[key.RIGHT] - pulsar[key.LEFT]
            if movimiento != 0:
                delta_x = (self.velocidad * movimiento * delta_t)[0]
                if self.x <= self.parent.ancho_ventana - self.width / 2 - delta_x:
                    if self.x - self.width / 2 + delta_x > abs(delta_x):
                        self.move_ver(self.velocidad * movimiento * delta_t)

        if self.y > self.parent.alto_ventana or self.y < 0:
            self.kill()
            director.replace(Scene(GameOver()))
コード例 #28
0
 def update_pos(self, dt):
     self.cshape.center = Vector2(self.cshape_x, self.cshape_y)
     pos = coordinate_trans(self.cshape_x, self.cshape_y)
     self.x = pos[0]
     self.y = pos[1] + self.c
     a = self.parent.children
     elem = self.z, self
     try:
         a.remove(elem)
     except:
         return
     self.z = 1 / (self.cshape_x + self.cshape_y + 1)
     elem = self.z, self
     lo = 0
     hi = len(a)
     while lo < hi:
         mid = (lo + hi) // 2
         if self.z < a[mid][0]:
             hi = mid
         else:
             lo = mid + 1
     a.insert(lo, elem)
コード例 #29
0
 def __init__(self, space):
     super(ShipLayer, self).__init__()
     self.space = space
     self.ship = AtomicShip()
     self.tracking = None
     create_convex_polygon_object(self.ship, "player.png", (0, 0), 0.0,
                                  ((98, 48), (59, 0), (41, 0), (2, 48),
                                   (44, 72), (55, 72)), 1.0)
     self.ship.body.moment = pymunk.inf
     #        create_disk_object( self.ship, "player.png", (0,0), 0.0, 50.0, 1.0 )
     self.keyboard_state = key.KeyStateHandler()
     self.acceleration = 10
     self.velocity = Vector2(0, 0)
     self.things = []
     self.add(self.ship.sprite)
     self.things.append(self.ship)
     self.space.add(self.ship.body, self.ship.shape)
     for i in range(20):
         debris = Thing()
         debris.name = "Asteroid"
         pos = (random.random() - 0.5) * 2000, (random.random() -
                                                0.5) * 2000
         d = random.random() * 2 * math.pi
         s = random.random() * 20.0
         vel = s * math.cos(d), s * math.sin(d)
         rot = random.random() * 360
         create_convex_polygon_object(debris, "meteorBig.png", pos, rot,
                                      ((134, 87), (129, 39), (83, 0),
                                       (24, 14), (0, 48), (14, 84),
                                       (83, 111)), 5.0)
         #            create_convex_polygon_object( debris, "meteorBig.png", pos, rot, ((50,50),(50,-50),(-50,-50),(-50,50)), 1.0 )
         #            create_disk_object( debris, "meteorBig.png", pos, rot, 50, 1.0 )
         debris.body.velocity = vel
         self.add(debris.sprite)
         self.things.append(debris)
         self.space.add(debris.body, debris.shape)
コード例 #30
0
 def __init__(self, left, right, up, down):
     if (left and not right and not up and not down):
         super(Wall, self).__init__(
             image.load(
                 os.path.normpath(r'../assets/Graphics/wall_part-1-0.png')))
     if (not left and right and not up and not down):
         super(Wall, self).__init__(
             image.load(
                 os.path.normpath(r'../assets/Graphics/wall_part-1-2.png')))
     if (not left and not right and up and not down):
         super(Wall, self).__init__(
             image.load(
                 os.path.normpath(r'../assets/Graphics/wall_part-0-1.png')))
     if (not left and not right and not up and down):
         super(Wall, self).__init__(
             image.load(
                 os.path.normpath(r'../assets/Graphics/wall_part-2-1.png')))
     if (left and not right and up and not down):
         super(Wall, self).__init__(
             image.load(
                 os.path.normpath(r'../assets/Graphics/wall_part-0-0.png')))
     if (left and not right and not up and down):
         super(Wall, self).__init__(
             image.load(
                 os.path.normpath(r'../assets/Graphics/wall_part-2-0.png')))
     if (not left and right and up and not down):
         super(Wall, self).__init__(
             image.load(
                 os.path.normpath(r'../assets/Graphics/wall_part-0-2.png')))
     if (not left and right and not up and down):
         super(Wall, self).__init__(
             image.load(
                 os.path.normpath(r'../assets/Graphics/wall_part-2-2.png')))
     self.cshape = CircleShape(
         Vector2(self.get_rect().center[0],
                 self.get_rect().center[1]), self.width / 2)