示例#1
0
def main():
    main_surface = pygame.display.set_mode((230, 220), 0, 32)
    main_surface.fill((255, 255, 255))
    red_brick = brick.Brick(main_surface, 20, 20, (255, 0, 0))
    blue_brick = brick.Brick(main_surface, 20, 20, (0, 0, 255))
    green_brick = brick.Brick(main_surface, 20, 20, (0, 255, 0))
    orange_brick = brick.Brick(main_surface, 20, 20, (255, 128, 0))
    yellow_brick = brick.Brick(main_surface, 20, 20, (255, 255, 0))
    space = 5
    width = 20
    for x in range(9):
        red_brick.draw((space + ((width + space) * x)), (220 - width - space))
    for x in range(7):
        orange_brick.draw(
            (width + (1.3 * space) + (space + ((width + space) * x))),
            (220 - (2 * space) - (2 * width)))
    for x in range(5):
        yellow_brick.draw(
            (width * 1.5 + (4 * space) + (space + ((width + space) * x))),
            (220 - (3 * space) - (3 * width)))
    for x in range(3):
        green_brick.draw(
            (width * 2.3 + (6 * space) + (space + ((width + space) * x))),
            (220 - (4 * space) - (4 * width)))
    blue_brick.draw(
        (width * 1.1 + (6 * space) + (space + ((width + space) * x))),
        (220 - (5 * space) - (5 * width)))
示例#2
0
    def level_1(self):
        for r in range(3):
            for i in range(13):
                brick_img = brick.Brick((i * 64) + 10, (r * 32 + 20), img_path=constants.BLUE_DIR)
                self.brick_sprites.add(brick_img)

        for i in range(3):
            las_img = brick.Brick((i * 64)+10, (constants.HEIGHT/2)-180, img_path=constants.RED_DIR)
            self.laser_bricks.add(las_img)
示例#3
0
def connect_to_brick(address, by_ip=True, by_bluetooth=True):
    if by_bluetooth:
        try:
            import bluetooth
            import bluesocket

            if bluetooth.is_valid_address(address):
                try:
                    _MODULE_LOGGER.debug(
                        "Bluetooth address found, trying to connect to brick")

                    if _is_brick_already_in_memory(address,
                                                   config.BLUETOOTH_PORT):
                        return _stored_brick(address, config.BLUETOOTH_PORT)

                    socket = bluesocket.BlueSocket()
                    socket.connect(address, config.BLUETOOTH_PORT)
                    _brick = brick.Brick(socket)

                    _store_brick_in_memory(address, config.BLUETOOTH_PORT,
                                           _brick)

                    return _brick

                except bluetooth.BluetoothError:
                    raise error.BrickNotFoundException(
                        "Did you provide the correct bluetooth address?")

        except ImportError:
            pass

    if by_ip:
        try:
            _MODULE_LOGGER.debug("Connecting to brick by IP")

            if _is_brick_already_in_memory(address, config.IP_SOCKET_PORT):
                return _stored_brick(address, config.IP_SOCKET_PORT)

            socket = ipsocket.IpSocket()
            socket.connect(address, config.IP_SOCKET_PORT)
            _brick = brick.Brick(socket)

            _store_brick_in_memory(address, config.IP_SOCKET_PORT, _brick)

            return _brick
        except:
            raise error.BrickNotFoundException(
                "Did you provide the correct ip address?")

    raise error.NoValidCommunicationChosenException(
        "You must choose either ip or bluetooth as a communication option")
示例#4
0
def find_brick_by_name(name, by_ip=True, by_bluetooth=True):
    if by_ip:
        try:
            socket = ipsocket.IpSocket()
            address = socket.get_address_by_hostname(
                hostname=name, port=config.IP_SOCKET_PORT)

            _MODULE_LOGGER.debug("Found brick with IP")

            if _is_brick_already_in_memory(address, config.IP_SOCKET_PORT):
                return _stored_brick(address, config.IP_SOCKET_PORT)

            socket.connect(address, config.IP_SOCKET_PORT)
            _brick = brick.Brick(socket)

            _store_brick_in_memory(address, config.BLUETOOTH_PORT, _brick)

            return _brick
        except error.BrickNotFoundException:
            pass

    if by_bluetooth:
        try:
            import bluetooth
            import bluesocket
            try:
                socket = bluesocket.BlueSocket()
                address = socket.get_address_by_hostname(hostname=name)

                _MODULE_LOGGER.debug("Found brick with bluetooth")

                if _is_brick_already_in_memory(address, config.BLUETOOTH_PORT):
                    return _stored_brick(address, config.BLUETOOTH_PORT)

                socket.connect(address, config.BLUETOOTH_PORT)
                _brick = brick.Brick(socket)

                _store_brick_in_memory(address, config.BLUETOOTH_PORT, _brick)

                return _brick
            except (error.BrickNotFoundException, bluetooth.BluetoothError):
                pass
        except (ImportError, IOError):
            pass

    raise error.BrickNotFoundException(
        "Brick with name '{0}' not found, Searched in ip={1}, bluetooth={2}".
        format(name, by_ip, by_bluetooth))
示例#5
0
    def __init__(self, window_config, ball_config, pad_config,
                 bricks_config_list):
        """Конструктор Контроллера.
		Принимает объекты, которыми будет управлять контроллер: окно, мяч, ракетку, список кирпичей.
		Устанавливает начальное состояние игры:
		количество попыток игрока, нулевое начальное значение счета (разрушенных кирпичей).
		Сохраняет ссылки на контролируемые объекты."""
        self.HP = 3  # Три попытки
        self.score = 0  # Начальный нулевой счёт
        self.window = window.Window(
            window_config[0],
            window_config[1],
            window_config[2],
        )
        self.ball = ball.Ball(self.window, ball_config[0], ball_config[1],
                              ball_config[2], ball_config[5])
        self.ball.set_speed(ball_config[3], ball_config[4])
        self.pad = pad.Pad(self.window, pad_config[0], pad_config[1],
                           pad_config[2])
        self.brick_list = [
            brick.Brick(self.window, brick_config[0], brick_config[1],
                        brick_config[2], brick_config[3], brick_config[4])
            for brick_config in bricks_config_list
        ]
        self.max_score = len(
            self.brick_list)  # Счёт, при котором игрок победит
        # Привязка нажатия и отпускания клавиш к функции управления скоростью ракетки:
        self.window.canvas.bind("<KeyPress>", self.pad_speed_control)
        self.window.canvas.bind("<KeyRelease>", self.pad_speed_control)
示例#6
0
    def setUp(self):
        """Create come bricks and positions for testing"""
        self.b = brick.Brick('42')
        self.pos = [1, 2, 3]
        self.b.position = deepcopy(self.pos)

        self.rot = [3, 4, 5]
        self.b.orientation = deepcopy(self.rot)
示例#7
0
def init_bricks(score, colour, y, points):
    bricks = []
    bs = pygame.sprite.RenderPlain()
    for i in range(30):
        size = rand_size()
        b = brick.Brick(score, colour, (i*30+(i*3)+8, y), points=points)
        bricks.append(b)
        bs.add(b)
    return bricks, bs
示例#8
0
 def generate(self):
     selector = selector_regular.SelectorRegular()
     custom_brick = brick.Brick(def_0, selector)
     custom_brick.structure_personalization()
     custom_brick.dressing_instantiation()
     custom_brick.dressing_personalization()
     concrete = concrete_room.ConcreteRoom()
     custom_brick.finalize(concrete)
     return concrete
示例#9
0
    def build(self):

        """
        Run two for loops to create wall of bricks
        """

        self.bricks = list()
        for x in xrange(0, 15):
            for y in xrange(0, 5):
                self.bricks.append(brick.Brick(x * 41 + 12, y * 11 + 4))
示例#10
0
 def test_kolizja_nie_zachodzi(self):
     ball_x = 500
     ball_y = 500
     brick_x = 300
     brick_y = 300
     brick_test = brick.Brick(self.gra, brick_x, brick_y)
     ball_test = ball.Ball(self.gra, ball_x, ball_y)
     x_move = ball_test.move_x
     y_move = ball_test.move_y
     self.gra.collision(ball_test, brick_test)
     self.assertEqual(ball_test.move_y, y_move)
     self.assertEqual(ball_test.move_x, x_move)
示例#11
0
 def test_kolizja_zachodzi(self):
     ball_x = 210
     ball_y = 130
     brick_x = 205
     brick_y = 120
     brick_test = brick.Brick(self.gra, brick_x, brick_y)
     ball_test = ball.Ball(self.gra, ball_x, ball_y)
     X_move = ball_test.move_x
     Y_move = ball_test.move_y
     self.gra.collision(ball_test, brick_test)
     self.assertEqual(ball_test.move_y, -1 * Y_move)
     self.assertEqual(ball_test.move_x, -1 * X_move)
示例#12
0
    def init_map(self, map_file, new_pos, first_time):
        self.tilemap = tmx.load(map_file, self.screen.get_size())

        if first_time:
            # condition for first attempt
            self.sprites = tmx.SpriteLayer()
            start_cell = self.tilemap.layers['triggers'].find('player')[0]
            self.my_mario = mario.Mario((start_cell.px, start_cell.py),
                                        self.sprites)
        else:
            start_cell = self.tilemap.layers['triggers'].find(new_pos)[0]
        self.my_mario.rect.topleft = (start_cell.px, start_cell.py)

        self.coinboxs = tmx.SpriteLayer()
        for _coinbox in self.tilemap.layers['triggers'].find('coinbox'):
            box_type = getattr(coinbox,
                               _coinbox.properties.get("type", "SECRET"))
            prize = None
            if _coinbox.properties.get("item"):
                prize = getattr(powerup, _coinbox.properties.get("item"))
            count = _coinbox.properties.get("count", 1)
            coinbox.CoinBox(self, (_coinbox.px, _coinbox.py), box_type, prize,
                            count, self.coinboxs)

        self.bricks = tmx.SpriteLayer()
        for _brick in self.tilemap.layers['triggers'].find('brick'):
            brick.Brick(self, (_brick.px, _brick.py), self.bricks)

        self.coins = tmx.SpriteLayer()
        for _coin in self.tilemap.layers['triggers'].find('coin'):
            coin.Coin((_coin.px, _coin.py), self.coins)

        self.enemies = tmx.SpriteLayer()
        for _turtle in self.tilemap.layers['triggers'].find('turtle'):
            turtle.Turtle((_turtle.px, _turtle.py), self.enemies)
        for _flower in self.tilemap.layers['triggers'].find('flower'):
            color = getattr(flower,
                            _flower.properties.get("color", "GREEN_FLOWER"))
            flower.Flower((_flower.px, _flower.py), color, self.enemies)

        self.powerups = tmx.SpriteLayer()
        # layer order: background, midground + sprites, foreground
        self.insert_layer(self.powerups, "powerups", 1)
        self.insert_layer(self.coins, "coins", 2)
        self.insert_layer(self.coinboxs, "coinboxs", 3)
        self.insert_layer(self.bricks, "bricks", 4)
        self.insert_layer(self.enemies, "enemies", 5)
        self.insert_layer(self.sprites, "sprites", 6)
示例#13
0
 def test_generate_0_pad(self):
     """generate one rectangular with no pad"""
     stream_handler = logging.StreamHandler(sys.stdout)
     logger.addHandler(stream_handler)
     selector = selector_regular.SelectorRegular()
     custom_brick = brick.Brick(brick_0_pad, selector)
     custom_brick.structure = sphere.BrickSphere().get_instance(
         custom_brick)
     custom_brick.dressing = basic.DressingBasic().get_instance(
         custom_brick)
     custom_brick.structure_personalization()
     custom_brick.dressing_instantiation()
     custom_brick.dressing_personalization()
     concrete = concrete_room.ConcreteRoom()
     custom_brick.finalize(concrete)
     self.assertEqual(len(concrete.objects), 1)
 def test_generate_0_pad_values(self):
     """generate one rectangular with no pad"""
     stream_handler = logging.StreamHandler(sys.stdout)
     logger.addHandler(stream_handler)
     selector = selector_regular.SelectorRegular()
     custom_brick = brick.Brick(brick_1_pad_values, selector)
     custom_brick.structure = rectangular.BrickRectangular().get_instance(custom_brick)
     custom_brick.dressing = basic.DressingBasic().get_instance(custom_brick)
     custom_brick.structure_personalization()
     logger.info(custom_brick.values.parameters)
     self.assertEqual(custom_brick.values.parameters.structure_private ,
                      {'size': [1.0, 2.0, 3.0]})
     custom_brick.dressing_instantiation()
     custom_brick.dressing_personalization()
     concrete = concrete_room.ConcreteRoom()
     custom_brick.finalize(concrete)
     self.assertEqual(len(concrete.objects) , 1)
示例#15
0
def generate_bricks(start_x: int, start_y: int, col: int, hps: List,
                    colors: List):
    if col != len(colors) or col != len(hps):
        raise ValueError(
            "Number of columns and length of color's/hps list must be the same!"
        )

    line_count = int(
        (gl.WIDTH - (2 * 5 - gl.SPACING)) / (gl.BRICK_WIDTH + gl.SPACING))
    for j in range(col):
        for i in range(line_count):
            br = brick.Brick(gl.BRICK_WIDTH, gl.BRICK_HEIGHT, hps[j], gl.BLACK,
                             colors[j])
            br.rect.x = start_x + i * (gl.BRICK_WIDTH + gl.SPACING)
            br.rect.y = start_y + j * (gl.BRICK_HEIGHT + gl.SPACING)
            gl.SPRITES.add(br)
            gl.BRICKS.add(br)
def main():
    pygame.init()
    mainSurface = pygame.display.set_mode((500, 250), 0, 32)
    pygame.display.set_caption("Brick Pyramid")
    width = (450 / 9)
    height = 20
    space = 5
    RED = (255, 0, 0)
    ORANGE = (255, 165, 0)
    YELLOW = (255, 255, 0)
    GREEN = (0, 255, 0)
    CYAN = (0, 255, 255)
    WHITE = (255, 255, 255)
    x = 0
    y = 230
    number_bricks = 9
    color = [RED, ORANGE, YELLOW, GREEN, CYAN]
    mainSurface.fill(WHITE)
    for b in range(5):
        c = color[b]
        x = (width + space) * b
        for a in range(number_bricks):
            bricks = brick.Brick(mainSurface, width, height, c)
            bricks.draw(x, y)
            x = x + width + space
        y = y - height - space
        number_bricks = number_bricks - 2

    # for c in range(9):
    #     bricks = brick.Brick(mainSurface, width, height, RED)
    #     bricks.rect.x = x
    #     bricks.rect.y = y
    #     mainSurface.blit(bricks.image, bricks.rect)
    #     x = x + width + space
    #     y = y + height + width
    #     x = 0
    # bricks.draw(0, 245)

    while True:
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
示例#17
0
def creat_brick():
    for lineNum in range(len(content)):
        line = content[lineNum].rstrip('\r\n')
        if 'level' in line:
            continue
        for each in line:
            bricks = brick.Brick(bg_size)
            bricks.change_position(brick_position[0], brick_position[1])
            if each == '1':
                bricks.curimage = bricks.image1
            if each == '2':
                bricks.curimage = bricks.image2
            if each == '3':
                bricks.curimage = bricks.image3
            group_brick.add(bricks)
            brick_position[0] += 50
        brick_position[0] = 5
        brick_position[1] += 40
    brick_position[1] = 10
示例#18
0
    def __init__(self, width, height, fps):

        game_mouse.Game.__init__(self, "Pygame Starter", width, height, fps)
        pygame.font.init()
        self.font = pygame.font.SysFont('arial', 30, True)

        self.ball = ball.Ball(10, 10, (255, 255, 255), width, height)

        self.paddle = paddle.Paddle(60, 20, (255, 255, 255), width, height)
        self.brick = [
            brick.Brick(60, 30, 575, 0, (255, 255, 255), width, height),
            brick.Brick(60, 30, 575, 62, (255, 255, 255), width, height),
            brick.Brick(60, 30, 575, 124, (255, 255, 255), width, height),
            brick.Brick(60, 30, 575, 186, (255, 255, 255), width, height),
            brick.Brick(60, 30, 575, 248, (255, 255, 255), width, height),
            brick.Brick(60, 30, 575, 310, (255, 255, 255), width, height),
            brick.Brick(60, 30, 575, 372, (255, 255, 255), width, height),
            brick.Brick(60, 30, 575, 434, (255, 255, 255), width, height)
        ]
        self.score = score.Score()

        return
示例#19
0
    def draw_map(self):
        '''
			Draw the bricks on the playing surface from map-file
		'''
        for row, tiles in enumerate(self.map_data):
            for column, tile in enumerate(tiles):
                if tile == "-":
                    startx = column * (GRID_SIZE_X + 5) + 1
                    starty = row * (GRID_SIZE_Y + 5) + 1
                    self.brick = brick.Brick(self.brick_image, startx, starty)
                    self.bricksprite.add(self.brick)
                    self.allsprites.add(self.brick)
                    #self.brick_count += 1

                if tile == "B":
                    ballstartx = column * GRID_SIZE_X
                    ballstarty = row * GRID_SIZE_Y
                    self.ball = ball.Ball(self.ball_image, ballstartx,
                                          ballstarty)
                    self.ballsprite.add(self.ball)
                    self.allsprites.add(self.ball)
示例#20
0
    def __init__(self):
        self.tps_max = 15.0
        self.temp_color = colors.Colors.GREEN
        self.temp_color_2 = colors.Colors.GREEN
        self.level = 1
        self.score = 0
        self.i = 0
        self.temp = 0
        self.temp_2 = 0
        self.screen = pygame.display.set_mode((1280, 720))
        self.tps_clock = pygame.time.Clock()
        self.tps_delta = 0.0
        try:
            assets.Assets.load()
        except:
            raise Exception("Music initialization went wrong")

        #  hitSound = pygame.mixer.Sound("assets/hit.wav")

        try:
            pygame.display.set_caption("Arcanoid")

            pygame.display.set_icon(assets.Assets.icon)
        except FileNotFoundError:
            raise Exception("File not found")
        self.screen = pygame.display.set_mode((1280, 720))
        self.tps_clock = pygame.time.Clock()
        self.tps_delta = 0.0

        self.player = paddle.Paddle(self)
        self.ball = ball.Ball(self, 600, 350)
        self.button = button.Button(440, 200, 400, 100, False)
        self.button_2 = button.Button(440, 500, 400, 100, False)

        self.list = []

        for i in range(5):
            self.list.append(
                brick.Brick(self, random.randint(100, 400),
                            random.randint(100, 400)))
示例#21
0
文件: scene.py 项目: JamesGaier/mario
 def read(self, path):
     file = open(path, "r")
     level = "".join([s for s in file])
     level = level.split("\n")
     for i in range(len(level)):
         level[i] = list(level[i])
     b_w = 32
     b_h = 32
     isMario = False
     for i in range(len(level)):
         for j in range(len(level[0])):
             image = None
             if level[i][j] == "1":
                 image = self.images.brick
                 b_w = self.images.brick[0].get_width()
                 b_h = self.images.brick[0].get_height()
             elif level[i][j] == "2":
                 my_question = question.Question((j * b_w, i * b_h),
                                                 self.images)
                 self.entities.append(my_question)
                 continue
             elif level[i][j] == "3":
                 my_brick = brick.Brick((j * b_w, i * b_h), self.images)
                 self.entities.append(my_brick)
                 continue
             elif level[i][j] == "4":
                 isMario = True
                 self.mario = m.Mario(j * 32, i * 32, self.images.idle[0],
                                      self.images)
                 self.m_group = pygame.sprite.Group(self.mario)
             elif level[i][j] == "5":
                 block = Entity.Entity(j * 32, i * 32, 32, 32, None)
                 self.entities.append(block)
             if image != None and not isMario:
                 block = Entity.Entity(j * b_w, i * b_h, b_w, b_h, image[0])
                 self.entities.append(block)
             isMario = False
             self.total_width = len(level[0]) * 32
示例#22
0
文件: main.py 项目: crazywh/Hit-Brick
def add_brick(content):
    for line in content:
        for each in line:
            bricks = brick.Brick(size)
            bricks.position(brick_pos[0], brick_pos[1])
            if each == 1:
                bricks.life = 1
                bricks.image = bricks.images[bricks.life - 1]
                bricks.score = 10
                brick_group.add(bricks)
            elif each == 2:
                bricks.life = 2
                bricks.image = bricks.images[bricks.life - 1]
                bricks.score = 30
                brick_group.add(bricks)
            elif each == 3:
                bricks.life = 3
                bricks.image = bricks.images[bricks.life - 1]
                bricks.score = 50
                brick_group.add(bricks)
            brick_pos[0] += 50
        brick_pos[0] = 100
        brick_pos[1] += 25
    brick_pos[1] = 50
示例#23
0
    def test_generate(self):
        """generate one simple door with no parameter"""
        stream_handler = logging.StreamHandler(sys.stdout)
        logger.addHandler(stream_handler)
        selector = selector_regular.SelectorRegular()
        custom_brick = brick.Brick(def_0, selector)
        custom_brick.structure_personalization()
        custom_brick.dressing_instantiation()
        custom_brick.dressing_personalization()
        concrete = concrete_room.ConcreteRoom()
        custom_brick.finalize(concrete)

        # check that it contains an object with expected parent
        objects = concrete.get_objects()
        self.assertEquals(len(objects), 1)
        object = objects[0]
        self.assertEquals(object.parent, None)

        # check there is a portal to an outer world (sounds nice, he ?)
        phys_faces = object.get_physical_faces()
        portal_faces = [ faces for faces in phys_faces if object.PHYS_TYPE_PORTAL == faces["physics"]["type"] ]
        self.assertEquals(len(portal_faces), 1)
        portal_face = portal_faces[0]
        self.assertEquals(portal_face["physics"], {'type': 'portal', 'connect': 'A', 'gate' : 'gate0'})
示例#24
0
def main():
    # Constants that will be used in the program
    application_width = 400
    application_height = 600
    paddle_y_offset = 30
    bricks_per_row = 10
    brick_sep = 4  # The space between each brick
    brick_y_offset = 70
    brick_width = (application_width -
                   (bricks_per_row - 1) * brick_sep) / bricks_per_row
    brick_height = 8
    paddle_width = 60
    paddle_height = 10
    radius_of_ball = 10
    num_turns = 3

    # Sets up the colors
    red = (255, 0, 0)
    black = (0, 0, 0)
    white = (255, 255, 255)
    purple = (195, 47, 191)

    bricks_group = pygame.sprite.Group()
    paddle_group = pygame.sprite.Group()

    # makes the main surface
    main_surface = pygame.display.set_mode(
        (application_width, application_height), 0, 32)
    main_surface.fill((0, 0, 0))
    background = pygame.image.load("revan.jpg")
    main_surface.blit(background, (0, 0))
    x_pos = brick_sep
    y_pos = brick_y_offset

    # makes the paddle
    my_paddle = paddle.Paddle(main_surface, (black), (paddle_width),
                              (paddle_height))
    my_paddle.rect.x = 200
    my_paddle.rect.y = 570
    main_surface.blit(my_paddle.image, my_paddle.rect)
    paddle_group.add(my_paddle)

    # makes the ball
    my_ball = ball.Ball(white, application_width, application_height,
                        radius_of_ball)
    my_ball.rect.x = 900
    my_ball.rect.y = 1000
    main_surface.blit(my_ball.image, my_ball.rect)
    pygame.display.update()

    # Makes the rows of bricks
    for x in range(bricks_per_row):
        my_brick = brick.Brick(brick_width, (brick_height), (red))
        my_brick.rect.x = x_pos
        my_brick.rect.y = y_pos
        bricks_group.add(my_brick)
        main_surface.blit(my_brick.image, (x_pos, y_pos))
        x_pos = x_pos + brick_sep + brick_width

    x_pos = brick_sep
    y_pos = y_pos + brick_height + brick_sep

    for y in range(bricks_per_row):
        my_brick = brick.Brick(brick_width, (brick_height), (red))
        my_brick.rect.x = x_pos
        my_brick.rect.y = y_pos
        bricks_group.add(my_brick)
        main_surface.blit(my_brick.image, (x_pos, y_pos))
        x_pos = x_pos + brick_sep + brick_width

    x_pos = brick_sep
    y_pos = y_pos + brick_height + brick_sep

    for y in range(bricks_per_row):
        my_brick = brick.Brick((brick_width), (brick_height), (purple))
        my_brick.rect.x = x_pos
        my_brick.rect.y = y_pos
        bricks_group.add(my_brick)
        main_surface.blit(my_brick.image, (x_pos, y_pos))
        x_pos = x_pos + brick_sep + brick_width

    x_pos = brick_sep
    y_pos = y_pos + brick_height + brick_sep

    for y in range(bricks_per_row):
        my_brick = brick.Brick((brick_width), (brick_height), (purple))
        my_brick.rect.x = x_pos
        my_brick.rect.y = y_pos
        bricks_group.add(my_brick)
        main_surface.blit(my_brick.image, (x_pos, y_pos))
        x_pos = x_pos + brick_sep + brick_width

    x_pos = brick_sep
    y_pos = y_pos + brick_height + brick_sep

    for y in range(bricks_per_row):
        my_brick = brick.Brick((brick_width), (brick_height), (red))
        my_brick.rect.x = x_pos
        my_brick.rect.y = y_pos
        bricks_group.add(my_brick)
        main_surface.blit(my_brick.image, (x_pos, y_pos))
        x_pos = x_pos + brick_sep + brick_width

    x_pos = brick_sep
    y_pos = y_pos + brick_height + brick_sep

    for y in range(bricks_per_row):
        my_brick = brick.Brick((brick_width), (brick_height), (red))
        my_brick.rect.x = x_pos
        my_brick.rect.y = y_pos
        bricks_group.add(my_brick)
        main_surface.blit(my_brick.image, (x_pos, y_pos))
        x_pos = x_pos + brick_sep + brick_width

    x_pos = brick_sep
    y_pos = y_pos + brick_height + brick_sep

    for y in range(bricks_per_row):
        my_brick = brick.Brick((brick_width), (brick_height), (purple))
        my_brick.rect.x = x_pos
        my_brick.rect.y = y_pos
        bricks_group.add(my_brick)
        main_surface.blit(my_brick.image, (x_pos, y_pos))
        x_pos = x_pos + brick_sep + brick_width

    x_pos = brick_sep
    y_pos = y_pos + brick_height + brick_sep

    for y in range(bricks_per_row):
        my_brick = brick.Brick((brick_width), (brick_height), (purple))
        my_brick.rect.x = x_pos
        my_brick.rect.y = y_pos
        bricks_group.add(my_brick)
        main_surface.blit(my_brick.image, (x_pos, y_pos))
        x_pos = x_pos + brick_sep + brick_width

    x_pos = brick_sep
    y_pos = y_pos + brick_height + brick_sep

    for y in range(bricks_per_row):
        my_brick = brick.Brick((brick_width), (brick_height), (red))
        my_brick.rect.x = x_pos
        my_brick.rect.y = y_pos
        bricks_group.add(my_brick)
        main_surface.blit(my_brick.image, (x_pos, y_pos))
        x_pos = x_pos + brick_sep + brick_width

    x_pos = brick_sep
    y_pos = y_pos + brick_height + brick_sep

    for y in range(bricks_per_row):
        my_brick = brick.Brick((brick_width), (brick_height), (red))
        my_brick.rect.x = x_pos
        my_brick.rect.y = y_pos
        bricks_group.add(my_brick)
        main_surface.blit(my_brick.image, (x_pos, y_pos))
        x_pos = x_pos + brick_sep + brick_width

    # loop that moves paddle and collides the ball and paddle as well as ends the game after 3 turns
    while True:
        main_surface.blit(background, (0, 0))
        for a_brick in bricks_group:
            main_surface.blit(a_brick.image, a_brick.rect)
        my_paddle.move(pygame.mouse.get_pos())
        my_ball.paddle_collide(paddle_group)
        my_ball.brick_collide(bricks_group)
        main_surface.blit(my_paddle.image, my_paddle.rect)
        my_ball.move()
        if my_ball.rect.bottom > application_height:
            num_turns -= 1
            my_ball.rect.x = 200
            my_ball.rect.y = 300
            main_surface.blit(my_ball.image, my_ball.rect)
        if num_turns == 0:
            main_surface.fill(white)
            myFont = pygame.font.SysFont("Times New Roman", 65)
            label = myFont.render("GAME OVER", 1, white)
            main_surface.blit(label, (200, 275))
            pygame.display.update()
            pygame.time.wait(100)
            break
        main_surface.blit(my_ball.image, my_ball.rect)
        pygame.display.update()
        for event in pygame.event.get():
            if event == QUIT:
                pygame.quit()
                sys.exit()
示例#25
0
def main():
    # Constants that will be used in the program
    APPLICATION_WIDTH = 400
    APPLICATION_HEIGHT = 600
    PADDLE_Y_OFFSET = 30
    BRICKS_PER_ROW = 10
    BRICK_SEP = 4  # The space between each brick
    BRICK_Y_OFFSET = 70
    BRICK_WIDTH =  (APPLICATION_WIDTH - (BRICKS_PER_ROW -1) * BRICK_SEP) / BRICKS_PER_ROW
    BRICK_HEIGHT = 8
    PADDLE_WIDTH = 60
    PADDLE_HEIGHT = 10
    RADIUS_OF_BALL = 10
    NUM_TURNS = 3

    # Sets up the colors
    RED = (255, 0, 0)
    ORANGE = (255, 165, 0)
    YELLOW = (255, 255, 0)
    GREEN =(0, 255, 0)
    CYAN = (0, 255, 255)
    BLACK = (0, 0, 0)
    WHITE = (255, 255, 255)

    colors = [RED, ORANGE, YELLOW, GREEN, CYAN]

    # creates a sprite fo the sprite groups so the bricks and paddle can collide with the ball
    bricks_group = pygame.sprite.Group()
    paddle_group = pygame.sprite.Group()

    # creates a main surface with a picture as the background
    main_surface = pygame.display.set_mode((APPLICATION_WIDTH, APPLICATION_HEIGHT), 0, 32)
    bg = pygame.image.load("construction.jpeg")
    main_surface.blit(bg, (0, 0))

    # the following code displays the bricks on the screen
    x_pos = BRICK_SEP
    y_pos = BRICK_Y_OFFSET
    for hue in colors:
        for y in range(2):
            for x in range(BRICKS_PER_ROW):
                my_brick = brick.Brick(BRICK_WIDTH, BRICK_HEIGHT, hue)
                my_brick.rect.x = x_pos
                my_brick.rect.y = y_pos
                bricks_group.add(my_brick)
                main_surface.blit(my_brick.image, my_brick.rect)
                x_pos += BRICK_WIDTH + BRICK_SEP
            y_pos += BRICK_HEIGHT + BRICK_SEP
            x_pos = BRICK_SEP
    # displays the paddle
    my_paddle = paddle.Paddle(main_surface, BLACK, PADDLE_WIDTH, PADDLE_HEIGHT)
    paddle_group.add(my_paddle)
    my_paddle.rect.y = APPLICATION_HEIGHT - PADDLE_Y_OFFSET
    main_surface.blit(my_paddle.image, my_paddle.rect)
    # displays the ball
    my_ball = ball.Ball(BLACK, APPLICATION_WIDTH, APPLICATION_HEIGHT, RADIUS_OF_BALL)
    my_ball.rect.x = APPLICATION_WIDTH/2
    my_ball.rect.y = APPLICATION_HEIGHT/2
    main_surface.blit(my_ball.image, my_ball.rect)

    tries = 0

    while True:
        main_surface.fill(WHITE)
        main_surface.blit(bg, (0, 0))
        # makes the paddle move with the mouse
        for a_brick in bricks_group:
            main_surface.blit(a_brick.image, a_brick.rect)
        my_paddle.move(pygame.mouse.get_pos())
        main_surface.blit(my_paddle.image, my_paddle.rect)
        my_ball.move()
        my_ball.collide(paddle_group)
        my_ball.collide_brick(bricks_group)
        main_surface.blit(my_ball.image, my_ball.rect)
        end_sound = pygame.mixer.Sound('maybe-next-time.wav')
        # resets the ball if it goes off the screen
        if my_ball.rect.bottom >= APPLICATION_HEIGHT:
            end_sound.play()
            my_ball.rect.y = APPLICATION_HEIGHT / 2
            tries += 1
        # displays "game over" if the player looses. The >= makes the game over displays even when the ball
        # keeps hitting the bottom of the screen
        if tries >= 3:
            game_over(main_surface)
        # displays "winner!" when the player wins by breaking all the bricks
        if len(bricks_group) == 0:
            win_game(main_surface)
        pygame.display.update()
        for event in pygame.event.get():
            if event == QUIT:
                pygame.quit()
                sys.exit()
示例#26
0
 def _decode_room(dct):
     if 'b_id' in dct:
         return brick.Brick(dct, self.selector)
     return dct
示例#27
0
def main():

    # Constants that will be used in the program
    APPLICATION_WIDTH = 500
    APPLICATION_HEIGHT = 600
    PADDLE_Y_OFFSET = 30
    BRICKS_PER_ROW = 10
    BRICK_SEP = 4
    BRICK_Y_OFFSET = 70
    BRICK_WIDTH = (APPLICATION_WIDTH -
                   (BRICKS_PER_ROW - 1) * BRICK_SEP) / BRICKS_PER_ROW
    BRICK_HEIGHT = 10
    PADDLE_WIDTH = 60
    PADDLE_HEIGHT = 10
    RADIUS_OF_BALL = 10
    NUM_TURNS = 3
    BLACK = (0, 0, 0)

    # Step 1: Use loops to draw the rows of bricks. The top row of bricks should be 70 pixels away from the top of
    # the screen (BRICK_Y_OFFSET)
    pygame.init()
    # Create a window for the game
    mainSurface = pygame.display.set_mode(
        (APPLICATION_WIDTH, APPLICATION_HEIGHT), 32, 0)
    pygame.display.set_caption("Break Out")
    bricksGroup = pygame.sprite.Group()
    paddleGroup = pygame.sprite.Group()

    # Create a pile of bricks
    x = 0
    y = BRICK_Y_OFFSET
    bricks = 10
    for rows in range(10):
        for number in range(bricks):
            pile = brick.Brick(BRICK_WIDTH, BRICK_HEIGHT, color)
            pile.rect.x = x
            pile.rect.y = y
            bricksGroup.add(pile)
            # Add the row to the window(surface)
            mainSurface.blit(pile.image, pile.rect)
            x = x + BRICK_WIDTH + BRICK_SEP
        # Start over at x = 0, but move up by the brick height + brick separation to draw two new rows
        x = 0
        y = y + BRICK_HEIGHT + BRICK_SEP
    pygame.display.update()

    # Step 2: Create a paddle
    board = paddle.Paddle(mainSurface, BLACK, PADDLE_WIDTH, PADDLE_HEIGHT)
    # The paddle starts at the middle of the screen and has a 30 pixel distance away from the bottom.
    board.rect.x = APPLICATION_WIDTH / 2
    board.rect.y = APPLICATION_HEIGHT - PADDLE_Y_OFFSET
    # Add the paddle to the main surface
    mainSurface.blit(board.image, board.rect)
    paddleGroup.add(board)
    pygame.display.update()

    # Step 3: Create a ball
    circle = ball.Ball(BLACK, APPLICATION_WIDTH, APPLICATION_HEIGHT,
                       RADIUS_OF_BALL)
    # The ball starts at the middle of the window
    circle.rect.x = APPLICATION_WIDTH / 2
    circle.rect.y = APPLICATION_HEIGHT / 2
    pygame.display.update()

    background = pygame.image.load("cat.png")
    background_rect = background.get_rect()
    background_rect.x = 0
    background_rect.y = 0
    while True:
        for event in pygame.event.get():
            if event == QUIT:
                pygame.quit()
                sys.exit()
        # Fill the window with the image every time the ball or the paddle moves
        mainSurface.blit(background, background_rect)
        # Add all the bricks on the window every time the ball or the paddle moves
        for cubes in bricksGroup:
            mainSurface.blit(cubes.image, cubes.rect)
        board.move()
        mainSurface.blit(board.image, board.rect)
        circle.move()
        circle.collision(paddleGroup)
        circle.collisionBrick(bricksGroup)
        # There are three turns in total to play breakout.
        # If the turn becomes 0(the ball hits the ball for three times), the player loses and the game stops and quits.
        if circle.rect.bottom >= APPLICATION_HEIGHT:
            # Every time the ball hits the bottom, the number of turns(3) will minus 1.
            NUM_TURNS = NUM_TURNS - 1
            # Reset the position of the ball.
            circle.rect.x = APPLICATION_WIDTH / 2
            circle.rect.y = APPLICATION_HEIGHT / 2
            # If the ball hits the bottom, the lose sound will be played.
            lose_sound = pygame.mixer.Sound("dk_dawae.wav")
            lose_sound.play()
            # The game waits for a second.
            pygame.time.wait(1000)
            # The ball will move with its original speed from the reset position.
            circle.speedx = 5
            circle.speedy = 6
            # If the user loses, the game waits for 1.5 seconds and quits afterwards.
            if NUM_TURNS == 0:
                pygame.time.wait(1500)
                pygame.quit()
                sys.exit()
        # If all bricks are eliminated(have collided with the ball), the game waits for 3 seconds.
        # It will play the winning sound, and quit.
        if len(bricksGroup) == 0:
            win_sound = pygame.mixer.Sound("clicking.wav")
            win_sound.play()
            pygame.time.wait(3000)
            pygame.quit()
            sys.exit()
        mainSurface.blit(circle.image, circle.rect)
        pygame.display.update()
示例#28
0
def main():

    # Constants that will be used in the program
    APPLICATION_WIDTH = 400
    APPLICATION_HEIGHT = 600
    PADDLE_Y_OFFSET = 30
    BRICKS_PER_ROW = 10
    BRICK_SEP = 4  # The space between each brick
    BRICK_Y_OFFSET = 70
    BRICK_WIDTH = (APPLICATION_WIDTH -
                   (BRICKS_PER_ROW - 1) * BRICK_SEP) / BRICKS_PER_ROW
    BRICK_HEIGHT = 8
    PADDLE_WIDTH = 60
    PADDLE_HEIGHT = 10
    RADIUS_OF_BALL = 10
    NUM_TURNS = 3

    # Sets up the colors
    RED = (255, 0, 0)
    ORANGE = (255, 165, 0)
    YELLOW = (255, 255, 0)
    GREEN = (0, 255, 0)
    CYAN = (0, 255, 255)
    BLACK = (0, 0, 0)
    WHITE = (255, 255, 255)
    colors = [
        RED, RED, ORANGE, ORANGE, YELLOW, YELLOW, GREEN, GREEN, CYAN, CYAN
    ]

    # Step 1: Use loops to draw the rows of bricks. The top row of bricks should be 70 pixels away from the top of
    # the screen (BRICK_Y_OFFSET)

    pygame.init()
    mainSurface = pygame.display.set_mode(
        (APPLICATION_WIDTH, APPLICATION_HEIGHT), 0, 32)
    mainSurface.fill((BLACK))
    pygame.display.set_caption(" Ultimate Breakout Z")

    background_image = pygame.image.load("Dragonball.png")
    # Changing the background image to a custom one.
    background_rect = background_image.get_rect()
    background_rect.x = 0
    background_rect.y = 0
    mainSurface.blit(background_image, background_rect)

    x = 0
    y = BRICK_Y_OFFSET

    brick_group = pygame.sprite.Group()
    paddle_group = pygame.sprite.Group()

    # Places the Paddle at the center of the application width and at the 30 offset of the bottom
    paddle_ = paddle.Paddle(mainSurface, WHITE, PADDLE_WIDTH, PADDLE_HEIGHT)
    paddle_.rect.x = APPLICATION_WIDTH / 2
    paddle_.rect.y = APPLICATION_HEIGHT - PADDLE_Y_OFFSET
    mainSurface.blit(paddle_.image, paddle_.rect)
    paddle_group.add(paddle_)

    # This places the ball at the center of the application
    bally = ball.Ball(RED, APPLICATION_WIDTH, APPLICATION_HEIGHT,
                      RADIUS_OF_BALL)
    bally.rect.x = APPLICATION_WIDTH / 2
    bally.rect.y = APPLICATION_HEIGHT / 2
    mainSurface.blit(bally.image, bally.rect)

    for m in range(BRICKS_PER_ROW):
        color = colors[m]
        x = 0
        for b in range(BRICKS_PER_ROW):

            bricks = brick.Brick(BRICK_WIDTH, BRICK_HEIGHT, color)

            brick_group.add(bricks)
            bricks.rect.x = x
            bricks.rect.y = y
            mainSurface.blit(bricks.image, bricks.rect)
            x = x + BRICK_WIDTH + BRICK_SEP
            # creates a row of bricks
        pygame.display.update()
        y = y + BRICK_HEIGHT + BRICK_SEP
    #     Creates the other row of bricks under the following one

    while True:
        for event in pygame.event.get():
            if event == QUIT:
                pygame.quit()
                sys.exit()
        mainSurface.blit(background_image, background_rect)
        mainSurface.blit(bally.image, bally.rect)
        for x in brick_group:
            mainSurface.blit(x.image, x.rect)
        paddle_.move()
        mainSurface.blit(paddle_.image, paddle_.rect)
        bally.move()
        bally.collide_paddle(paddle_group)
        # When the ball collides with the paddle
        bally.collide(brick_group)
        # When the ball collides with the bricks
        if bally.rect.bottom >= APPLICATION_HEIGHT:
            bally.rect.x = APPLICATION_WIDTH / 2
            bally.rect.y = APPLICATION_HEIGHT / 2
            NUM_TURNS = NUM_TURNS - 1
            pygame.time.delay(6000)
        if NUM_TURNS == 0:
            pygame.quit()
            sys.exit()
        # Exits the game when the player is out of turns
        mainSurface.blit(bally.image, bally.rect)

        pygame.display.update()
示例#29
0
            # Узлы на которых располагется brick'и volume'а
            nodes_of_volume = list((bricks_of_volume[key_brick]["Info"]["node"] for key_brick in bricks_of_volume))

            # Доступные узлы
            available_node = list((node for node in list(heketi_object["nodeentries"].keys())
                                   if node not in nodes_of_volume))
            # Если в доступных узлах есть toswrkr2 - удалить
            try:
                available_node.remove("6622e5d6546408f4c66e2844fad2c4f1")
            except ValueError:
                pass

            size_new_brick = bricks_of_volume[next(iter(bricks_of_volume))]["Info"]["size"]
            node_for_new_brick = random.choice(available_node)
            device_for_new_brick = random.choice(heketi_object["nodeentries"][node_for_new_brick]["Devices"])
            new_brick = brick.Brick(node=node_for_new_brick, volume=key_volume, size=size_new_brick,
                                    device=device_for_new_brick)
            heketi_object["brickentries"].update(new_brick.brick)
            heketi_object["volumeentries"][key_volume]["Bricks"].append(new_brick.id_brick)
            heketi_object["deviceentries"][device_for_new_brick]["Bricks"].append(new_brick.id_brick)

            # Отладка для отслеживания распределния по нодам
            for x in new_brick.brick:
                print(new_brick.brick[x]["Info"]["node"])

            CScript.write("ssh " + heketi_object["nodeentries"][node_for_new_brick]["Info"]["hostnames"]["manage"][0] +
                  " lvcreate --thinpool vg_" + device_for_new_brick + "/tp_" + next(iter(new_brick.brick)) +
                  " --size " + str(size_new_brick) + "k --chunksize 256k --poolmetadatasize " +
                  str(brick.Brick.PoolMetadataSize[size_new_brick]) + "k --zero n\n")

            CScript.write("ssh " + heketi_object["nodeentries"][node_for_new_brick]["Info"]["hostnames"]["manage"][0] +
            " lvcreate --thin --name brick_" + next(iter(new_brick.brick)) + " --virtualsize " + str(size_new_brick) +
示例#30
0
    def generator_poziomow(self, level, bricks_number, player_moving_speed,
                           ball_speed_x, ball_speed_y):
        try:
            points = self.score
            list_of_bricks = []
            for i in range(bricks_number):
                list_of_bricks.append(
                    brick.Brick(self, random.randint(70, 884),
                                random.randint(70, 500)))
            for brick_object in list_of_bricks:
                brick_object.bool = True

            self.temp_color
            self.temp_color_2
            self.i = 0
            self.button = button.Button(310, 300, 400, 100, False)
            self.button_2 = button.Button(310, 300, 400, 100, False)
            self.ball.pos.x = 500
            self.ball.pos.y = 550
            self.player.move_x = player_moving_speed

            while True:

                # Handle events
                for event in pygame.event.get():
                    mouse_pos = pygame.mouse.get_pos()
                    if event.type == pygame.QUIT:
                        sys.exit(0)
                    elif event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
                        sys.exit(0)
                    elif event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
                        self.score += 1
                    elif event.type == pygame.MOUSEMOTION:
                        if self.is_over(self.button, mouse_pos):
                            self.temp_color = colors.Colors.GREEN
                        elif self.is_over(self.button, mouse_pos):
                            self.temp_color_2 = colors.Colors.PINK
                        else:
                            self.temp_color = colors.Colors.GREEN
                    elif event.type == pygame.MOUSEBUTTONDOWN:
                        if self.button_2.bool and self.is_over(
                                self.button_2, mouse_pos):
                            self.button_2.bool = False
                            return True

                        if self.button.bool and self.is_over(
                                self.button, mouse_pos):
                            for i in list_of_bricks:
                                i.bool = True
                            self.button.bool = False
                            self.ball.move_y = 0
                            self.ball.move_x = 0
                            self.ball.pos.x = 500
                            self.ball.pos.y = 550
                            self.player.pos = math.Vector2(460, 650)
                            self.score = 0
                            self.i = 0
                            self.temp = 0

                # ticking
                self.tps_delta += self.tps_clock.tick() / 120.0
                while self.tps_delta > 1 / self.tps_max:
                    self.tick()
                    self.tps_delta -= 1 / self.tps_max

                # drawing
                self.screen.fill((130, 130, 130))
                self.screen.blit(assets.Assets.interface, (0, 0))
                for i in list_of_bricks:
                    if i.bool:
                        self.collision(self.ball, i)

                text = assets.Assets.font.render(str(self.score), 1,
                                                 (130, 105, 20))
                text2 = assets.Assets.font_2.render(str(level), 1,
                                                    (130, 105, 20))
                self.screen.blit(text, (1115, 420))
                self.screen.blit(text2, (1115, 260))
                self.screen.blit(pygame.image.load("assets/ball.png"),
                                 (int(self.ball.pos.x), int(self.ball.pos.y)))
                old_y = self.ball.pos.y

                self.draw()
                if old_y > 700:
                    self.button.bool = True
                    self.you_lost_statement()

                if self.score == points + bricks_number:
                    self.button_2.bool = True
                    self.next_level_button(level)

                self.wait(ball_speed_x, ball_speed_y)
                pygame.display.flip()
        except TypeError:
            raise Exception("Type Error")
        except Exception:
            raise Exception("Error - level creator")