Exemplo n.º 1
0
 def __create_random_walls(self):
     random_walls_return = {}
     reserved_spaces = [[1, 1], [1, 2], [2, 1], [1, 6], [1, 7], [2, 7],
                        [12, 1], [13, 1], [13, 2], [13, 6], [13, 7],
                        [12, 7], [7, 4]]
     x = 1
     y = 1
     n = 0
     n_walls = 25
     model_wall = self.__model_wall[2]
     while True:
         x = randint(1, 13)
         y = randint(1, 7)
         if x % 2 == 1 or y % 2 == 1:  # fixes walls
             if [x, y] not in reserved_spaces:
                 n += 1
                 reserved_spaces.append([x, y])
                 wall = Wall(
                     0, [x * Server.wall_factor, y * Server.wall_factor],
                     model_wall.get_id(), [55, 55], 255,
                     self.__create_random_gift())
                 random_walls_return[wall.get_id()] = wall
         if n == n_walls:
             break
     return random_walls_return
Exemplo n.º 2
0
    def __init__(self, game_name):
        self.game_name = game_name
        # задаємо розміри екрану
        self.screen_width = 720
        self.screen_height = 460
        self.play_surface = pygame.display.set_mode(
            (self.screen_width, self.screen_height))

        # необхідні кольори
        self.red = pygame.Color(255, 0, 0)
        self.green = pygame.Color(0, 255, 0)
        self.black = pygame.Color(0, 0, 0)
        self.white = pygame.Color(255, 255, 255)
        self.brown = pygame.Color(165, 42, 42)

        # задає кількість кадрів в секуну
        self.fps_controller = pygame.time.Clock()

        # змінна для відображення результату
        # (скільки їжі зїли)
        self.score = 0
        pygame.display.set_caption(self.game_name)
        self.snake = Snake(self.green)
        self.food = Food(self.brown, self.screen_width, self.screen_height)
        self.wall = Wall(self.white)
        self.difficulty = 10
        self.ratio = 10
        self.playername = "Gamer"
        self.is_wall = False
        self.wall_start_time = None
        pygame.init()
Exemplo n.º 3
0
    def create_chamber(self, chamber):
        # make top and bottom walls
        for i in xrange(0, chamber.length):
            # syntactic sugar
            fst = chamber.start[0] + i
            snd = chamber.start[1]
            wall = Wall(fst * TILE_SIZE, snd * TILE_SIZE)
            self.walls[fst][snd] = 1
            self.wall_list.add(wall)

            fst = chamber.start[0] + i
            snd = chamber.start[1] + chamber.height - 1
            wall = Wall(fst * TILE_SIZE, snd * TILE_SIZE)
            self.walls[fst][snd] = 1
            self.wall_list.add(wall)
        # make side walls
        for i in xrange(0, chamber.height):
            fst = chamber.start[0]
            snd = chamber.start[1] + i
            wall = Wall(fst * TILE_SIZE, snd * TILE_SIZE)
            self.walls[fst][snd] = 1
            self.wall_list.add(wall)

            fst = chamber.start[0] + chamber.length - 1
            snd = chamber.start[1] + i
            wall = Wall(fst * TILE_SIZE, snd * TILE_SIZE)
            self.walls[fst][snd] = 1
            self.wall_list.add(wall)

        # fill in floor
        for x in xrange(1, chamber.length - 1):
            for y in range(1, chamber.height - 1):
                self.floor[chamber.start[0] + x][chamber.start[1] + y] = 1
Exemplo n.º 4
0
    def __init__(self, screen_rect):

        self.wall_group = list()

        rect = pygame.rect.Rect((0, 0), (10, screen_rect.h))
        rect.topright = screen_rect.topright
        self.wall_group.append(Wall(rect))

        rect = pygame.rect.Rect((0, 0), (screen_rect.w, 10))
        rect.bottomleft = screen_rect.bottomleft
        self.wall_group.append(Wall(rect))

        rect = pygame.rect.Rect((0, 0), (10, screen_rect.h))
        rect.topleft = screen_rect.topleft
        self.wall_group.append(Wall(rect))

        rect = pygame.rect.Rect((0, 0), (screen_rect.w, 10))
        rect.topleft = screen_rect.topleft
        self.wall_group.append(Wall(rect))

        self.ball_group = list()
        for i in range(50):
            b = Ball((random.randint(0, screen_rect.w), random.randint(0, screen_rect.h)))
            if not any(Physics.is_circle_collision(b, ball) for ball in self.ball_group):
                self.ball_group.append(b)

        self.physics = Physics()
        self.physics.solids.extend(self.wall_group)
        self.physics.mobiles.extend(self.ball_group)
Exemplo n.º 5
0
 def __init__(self):
     self.__arena = Arena()
     self.__wall = Wall(self.__arena)
     self.__snake = Snake(self.__arena)
     self.__movement = Movement(self.__arena, self.__snake)
     self.cls()
     self.gameloop()
Exemplo n.º 6
0
 def __init__(self, game):
     """init and position the wall"""
     # we use only white dragons for building the wall. We could actually
     # use any tile because the face is never shown anyway.
     self.initWindMarkers()
     game.wall = self
     Wall.__init__(self, game)
     self.__square = Board(1, 1, Tileset.current())
     self.__square.setZValue(ZValues.markerZ)
     sideLength = len(self.tiles) // 8
     self.__sides = [
         UIWallSide(Tileset.current(), boardRotation, sideLength)
         for boardRotation in self.sideAngles
     ]
     for idx, side in enumerate(self.__sides):
         side.setParentItem(self.__square)
         side.lightSource = self.lightSource
         side.windTile = Wind.all4[idx].marker
         side.windTile.hide()
         side.message = YellowText(side)
         side.message.setZValue(ZValues.popupZ)
         side.message.setVisible(False)
         side.message.setPos(side.center())
     self.__sides[self.Lower].setPos(yWidth=sideLength)
     self.__sides[self.Left].setPos(xHeight=1)
     self.__sides[self.Upper].setPos(xHeight=1,
                                     xWidth=sideLength,
                                     yHeight=1)
     self.__sides[self.Right].setPos(xWidth=sideLength,
                                     yWidth=sideLength,
                                     yHeight=1)
     Internal.scene.addItem(self.__square)
     Internal.Preferences.addWatch('showShadows', self.showShadowsChanged)
Exemplo n.º 7
0
class GameState(object):
    def __init__(self, screen):
        self.screen = screen
        self.score = 0
        self.is_gameover = True
        self.is_paused = False
        self.time_interval = GameConfig.TIMER_INTERVAL
        self.piece = None
        self.next_piece = None
        self.wall = Wall(self.screen)

    def new_piece(self):
        self.piece = self.next_piece
        shape = GameConfig.SHAPES[random.randint(0,
                                                 len(GameConfig.SHAPES) - 1)]
        self.next_piece = Piece(self.screen, shape, self.wall)

    def add_score(self, elimiate_lines):
        self.score += elimiate_lines * GameConfig.SCORE_PER_LINE

    def start(self):
        self.score = 0
        self.is_gameover = False
        self.is_paused = False
        self.new_piece()
        self.new_piece()
        self.wall.clear()
        self.set_timer()

    def restart(self):
        self.start()

    def gameover(self):
        self.is_gameover = True
        self.clear_timer()

    def pause(self):
        self.is_paused = True
        self.clear_timer()

    def resume(self):
        self.is_paused = False
        self.set_timer()

    def set_timer(self):
        pygame.time.set_timer(pygame.USEREVENT, self.time_interval)

    def clear_timer(self):
        pygame.time.set_timer(pygame.USEREVENT, 0)

    def judge(self):
        elimiate_lines = self.wall.elimiate_lines()
        self.add_score(elimiate_lines)

        for i in range(GameConfig.COLUMN_NUM):
            if self.wall.is_wall(0, i):
                self.gameover()
                return

        self.new_piece()
Exemplo n.º 8
0
    def open_door(self, player, current_room):
        if player.rect.x - door[0] > -100:  #Door opens if player comes close
            self.wall_list = None
            self.wall_list = py.sprite.Group()
            block = copy.deepcopy(walls)  #makes deep copy
            block.append(secret)  #adds secret door
            #Add list of walls to wall_list from superclass Room
            for item in block:
                wall = Wall(item[0], item[1], item[2], item[3], item[4])
                self.wall_list.add(wall)

            #Declare door open
            self.door_open = True

        if len(current_room.enemies
               ) <= 1:  #Secret door opens after two orc killed
            self.wall_list = None
            self.wall_list = py.sprite.Group()
            block = copy.deepcopy(walls)  #makes deep copy
            #Add list of walls to wall_list from superclass Room
            for item in block:
                wall = Wall(item[0], item[1], item[2], item[3], item[4])
                self.wall_list.add(wall)

            #Declare door open
            self.secret_open = True
Exemplo n.º 9
0
def get_center_wall(ai_settings, screen):
    """Returns a wall with it's centerx and centery equal to that of the screen's."""
    screen_rect = screen.get_rect()
    center_wall = Wall(ai_settings, screen)
    center_wall.centerx = screen_rect.centerx
    center_wall.centery = screen_rect.centery
    return center_wall
Exemplo n.º 10
0
 def draw_room_from_point(self, grid, x, y, size):
     len = size
     for i in range(len):
         grid.place_agent(Wall(i, self), (x + i, y))
         grid.place_agent(Wall(i, self), (x + i, y - len))
         grid.place_agent(Wall(i, self), (x, y - i))
         grid.place_agent(Wall(i, self), (x + len, y - i))
Exemplo n.º 11
0
def makeMaze(mazeColumn, mazeRow):
    grid = [[0] * mazeColumn for _ in range(mazeRow)]
    for r in range(0, mazeRow):
        for c in range(0, mazeColumn):
            top, left = Wall(), Wall()
            if r != 0:
                top = grid[r - 1][c].getWalls()[2]
            if c != 0:
                left = grid[r][c - 1].getWalls()[1]
            grid[r][c] = Cell([top, Wall(), Wall(), left])
            for wall in grid[r][c].getWalls():
                wall.addOwner(grid[r][c])
    maze = []
    wallsToDo = []
    random.random()
    randomCell = grid[random.randint(0, mazeRow - 1)][random.randint(0, mazeColumn - 1)]
    maze.append(randomCell)
    for i in range(0, 4):
        wallsToDo.append(randomCell.getWalls()[i])

    while len(maze) < mazeColumn * mazeRow:
        randomWall = random.choice(wallsToDo)
        if len(randomWall.owner) > 1 and (maze.count(randomWall.owner[0]) == 0 or maze.count(randomWall.owner[1]) == 0):
            randomWall.breakWall()
            newOwner = randomWall.owner[0 if maze.count(randomWall.owner[0]) == 0 else 1]
            maze.append(newOwner)
            for i in range(0, 4):
                if newOwner.getWalls()[i].exists:
                    wallsToDo.append(newOwner.getWalls()[i])
        wallsToDo.remove(randomWall)
        if len(wallsToDo) == 0:
            print("GOT STUCK")
            return makeMaze(mazeColumn, mazeRow)
    return grid
Exemplo n.º 12
0
    def __init__(self):
        random.seed(time.time())
        random.seed(123)
        pygame.init()
        pygame.font.init()
        self.font = pygame.font.SysFont('Comic Sans MS', 200)
        self.window = pygame.display.set_mode(
            (self.WINDOW_LENGTH, self.WINDOW_HEIGHT))
        self.clock = pygame.time.Clock()
        self.running = True

        self.piecesName = []
        self.objects = []

        self.objects.append(
            Player(self.PLAYER1_NAME, self.PLAYER1_START_POS,
                   self.PLAYER1_KEYS, self.PLAYER1_COLOR, self))
        self.objects.append(
            Player(self.PLAYER2_NAME, self.PLAYER2_START_POS,
                   self.PLAYER2_KEYS, self.PLAYER2_COLOR, self))

        self.piecesName = []
        self.generatePieces()

        self.objects.append(Wall("LEFT", self.piecesName, self))
        self.objects.append(Wall("RIGHT", self.piecesName, self))
Exemplo n.º 13
0
    def load(self):
        self._map = {}
        self._tiles = {}
        self._attributes = {}

        file = Files.openFile(self._file)
        self._attributes = self.loadAttributes('attribs', file)
        self._enemies = self.loadAttributes('enemies', file)
        self.w = self.getAttr("w") * const.res
        self.h = self.getAttr("h") * const.res
        self._display = Display(Surface((self.w, self.h)), klass=self, transparent=True)

        file = re.search("map: {(.*?)}", file, flags=re.DOTALL).group(1)
        for tile in re.finditer(r"\((.*?):(.*?)\)", file):
            rect, right = tile.group(1), tile.group(2)
            rect = re.match(r"(\d+),(\d+),(\d+),(\d+),(\d+),(\d+)", rect)
            if not rect:
                raise Exception("Unrecognized pattern: {}".format(rect))

            details = re.match(r"(\d+),(\d+)$", right)
            if not details:
                raise Exception("Unrecognized pattern: {}".format(right))

            i, e = int(rect.group(1)), int(rect.group(2))
            x, y, w, h = rect.group(3), rect.group(4), rect.group(5), rect.group(6)
            x, y, w, h = int(x), int(y), int(w), int(h)
            typ, tile = int(details.group(1)), int(details.group(2))

            attrib = {}
            wall = Wall((x, y, w, h), typ, tile, attrib)
            wall.subscribe("map", self._updateMap)

            self._map[(i, e)] = wall
            self._tiles.setdefault(wall.getType(), []).append(wall)
Exemplo n.º 14
0
    def play(self):
        """
        Sets up our scene and executes the game loop.
        """
        self.is_running = True
        self.is_building_wall = False
        self.balls = []
        color = (255, 255, 255)
        self.walls = [Wall((1, 1), (self.width-1, 1), color),                           # ceiling
                      Wall((1, 1), (1, self.height-1), color),                          # left wall
                      Wall((1, self.height-1), (self.width-1, self.height-1), color),   # floor
                      Wall((self.width-1, 1), (self.width-1, self.height-1), color)]    # right wall

        last_frame_time = time.time()
        while self.is_running:
            time_remaining = 1. / self.frames_per_second - (time.time() - last_frame_time)
            if time_remaining > 0:
                time.sleep(time_remaining)
            current_frame_time = time.time()
            dt = current_frame_time - last_frame_time
            dt = max(0.00001, min(dt, 0.1))
            last_frame_time = current_frame_time

            self.event_handler()
            self.update(dt)
            self.render()
Exemplo n.º 15
0
 def create_wall(self, player_number):
     """
     Creates a new wall that the players cannot cross based on the last position that the player turned and
     the players current position.
     :param player_number: The index of the player who the wall is being created from.
     :return: a new Wall object.
     """
     horizontal = self.wall_start[player_number][1] == self.characters[
         player_number].get_y_pos()
     if horizontal:
         if self.wall_start[player_number][0] < self.characters[
                 player_number].get_x_pos():
             new_wall = Wall(horizontal, self.wall_start[player_number][0],
                             self.characters[player_number].get_x_pos(),
                             self.characters[player_number].get_y_pos(),
                             self.characters[player_number].get_color())
         else:
             new_wall = Wall(horizontal,
                             self.characters[player_number].get_x_pos(),
                             self.wall_start[player_number][0],
                             self.characters[player_number].get_y_pos(),
                             self.characters[player_number].get_color())
     else:
         if self.wall_start[player_number][1] < self.characters[
                 player_number].get_y_pos():
             new_wall = Wall(horizontal, self.wall_start[player_number][0],
                             self.wall_start[player_number][1],
                             self.characters[player_number].get_y_pos(),
                             self.characters[player_number].get_color())
         else:
             new_wall = Wall(horizontal, self.wall_start[player_number][0],
                             self.characters[player_number].get_y_pos(),
                             self.wall_start[player_number][1],
                             self.characters[player_number].get_color())
     return new_wall
Exemplo n.º 16
0
 def __init__(self, game):
     """init and position the wall"""
     # we use only white dragons for building the wall. We could actually
     # use any tile because the face is never shown anyway.
     game.wall = self
     Wall.__init__(self, game)
     self.__square = Board(1, 1, Tileset.activeTileset())
     self.__square.setZValue(ZValues.marker)
     sideLength = len(self.tiles) // 8
     self.__sides = [UIWallSide(
         Tileset.activeTileset(),
         boardRotation, sideLength) for boardRotation in (0, 270, 180, 90)]
     for side in self.__sides:
         side.setParentItem(self.__square)
         side.lightSource = self.lightSource
         side.windTile = PlayerWind(
             East,
             Internal.scene.windTileset,
             parent=side)
         side.windTile.hide()
         side.nameLabel = QGraphicsSimpleTextItem('', side)
         side.message = YellowText(side)
         side.message.setZValue(ZValues.popup)
         side.message.setVisible(False)
         side.message.setPos(side.center())
     self.__sides[0].setPos(yWidth=sideLength)
     self.__sides[3].setPos(xHeight=1)
     self.__sides[2].setPos(xHeight=1, xWidth=sideLength, yHeight=1)
     self.__sides[1].setPos(xWidth=sideLength, yWidth=sideLength, yHeight=1)
     self.__findOptimalFontHeight()
     Internal.scene.addItem(self.__square)
     Internal.Preferences.addWatch('showShadows', self.showShadowsChanged)
Exemplo n.º 17
0
    def __init__(self):
        pygame.init()
        pygame.display.set_caption("My Pong Game")
        self.screen = pygame.display.set_mode((800, 600))
        self.running = True
        self.clock = pygame.time.Clock()
        self.walls = [Wall((10, 10), 780, 10),
                      Wall((10, 580), 780,
                           10)]  # Position and dimensions of walls
        self.background = pygame.Surface((800, 600))
        self.background.fill(pygame.Color("#000000"))
        self.ball = Ball((400, 300))
        self.font = pygame.font.Font(None, 50)

        control_scheme_1 = ControlScheme()
        control_scheme_1.up = pygame.K_w
        control_scheme_1.down = pygame.K_s

        control_scheme_2 = ControlScheme()
        control_scheme_2.up = pygame.K_UP
        control_scheme_2.down = pygame.K_DOWN

        self.bats = [
            Bat((10, 200), 10, 100, control_scheme_1),
            Bat((780, 200), 10, 100, control_scheme_2)
        ]  # Position and dimensions of paddles, their respective control schemes
        self.score = Score(self.font)
Exemplo n.º 18
0
 def __create_walls(self):
     self.__walls = []
     for x in range(self.width()):
         self.__walls.append(Wall(x, 0))
         self.__walls.append(Wall(x, self.height() - 1))
     for y in range(1, self.height()):
         self.__walls.append(Wall(0, y))
         self.__walls.append(Wall(self.width() - 1, y))
Exemplo n.º 19
0
 def create_initial_walls(self):
     """
     Creates walls around the border of the map.
     :return: None
     """
     self.walls.append(Wall(True, 0, 1280, 0, 'black'))
     self.walls.append(Wall(True, 0, 1280, 707, 'black'))
     self.walls.append(Wall(False, 0, 0, 720, 'black'))
     self.walls.append(Wall(False, 1280, 0, 720, 'black'))
Exemplo n.º 20
0
 def __init__(self, screen):
     self.screen = screen
     self.score = 0
     self.is_gameover = True
     self.is_paused = False
     self.time_interval = GameConfig.TIMER_INTERVAL
     self.piece = None
     self.next_piece = None
     self.wall = Wall(self.screen)
Exemplo n.º 21
0
    def __init__(self, initial_wall_bitmap, mine_max_speed, mine_rad,
                 are_mines_magnetic, ball_max_speed, ball_rad,
                 initial_ball_poss, width_in_tiles, height_in_tiles,
                 tile_width, tile_height, power_fill_speed, full_power_level,
                 explosive_power_level, min_spawn_time, max_spawn_time,
                 min_ball_added_mine_dist):

        self.initial_wall_bitmap = initial_wall_bitmap

        self.mine_max_speed = mine_max_speed
        self.mine_rad = mine_rad
        self.are_mines_magnetic = are_mines_magnetic

        self.ball_max_speed = ball_max_speed
        self.ball_rad = ball_rad
        self.initial_ball_poss = initial_ball_poss

        self.width_in_tiles = width_in_tiles
        self.height_in_tiles = height_in_tiles
        self.tile_width = tile_width
        self.tile_height = tile_height

        self.width = width_in_tiles * tile_width
        self.height = height_in_tiles * tile_height

        self.power_fill_speed = power_fill_speed
        self.full_power_level = full_power_level
        self.explosive_power_level = explosive_power_level
        self.min_spawn_time = min_spawn_time
        self.max_spawn_time = max_spawn_time
        self.min_ball_added_mine_dist = min_ball_added_mine_dist

        assert (self.min_ball_added_mine_dist > 0.0)
        assert (self.min_spawn_time > 0.0)
        assert (self.min_spawn_time <= self.max_spawn_time)
        assert (self.power_fill_speed > 0.0)
        assert (self.full_power_level > 0.0)
        assert (self.explosive_power_level is None
                or self.explosive_power_level >= self.full_power_level)

        area_in_tiles = width_in_tiles * height_in_tiles
        assert (len(initial_wall_bitmap) == area_in_tiles)
        assert (width_in_tiles > 0)
        assert (height_in_tiles > 0)
        assert (tile_width > 0.0)
        assert (tile_height > 0.0)
        assert (mine_max_speed > 0.0)
        assert (ball_max_speed > 0.0)
        assert (mine_rad > 0.0)
        assert (ball_rad > 0.0)

        wall = Wall(self)
        for i in range(len(initial_ball_poss)):
            pos = initial_ball_poss[i]
            assert (wall.is_circle_within_borders(pos, ball_rad))  # REM?
            assert (not wall.is_circle_collision(pos, ball_rad))
Exemplo n.º 22
0
class Game:
    def __init__(self, preference):
        self.preference = preference
        self.display = pygame.display.set_mode(preference.display)
        pygame.display.set_caption("Bricks")
        # Game Properties
        self.running = True
        self.bricks = pygame.sprite.Group()
        self.wall = Wall(self)
        self.bullet = Bullet(self)

        pygame.init()

        self.start()
        self.main_loop()

    def main_loop(self):
        def update():
            self._update()
            self._flip()

        while self.running:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    self.running = False
                if event.type == pygame.KEYUP and event.key == pygame.K_r:
                    self.start()
            update()

    def start(self):
        brick = self.preference.brick
        margin = self.preference.margin

        self.bricks = pygame.sprite.Group()
        self.wall = Wall(self)
        self.bullet = Bullet(self)
        for x in range(self.preference.army[0]):
            for y in range(self.preference.army[1]):
                b = Brick(self,
                          x * (brick[0] + margin[0]) + margin[0],
                          y * (brick[1] + margin[1]) + margin[1])
                self.bricks.add(b)

    def _update(self):
        self.wall.update()
        self.bricks.update()
        self.bullet.update()

    def _flip(self):
        self.display.fill((255, 255, 255))

        self.wall.draw()
        self.bullet.draw()
        for brick in self.bricks:
            brick.draw()
        pygame.display.flip()
Exemplo n.º 23
0
 def __init__(self, grid, wall_inverse_ratio=10):
     self.width = grid.get_width()
     self.height = grid.get_height()
     self.grid = grid
     self.vertical_walls = [[
         Wall(0, wall_inverse_ratio) for i in range(self.width + 1)
     ] for j in range(self.height)]
     self.horizontal_walls = [[
         Wall(1, wall_inverse_ratio) for i in range(self.width)
     ] for j in range(self.height + 1)]
Exemplo n.º 24
0
def create_wall(ai_settings, screen, walls, center_wall, column_number,
                row_number):
    """Specify the correct coordinates for the individual walls to 
	spawn and Adds the new wall into the list(walls)."""
    new_wall = Wall(ai_settings, screen)
    new_wall.centerx = wall_get_x(ai_settings, new_wall.rect, column_number,
                                  center_wall)
    new_wall.centery = wall_get_y(ai_settings, new_wall.rect, row_number,
                                  center_wall)
    walls.add(new_wall)
Exemplo n.º 25
0
 def make_walls(self):
     self.obstacles.append(
         Wall(Point2D(0, 0), Point2D(self.minuature_width, 0)))
     self.obstacles.append(
         Wall(Point2D(0, 0), Point2D(0, self.minuature_height)))
     self.obstacles.append(
         Wall(Point2D(self.minuature_width, self.minuature_height),
              Point2D(self.minuature_width, 0)))
     self.obstacles.append(
         Wall(Point2D(self.minuature_width, self.minuature_height),
              Point2D(0, self.minuature_height)))
Exemplo n.º 26
0
def generation_room(x_initial, y_initial, room):
    x = x_initial
    y = y_initial
    for i in range(len(room)):
        for j in range(len(room[0])):
            if room[i][j] == "f":
                pf = Floor(x, y, random.randint(0,5))
                layer_0.add(pf)
            if room[i][j] == "w":
                pf = Wall(x, y, 4)
                layer_1.add(pf)
            if room[i][j] == "d":
                pf = Wall(x, y, 1)
                layer_2.add(pf)
            if room[i][j] == "v":
                pf = Wall(x, y, 2)
                layer_2.add(pf)
            if room[i][j] == "x":
                pf = Wall(x, y, 0)
                layer_0.add(pf)
                wall.append(pf)
            if room[i][j] == "u":
                pf = Wall(x, y, 3)
                layer_1.add(pf)
                r = random.randint(0, 100)
                if r <= 5:
                    torch = Torch(x, y, 3)
                    layer_1.add(torch)
            if room[i][j] == "c":
                r = random.randint(3, 10)
                if r >= 5:
                    pf = Floor(x, y, 6)
                    layer_0.add(pf)
                    pf = Chest(x, y-6, random.randint(1, 2))
                    layer_1.add(pf)
                    chest.append(pf)
                else:
                    pf = Floor(x, y, 6)
                    layer_0.add(pf)
            if room[i][j] == "z":
                pf = Monster_spawn(x, y)
                layer_0.add(pf)
                r = random.randint(2, 5)
                for i in range(r):
                    x_ = random.randint(pf.rect.x-32, pf.rect.x+64)
                    y_ = random.randint(pf.rect.y-32, pf.rect.y+64)
                    pf = Monster(x_, y_, random.randint(1, 4))
                    layer_1.add(pf)
                    layer_monster.add(pf)
                    layer_all_monster_and_layer.add(pf)

            x += 32
        x = x_initial
        y += 32
Exemplo n.º 27
0
 def divide(self):
     """divides a wall, building a living and and a dead end"""
     with MoveImmediate():
         Wall.divide(self)
         for uiTile in self.tiles:
             # update graphics because tiles having been
             # in kongbox in a previous game
             # might not be there anymore. This gets rid
             # of the cross on them.
             uiTile.update()
         # move last two tiles onto the dead end:
         return self._placeLooseTiles()
Exemplo n.º 28
0
 def divide(self):
     """divides a wall, building a living end and a dead end"""
     with AnimationSpeed():
         Wall.divide(self)
         for uiTile in self.tiles:
             # update graphics because tiles having been
             # in kongbox in a previous game
             # might not be there anymore. This gets rid
             # of the cross on them.
             uiTile.update()
         # move last two tiles onto the dead end:
         return self._placeLooseTiles()
Exemplo n.º 29
0
    def start(self):
        brick = self.preference.brick
        margin = self.preference.margin

        self.bricks = pygame.sprite.Group()
        self.wall = Wall(self)
        self.bullet = Bullet(self)
        for x in range(self.preference.army[0]):
            for y in range(self.preference.army[1]):
                b = Brick(self,
                          x * (brick[0] + margin[0]) + margin[0],
                          y * (brick[1] + margin[1]) + margin[1])
                self.bricks.add(b)
Exemplo n.º 30
0
def addRegularShape(center, radius, nSides):
    angleToTurn = 360 / nSides
    points = []
    radiusVector = Vector(radius, 0)
    for x in range(nSides):
        point = center + radiusVector
        points.append(point)
        radiusVector = radiusVector.rotate(radians(angleToTurn))

    for i in range(len(points)-1):
        walls.append(Wall(points[i], points[i+1], colour=BLACK, width=1))

    walls.append(Wall(points[-1], points[0], colour=BLACK, width=1))
Exemplo n.º 31
0
def create_map():
    map = []
    if guy.stage == 1:
        map_file = open('map1.json', 'r')
    elif guy.stage == 2:
        map_file = open('map2.json', 'r')
    elif guy.stage == 3:
        map_file = open('map3.json', 'r')
    map_data = json.load(map_file)
    map_file.close()
    tile_width = map_data['layers'][0]['width']
    tile_height = map_data['layers'][0]['height']
    tile_data = map_data['layers'][0]['data']


    count = 0



    for tile in tile_data:
        if tile in range (1,6):
            wall = Wall()
            wall.idx = count
            wall.x = 25 + 50 * (wall.idx % tile_width )         + 1000
            wall.y = 25 + 50 * (tile_height - 1 - (wall.idx//tile_width))   + 1000
            if tile == 2:
                wall.shape = wall.DOWN
            if tile == 3:
                wall.shape = wall.LEFT
            if tile == 4:
                wall.shape = wall.RIGHT
            if tile == 5:
                wall.shape = wall.UP

            map.append(wall)
        elif tile == 6:

            portal.x = 25 + 50 * (count % tile_width) + 1000
            portal.y = 75 + 50 * (tile_height-1 - count // tile_width) + 1000
            portal.dir = 0
        elif tile == 7:

            portal.x = 75 + 50 * (count % tile_width) + 1000
            portal.y = 25 + 50 * (tile_height-1 - count // tile_width) + 1000
            portal.dir = 1
        elif tile == 8:


            guy.initx = 25 + 50 * (count % tile_width) + 1000
            guy.inity = 50 + 50 * (tile_height-1 - (count // tile_width)) + 1000
            guy.x = guy.initx
            guy.y = guy.inity

        count += 1

    return map
Exemplo n.º 32
0
    def __init__(self, preference):
        self.preference = preference
        self.display = pygame.display.set_mode(preference.display)
        pygame.display.set_caption("Bricks")
        # Game Properties
        self.running = True
        self.bricks = pygame.sprite.Group()
        self.wall = Wall(self)
        self.bullet = Bullet(self)

        pygame.init()

        self.start()
        self.main_loop()
Exemplo n.º 33
0
 def removePlayer(self, player):
     if abs(self.findDistance(player)) < self._wallSize:
         if abs(self.getSlope()) >= 1:
             changeInY = player.getPosition()[1] - self.getPoints()[1][1]
             player.setPosition(
                 self.__nextWarp.getPoints()[0][0] +
                 changeInY / self.getSlope(),
                 self.__nextWarp.getPoints()[0][1] + changeInY)
         else:
             changeInX = player.getPosition()[0] - self.getPoints()[1][0]
             player.setPosition(
                 self.__nextWarp.getPoints()[0][0] + changeInX,
                 self.__nextWarp.getPoints()[0][1] +
                 self.getSlope() * changeInX)
         wall = Wall(self.__nextWarp.getPoints()[0][0],
                     self.__nextWarp.getPoints()[0][1],
                     self.__nextWarp.getPoints()[1][0],
                     self.__nextWarp.getPoints()[1][1])
         wall.isEnabled(True)
         wall.removePlayer(player)
         player.move()
         wall.isEnabled(False)
         self.__thisRoom.unloadRoom()
         #   Reloading the room fixes bugs with items being present when they shouldn't be
         self.__thisRoom.loadRoom()
         self.__thisRoom.unloadRoom()
         self.__nextRoom.loadRoom()
Exemplo n.º 34
0
	def __init__( self ):

		self.core = Core( 60, 1024, 768, "Ninja" )

		self.intro = Intro()

		self.menu_background = Texture( "menu/background.png" )
		self.menu_title = Menu_title()
		self.menu_play_button = Menu_play_button()
		self.menu_git_button = Menu_link_button( "menu/git.png", "https://github.com/Adriqun" )
		self.menu_google_button = Menu_link_button( "menu/google.png", "https://en.wikipedia.org/wiki/Ninja" )
		self.menu_facebook_button = Menu_link_button( "menu/facebook.png", "nothing", True )
		self.menu_twitter_button = Menu_link_button( "menu/twitter.png", "nothing", True )
		self.menu_music_button = Menu_music_button( "menu/music.png" )
		self.menu_chunk_button = Menu_music_button( "menu/chunk.png", 1 )
		self.menu_exit_log = Menu_exit_log()
		self.menu_author_log = Menu_author_log()
		self.menu_game_log = Menu_link_button( "menu/game.png", "nothing", True )
		self.menu_settings_log = Menu_link_button( "menu/settings.png", "nothing", True )
		self.menu_score_log = Menu_score_log()
		self.menu_music = Menu_music( "menu/Rayman Legends OST - Moving Ground.mp3" )
		
		self.wall = Wall()
		self.hero = Hero()
		self.menu_log = Menu_log()
		self.map = Map()
Exemplo n.º 35
0
	def __init__(self):
		super(WallGame, self).__init__('Wall', WallGame.BLACK)
		self.arrow = []
		for i in range(10):
			self.arrow.append(Arrow(key = random.randint(0,25), color = WallGame.WHITE , pos = (random.randint(800,1000), random.randint(50,350)), speed = 1))
		self.wall = Wall(pos = (200,0), color = WallGame.WHITE)
		self.score = 0
		self.count_speed_up = 0
		self.count_speed_down = 0
		self.dead = True
Exemplo n.º 36
0
def notice_mail_day(to_id, li):
    from user_mail import mail_by_user_id

    to_user = Zsite.mc_get(to_id)
    name = to_user.name
    mail = mail_by_user_id(to_id)
    count = len(li)
    li_wall = []
    _li_wall_reply = defaultdict(list)

    for from_id, cid, rid in li:
        from_user = Zsite.mc_get(from_id)
        if cid == CID_NOTICE_WALL:
            li_wall.append(from_user)
        elif cid == CID_NOTICE_WALL_REPLY:
            o = Wall.mc_get(rid)
            _li_wall_reply[rid].append(from_user)

    li_wall_reply = {}

    for rid, from_list in _li_wall_reply.iteritems():
        o = Wall.mc_get(rid)
        li_wall_reply[o] = from_list

    if li_wall or li_wall_reply:

        subject = render_template(
            '/mail/notice/day_total.txt',
            count=count,
            li_wall=li_wall,
            li_wall_reply=li_wall_reply,
        )

        rendermail(
            '/mail/notice/day_total.htm',
            mail,
            name,
            to_user=to_user,
            li_wall=li_wall,
            li_wall_reply=li_wall_reply,
            format='html',
            subject=subject,
        )
Exemplo n.º 37
0
   def fromJson(jsonData, player):
      backgroundTile = jsonData["backgroundTile"]
      walls = Wall.fromJson(jsonData["walls"])
      location = jsonData["locationName"]
      ov =  Overworld(backgroundTile, player, location, walls)

      for monster in jsonData['monsters']:
         center = (monster['location'][0] * 32 + 16,
                   monster['location'][1] * 32 + 16)
         ov.addNPC(load_monster(monster['name'], center=center))

      return ov
Exemplo n.º 38
0
class Engine:

#-------------------------------------------------------------------------------------------------------
	def __init__( self ):

		self.core = Core( 60, 1024, 768, "Ninja" )

		self.intro = Intro()

		self.menu_background = Texture( "menu/background.png" )
		self.menu_title = Menu_title()
		self.menu_play_button = Menu_play_button()
		self.menu_git_button = Menu_link_button( "menu/git.png", "https://github.com/Adriqun" )
		self.menu_google_button = Menu_link_button( "menu/google.png", "https://en.wikipedia.org/wiki/Ninja" )
		self.menu_facebook_button = Menu_link_button( "menu/facebook.png", "nothing", True )
		self.menu_twitter_button = Menu_link_button( "menu/twitter.png", "nothing", True )
		self.menu_music_button = Menu_music_button( "menu/music.png" )
		self.menu_chunk_button = Menu_music_button( "menu/chunk.png", 1 )
		self.menu_exit_log = Menu_exit_log()
		self.menu_author_log = Menu_author_log()
		self.menu_game_log = Menu_link_button( "menu/game.png", "nothing", True )
		self.menu_settings_log = Menu_link_button( "menu/settings.png", "nothing", True )
		self.menu_score_log = Menu_score_log()
		self.menu_music = Menu_music( "menu/Rayman Legends OST - Moving Ground.mp3" )
		
		self.wall = Wall()
		self.hero = Hero()
		self.menu_log = Menu_log()
		self.map = Map()
	
#-------------------------------------------------------------------------------------------------------

	def load( self ):

		self.core.setState( -1 )

		self.intro.load( self.core.getWidth(), self.core.getHeight() )

		self.menu_title.load( self.core.getWidth() )
		self.menu_play_button.load( self.core.getWidth(), self.core.getHeight() )
		self.menu_git_button.load( self.core.getWidth(), 10 )
		self.menu_google_button.load( self.core.getWidth(), self.menu_git_button.getBot() )
		self.menu_facebook_button.load( self.core.getWidth(), self.menu_google_button.getBot() )
		self.menu_twitter_button.load( self.core.getWidth(), self.menu_facebook_button.getBot() )
		self.menu_music_button.load( 10 )
		self.menu_chunk_button.load( self.menu_music_button.getBot() )
		self.menu_exit_log.load( self.core.getWidth(), self.core.getHeight() )
		self.menu_author_log.load( self.menu_play_button.getLeft()+5, self.core.getWidth(), self.menu_title.getBot() +150, self.menu_play_button.getBot() )
		self.menu_game_log.load( self.menu_author_log.getRight(), self.menu_play_button.getBot() +10, True )
		self.menu_settings_log.load( self.menu_game_log.getRight(), self.menu_play_button.getBot() +10, True )
		self.menu_score_log.load( self.menu_settings_log.getRight(), self.core.getWidth(), self.menu_title.getBot() +150, self.menu_play_button.getBot() )

		self.wall.load()
		self.hero.load( self.core.getWidth(), self.core.getHeight() )
		self.menu_log.load( self.core.getWidth(), self.core.getHeight() )
		self.map.load()

#-------------------------------------------------------------------------------------------------------	

	def handle( self ):
		for event in pygame.event.get():

			if event.type == pygame.QUIT:
				self.core.setQuit()

#-------------------------------------------------------------------------------------------------------

			if self.core.getState() == 0:
				
				if self.menu_play_button.getState() == 0:
					self.menu_exit_log.handle( event )

				#HANDLE IF AUTHOR BUTTON == OFF AND SCORE BUTTON == OFF
				if self.menu_author_log.getState() == 0 and self.menu_score_log.getState() == 0:
					self.menu_play_button.handle( event )
					self.menu_git_button.handle( event )
					self.menu_google_button.handle( event )
					self.menu_music_button.handle( event )
					self.menu_chunk_button.handle( event )
				if self.menu_score_log.getState() == 0:
					self.menu_author_log.handle( event )
				if self.menu_author_log.getState() == 0:
					self.menu_score_log.handle( event )

#-------------------------------------------------------------------------------------------------------

			if self.core.getState() == 1:
				
				self.menu_log.handle( event )
				#HANDLE IF MENU_LOG == OFF
				if self.menu_log.getState() == 0:
					self.hero.handle( event )
				
#-------------------------------------------------------------------------------------------------------

	def states( self ):

#-------------------------------------------------------------------------------------------------------STATE -1

		if self.core.getState() == -1:
			self.intro.draw( self.core.getWindow() )
			if self.intro.getQuit():
				self.intro.free()
				del self.intro
				self.menu_music.play()#MENU MUSIC
				self.core.setState( 0 )
		

#-------------------------------------------------------------------------------------------------------STATE 0

		if self.core.getState() == 0:

			#FADE IN
			if self.menu_play_button.getState() != 1 and self.menu_exit_log.getState() == 0:
				self.menu_background.fadein( 5 )
				self.menu_title.fadein( 5 )
				self.menu_play_button.fadein( 5 )
				self.menu_git_button.fadein( 5 )
				self.menu_google_button.fadein( 5 )
				self.menu_facebook_button.fadein( 5 )
				self.menu_twitter_button.fadein( 5 )
				self.menu_music_button.fadein( 5 )
				self.menu_chunk_button.fadein( 5 )
				self.menu_author_log.fadein( 5 )
				self.menu_game_log.fadein( 5 )
				self.menu_settings_log.fadein( 5 )
				self.menu_score_log.fadein( 5 )
				self.menu_music.setVolume( 1.0 )

			#DRAW ALWAYS IN MENU STATE
			self.menu_background.draw( self.core.getWindow() )
			self.menu_title.draw( self.core.getWindow() )
			self.menu_exit_log.draw( self.core.getWindow() )
			#DRAW IF AUTHOR BUTTON == OFF AND SCORE BUTTON == OFF
			if self.menu_author_log.getState() == 0 and self.menu_score_log.getState() == 0:
				self.menu_git_button.draw( self.core.getWindow() )			
				self.menu_google_button.draw( self.core.getWindow() )
				self.menu_facebook_button.draw( self.core.getWindow() )
				self.menu_twitter_button.draw( self.core.getWindow() )
				self.menu_play_button.draw( self.core.getWindow() )
				self.menu_music_button.draw( self.core.getWindow() )
				self.menu_chunk_button.draw( self.core.getWindow() )
				self.menu_game_log.draw( self.core.getWindow() )
				self.menu_settings_log.draw( self.core.getWindow() )

			if self.menu_score_log.getState() == 0:
				self.menu_author_log.draw( self.core.getWindow() )
			if self.menu_author_log.getState() == 0:
				self.menu_score_log.draw( self.core.getWindow() )

			#IF USER TURN ON/OFF CHUNKS
			if self.menu_chunk_button.getState():
				self.menu_play_button.setState()
				self.menu_git_button.setState()
				self.menu_google_button.setState()
				self.menu_music_button.setState()
				self.menu_chunk_button.setState()
				self.menu_author_log.setState()
				self.menu_score_log.setState()
			#IF USER TURN ON/OFF MUSIC
			if self.menu_music_button.getState():
				self.menu_music.pause()

			#IF USER PRESS Q - EXIT
			if self.menu_exit_log.getState() == 1:
				self.menu_background.fadeout( 6, 120 )
				self.menu_title.fadeout( 6, 120 )
				self.menu_play_button.fadeout( 6, 120 )
				self.menu_git_button.fadeout( 6, 120 )
				self.menu_google_button.fadeout( 6, 120 )
				self.menu_facebook_button.fadeout( 6, 120 )
				self.menu_twitter_button.fadeout( 6, 120 )
				self.menu_music_button.fadeout( 6, 120 )
				self.menu_chunk_button.fadeout( 6, 120 )
				self.menu_author_log.fadeout( 6, 120 )
				self.menu_game_log.fadeout( 6, 120 )
				self.menu_settings_log.fadeout( 6, 120 )
				self.menu_score_log.fadeout( 6, 120 )
				self.menu_music.setVolume( 0.3 )

			elif self.menu_exit_log.getState() == 2:
				self.menu_background.fadeout( 6 )
				self.menu_title.fadeout( 6 )
				self.menu_play_button.fadeout( 6 )
				self.menu_git_button.fadeout( 6 )
				self.menu_google_button.fadeout( 6 )
				self.menu_facebook_button.fadeout( 6 )
				self.menu_twitter_button.fadeout( 6 )
				self.menu_music_button.fadeout( 6 )
				self.menu_chunk_button.fadeout( 6 )
				self.menu_author_log.fadeout( 6 )
				self.menu_game_log.fadeout( 6 )
				self.menu_settings_log.fadeout( 6 )
				self.menu_score_log.fadeout( 6 )
			if self.menu_exit_log.getState() == 2 and self.menu_background.getAlpha() == 0:
				self.core.setQuit()

			#IF USER CLICK PLAY BUTTON
			if self.menu_play_button.getState() == 1:
				self.menu_background.fadeout( 6 )
				self.menu_title.fadeout( 6 )
				self.menu_play_button.fadeout( 6 )
				self.menu_git_button.fadeout( 6 )
				self.menu_google_button.fadeout( 6 )
				self.menu_facebook_button.fadeout( 6 )
				self.menu_twitter_button.fadeout( 6 )
				self.menu_music_button.fadeout( 6 )
				self.menu_chunk_button.fadeout( 6 )
				self.menu_author_log.fadeout( 6 )
				self.menu_game_log.fadeout( 6 )
				self.menu_settings_log.fadeout( 6 )
				self.menu_score_log.fadeout( 6 )
				if self.menu_music.isPaused() == False:
					self.menu_music.fadeOut()

				if self.menu_play_button.getAlpha() == 0:
					self.menu_play_button.setNext( 0 )
					self.core.setState( 1 )

#-------------------------------------------------------------------------------------------------------STATE 1
		
		if self.core.getState() == 1:
			
			#FADE IN IF PAUSE BUTTON == OFF AND MENU_LOG == OFF
			if self.menu_log.getState() == 0:
				self.wall.fadein( 5 )
				self.hero.fadein( 5 )
				self.map.fadein( 5 )
			elif self.menu_log.getState() == 1:
				self.wall.fadeout( 6, 130 )
				self.hero.fadeout( 6, 130 )
				self.map.fadeout( 6, 130 )
			elif self.menu_log.getState() == 2:
				self.wall.fadeout( 6 )
				self.hero.fadeout( 6 )
				self.map.fadeout( 6 )
				if self.wall.getAlpha() == 0:
					self.menu_log.setState( 0 )
					if self.menu_music.isPaused() == False:
						self.menu_music.play()
					self.core.setState( 0 ) #Back to menu
			
			#DRAW
			self.wall.draw( self.core.getWindow() )
			self.hero.draw( self.core.getWindow() )
			self.menu_log.draw( self.core.getWindow() )
			self.map.draw( self.core.getWindow() )














	def loop( self ):
		while not self.core.isQuit():
			self.handle()
			self.core.fillDisplay()
			self.states()
			self.core.tickClock()
			pygame.display.update()
			
	def quit( self ):
		pygame.quit()
Exemplo n.º 39
0
class WallGame(gamelib.SimpleGame):
	BLACK = pygame.Color('black')
	WHITE = pygame.Color('white')
	GREEN = pygame.Color('green')
	
	def __init__(self):
		super(WallGame, self).__init__('Wall', WallGame.BLACK)
		self.arrow = []
		for i in range(10):
			self.arrow.append(Arrow(key = random.randint(0,25), color = WallGame.WHITE , pos = (random.randint(800,1000), random.randint(50,350)), speed = 1))
		self.wall = Wall(pos = (200,0), color = WallGame.WHITE)
		self.score = 0
		self.count_speed_up = 0
		self.count_speed_down = 0
		self.dead = True
		
	def init(self):
		super(WallGame, self).init()
		self.render_score()

		
	def update(self):
		if self.dead is True:
			for i in self.arrow:
				i.move()
				if self.is_key_pressed(i.key_press(i.get_key())):
					i.remove()
					self.score += 1
					self.render_score()
					self.count_speed_up += 1
				if i.get_x() < 200:
					i.remove()
					self.score -= 5
					self.render_score()
					self.count_speed_down += 1
				if self.count_speed_up == 10:
					i.speed_up()
					self.count_speed_up = 0
				if self.count_speed_down == 100:
					i.speed_down()
					self.count_speed_down = 0
				if self.score < 0:
					self.is_dead()

	def is_dead(self):
		self.dead = False
		self.render_dead()
		self.score = 0
		self.render_score()

		
	def render_dead(self):
		self.dead_image = self.font.render("BooM Your Dead!!!", 0,WallGame.WHITE)
				
	def render_score(self):
		self.score_image = self.font.render("Score = %d" % self.score, 0, WallGame.WHITE)

	def render_key(self):
		for i in self.arrow:
			i.key_image = self.font.render("%c" % i.key_arrow(i.get_key()), 0, WallGame.WHITE)
		

	def render(self, surface):
		surface.blit(self.score_image, (10,10))
		if self.dead is False:
			surface.blit(self.dead_image,(300,150))
		self.render_key()
		for i in self.arrow:
			surface.blit(i.key_image, (i.get_x(),i.get_y()))
		self.wall.render(surface)
Exemplo n.º 40
0
 def update(self):
     Wall.update(self)
Exemplo n.º 41
0
	def __init__(self, canvas, jenkins):
		Wall.__init__(self, canvas, jenkins)
Exemplo n.º 42
0
class Game(object):
    """the game without GUI"""
    # pylint: disable=R0902
    # pylint we need more than 10 instance attributes

    def __del__(self):
        """break reference cycles"""
        self.clearHand()
        if self.players:
            for player in self.players[:]:
                self.players.remove(player)
                del player
            self.players = []
        self.__activePlayer = None
        self.prevActivePlayer = None
        self.__winner = None
        self.myself = None
        if self.client:
            self.client.game = None
        self.client = None

    def __init__(self, names, ruleset, gameid=None, wantedGame=None, shouldSave=True, client=None):
        """a new game instance. May be shown on a field, comes from database if gameid is set

        Game.lastDiscard is the tile last discarded by any player. It is reset to None when a
        player gets a tile from the living end of the wall or after he claimed a discard.
        """
        # pylint: disable=R0915
        # pylint we need more than 50 statements
        self.players = Players() # if we fail later on in init, at least we can still close the program
        self._client = None
        self.client = client
        self.rotated = 0
        self.notRotated = 0 # counts hands since last rotation
        self.ruleset = None
        self.roundsFinished = 0
        self._currentHandId = None
        self._prevHandId = None
        self.seed = 0
        self.randomGenerator = CountingRandom(self)
        if self.isScoringGame():
            self.wantedGame = str(wantedGame)
            self.seed = wantedGame
        else:
            self.wantedGame = wantedGame
            _ = int(wantedGame.split('/')[0]) if wantedGame else 0
            self.seed = _ or int(self.randomGenerator.random() * 10**9)
        self.shouldSave = shouldSave
        self.__setHandSeed()
        self.activePlayer = None
        self.__winner = None
        self.moves = []
        self.myself = None   # the player using this client instance for talking to the server
        self.gameid = gameid
        self.playOpen = False
        self.autoPlay = False
        self.handctr = 0
        self.roundHandCount = 0
        self.handDiscardCount = 0
        self.divideAt = None
        self.lastDiscard = None # always uppercase
        self.visibleTiles = IntDict()
        self.discardedTiles = IntDict(self.visibleTiles) # tile names are always lowercase
        self.dangerousTiles = list()
        self.csvTags = []
        self._setGameId()
        self.__useRuleset(ruleset)
        # shift rules taken from the OEMC 2005 rules
        # 2nd round: S and W shift, E and N shift
        self.shiftRules = 'SWEN,SE,WE'
        field = Internal.field
        if field:
            field.game = self
            field.startingGame = False
            field.showWall()  # sets self.wall
        else:
            self.wall = Wall(self)
        self.assignPlayers(names)
        if self.belongsToGameServer():
            self.__shufflePlayers()
        if not self.isScoringGame() and '/' in self.wantedGame:
            roundsFinished, rotations, notRotated = self.__scanGameOption(self.wantedGame)
            for _ in range(roundsFinished * 4 + rotations):
                self.rotateWinds()
            self.notRotated = notRotated
        if self.shouldSave:
            self.saveNewGame()
        if field:
            self.__initVisiblePlayers()
            field.updateGUI()
            self.wall.decorate()

    @property
    def client(self):
        """hide weakref"""
        if self._client is not None:
            return self._client()
    @client.setter
    def client(self, value):
        """hide weakref"""
        if value is None:
            self._client = None
        else:
            self._client = weakref.ref(value)

    def __scanGameOption(self, wanted):
        """scan the --game option. Return roundsFinished, rotations, notRotated"""
        part = wanted.split('/')[1]
        roundsFinished = 'ESWN'.index(part[0])
        if roundsFinished > self.ruleset.minRounds:
            logWarning('Ruleset %s has %d minimum rounds but you want round %d(%s)' % (
                self.ruleset.name, self.ruleset.minRounds, roundsFinished + 1, part[0]))
            return self.ruleset.minRounds, 0
        rotations = int(part[1]) - 1
        notRotated = 0
        if rotations > 3:
            logWarning('You want %d rotations, reducing to maximum of 3' % rotations)
            return roundsFinished, 3, 0
        for char in part[2:]:
            if char < 'a':
                logWarning('you want %s, changed to a' % char)
                char = 'a'
            if char > 'z':
                logWarning('you want %s, changed to z' % char)
                char = 'z'
            notRotated = notRotated * 26 + ord(char) - ord('a') + 1
        return roundsFinished, rotations, notRotated

    @property
    def winner(self):
        """the name of the game server this game is attached to"""
        return self.__winner

    @winner.setter
    def winner(self, value):
        """the name of the game server this game is attached to"""
        if self.__winner != value:
            if self.__winner:
                self.__winner.invalidateHand()
            self.__winner = value
            if value:
                value.invalidateHand()

    def addCsvTag(self, tag, forAllPlayers=False):
        """tag will be written to tag field in csv row"""
        if forAllPlayers or self.belongsToHumanPlayer():
            self.csvTags.append('%s/%s' % (tag, self.handId()))

    def isFirstHand(self):
        """as the name says"""
        return self.roundHandCount == 0 and self.roundsFinished == 0

    def handId(self, withAI=True, withMoveCount=False):
        """identifies the hand for window title and scoring table"""
        aiVariant = ''
        if withAI and self.belongsToHumanPlayer():
            aiName = self.client.intelligence.name()
            if aiName != 'Default':
                aiVariant = aiName + '/'
        num = self.notRotated
        charId = ''
        while num:
            charId = chr(ord('a') + (num-1) % 26) + charId
            num = (num-1) / 26
        if self.finished():
            wind = 'X'
        else:
            wind = WINDS[self.roundsFinished]
        result = '%s%s/%s%s%s' % (aiVariant, self.seed, wind, self.rotated + 1, charId)
        if withMoveCount:
            result += '/moves:%d' % len(self.moves)
        if result != self._currentHandId:
            self._prevHandId = self._currentHandId
            self._currentHandId = result
        return result

    def _setGameId(self):
        """virtual"""
        assert not self # we want it to fail, and quiten pylint

    def close(self):
        """log off from the server and return a Deferred"""
        Internal.autoPlay = False # do that only for the first game
        self.__hideGame()
        if self.client:
            client = self.client
            self.client = None
            result = client.logout()
            client.delete()
        else:
            result = succeed(None)
        return result

    def __hideGame(self):
        """remove all visible traces of the current game"""
        field = Internal.field
        if isAlive(field):
            field.setWindowTitle('Kajongg')
        if field:
            field.discardBoard.hide()
            field.selectorBoard.tiles = []
            field.selectorBoard.allSelectorTiles = []
            if isAlive(field.centralScene):
                field.centralScene.removeTiles()
            field.clientDialog = None
            for player in self.players:
                if player.handBoard:
                    player.clearHand()
                    player.handBoard.hide()
            if self.wall:
                self.wall.hide()
        self.wall = None
        self.lastDiscard = None
        if field:
            field.actionAutoPlay.setChecked(False)
            field.startingGame = False
            field.game = None
            field.updateGUI()

    def __initVisiblePlayers(self):
        """make players visible"""
        for idx, player in enumerate(self.players):
            player.front = self.wall[idx]
            player.clearHand()
            player.handBoard.setVisible(True)
            scoring = self.isScoringGame()
            player.handBoard.setEnabled(scoring or \
                (self.belongsToHumanPlayer() and player == self.myself))
            player.handBoard.showMoveHelper(scoring)
        Internal.field.adjustView()

    def setConcealedTiles(self, allPlayerTiles):
        """when starting the hand. tiles is one string"""
        with Animated(False):
            for playerName, tileNames in allPlayerTiles:
                player = self.playerByName(playerName)
                player.addConcealedTiles(self.wall.deal(tileNames))

    def playerByName(self, playerName):
        """return None or the matching player"""
        if playerName is None:
            return None
        for myPlayer in self.players:
            if myPlayer.name == playerName:
                return myPlayer
        logException('Move references unknown player %s' % playerName)

    def losers(self):
        """the 3 or 4 losers: All players without the winner"""
        return list([x for x in self.players if x is not self.__winner])

    def belongsToRobotPlayer(self):
        """does this game instance belong to a robot player?"""
        return self.client and self.client.isRobotClient()

    def belongsToHumanPlayer(self):
        """does this game instance belong to a human player?"""
        return self.client and self.client.isHumanClient()

    def belongsToGameServer(self):
        """does this game instance belong to the game server?"""
        return self.client and self.client.isServerClient()

    @staticmethod
    def isScoringGame():
        """are we scoring a manual game?"""
        return False

    def belongsToPlayer(self):
        """does this game instance belong to a player (as opposed to the game server)?"""
        return self.belongsToRobotPlayer() or self.belongsToHumanPlayer()

    def assignPlayers(self, playerNames):
        """the server tells us the seating order and player names"""
        pairs = []
        for idx, pair in enumerate(playerNames):
            if isinstance(pair, basestring):
                wind, name = WINDS[idx], pair
            else:
                wind, name = pair
            pairs.append((wind, name))

        field = Internal.field
        if not self.players:
            if field:
                self.players = field.genPlayers()
            else:
                self.players = Players([Player(self) for idx in range(4)])
            for idx, pair in enumerate(pairs):
                wind, name = pair
                player = self.players[idx]
                Players.createIfUnknown(name)
                player.wind = wind
                player.name = name
        else:
            for idx, pair in enumerate(playerNames):
                wind, name = pair
                self.players.byName(name).wind = wind
        if self.client and self.client.name:
            self.myself = self.players.byName(self.client.name)
        self.sortPlayers()

    def assignVoices(self):
        """now we have all remote user voices"""
        assert self.belongsToHumanPlayer()
        available = Voice.availableVoices()[:]
        # available is without transferred human voices
        for player in self.players:
            if player.voice and player.voice.oggFiles():
                # remote human player sent her voice, or we are human and have a voice
                if Debug.sound and player != self.myself:
                    logDebug('%s got voice from opponent: %s' % (player.name, player.voice))
            else:
                player.voice = Voice.locate(player.name)
                if player.voice:
                    if Debug.sound:
                        logDebug('%s has own local voice %s' % (player.name, player.voice))
            if player.voice:
                for voice in Voice.availableVoices():
                    if voice in available and voice.md5sum == player.voice.md5sum:
                        # if the local voice is also predefined,
                        # make sure we do not use both
                        available.remove(voice)
        # for the other players use predefined voices in preferred language. Only if
        # we do not have enough predefined voices, look again in locally defined voices
        predefined = [x for x in available if x.language() != 'local']
        predefined.extend(available)
        for player in self.players:
            if player.voice is None and predefined:
                player.voice = predefined.pop(0)
                if Debug.sound:
                    logDebug('%s gets one of the still available voices %s' % (player.name, player.voice))

    def __shufflePlayers(self):
        """assign random seats to the players and assign winds"""
        self.players.sort(key=lambda x:x.name)
        self.randomGenerator.shuffle(self.players)
        for player, wind in zip(self.players, WINDS):
            player.wind = wind

    def __exchangeSeats(self):
        """execute seat exchanges according to the rules"""
        windPairs = self.shiftRules.split(',')[(self.roundsFinished-1) % 4]
        while len(windPairs):
            windPair = windPairs[0:2]
            windPairs = windPairs[2:]
            swappers = list(self.players[windPair[x]] for x in (0, 1))
            if self.belongsToPlayer():
                # we are a client in a remote game, the server swaps and tells us the new places
                shouldSwap = False
            elif self.isScoringGame():
                # we play a manual game and do only the scoring
                shouldSwap = Internal.field.askSwap(swappers)
            else:
                # we are the game server. Always swap in remote games.
                # do not do assert self.belongsToGameServer() here because
                # self.client might not yet be set - this code is called for all
                # suspended games but self.client is assigned later
                shouldSwap = True
            if shouldSwap:
                swappers[0].wind, swappers[1].wind = swappers[1].wind, swappers[0].wind
        self.sortPlayers()

    def sortPlayers(self):
        """sort by wind order. If we are in a remote game, place ourself at bottom (idx=0)"""
        players = self.players
        if Internal.field:
            fieldAttributes = list([(p.handBoard, p.front) for p in players])
        players.sort(key=lambda x: 'ESWN'.index(x.wind))
        if self.belongsToHumanPlayer():
            myName = self.myself.name
            while players[0].name != myName:
                values0 = players[0].values
                for idx in range(4, 0, -1):
                    this, prev = players[idx % 4], players[idx - 1]
                    this.values = prev.values
                players[1].values = values0
            self.myself = players[0]
        if Internal.field:
            for idx, player in enumerate(players):
                player.handBoard, player.front = fieldAttributes[idx]
                player.handBoard.player = player
        self.activePlayer = self.players['E']

    @staticmethod
    def _newGameId():
        """write a new entry in the game table
        and returns the game id of that new entry"""
        with Transaction():
            query = Query("insert into game(seed) values(0)")
            gameid, gameidOK = query.query.lastInsertId().toInt()
        assert gameidOK
        return gameid

    def saveNewGame(self):
        """write a new entry in the game table with the selected players"""
        if self.gameid is None:
            return
        if not self.isScoringGame():
            records = Query("select seed from game where id=?", list([self.gameid])).records
            assert records
            if not records:
                return
            seed = records[0][0]

        if not Internal.isServer and self.client:
            host = self.client.connection.url
        else:
            host = None

        if self.isScoringGame() or seed == 'proposed' or seed == host:
            # we reserved the game id by writing a record with seed == hostname
            starttime = datetime.datetime.now().replace(microsecond=0).isoformat()
            args = list([starttime, self.seed, int(self.autoPlay), self.ruleset.rulesetId])
            args.extend([p.nameid for p in self.players])
            args.append(self.gameid)
            with Transaction():
                Query("update game set starttime=?,seed=?,autoplay=?," \
                        "ruleset=?,p0=?,p1=?,p2=?,p3=? where id=?", args)
                if not Internal.isServer:
                    Query('update server set lastruleset=? where url=?',
                          list([self.ruleset.rulesetId, host]))

    def __useRuleset(self, ruleset):
        """use a copy of ruleset for this game, reusing an existing copy"""
        self.ruleset = ruleset
        self.ruleset.load()
        query = Query('select id from ruleset where id>0 and hash="%s"' % \
            self.ruleset.hash)
        if query.records:
            # reuse that ruleset
            self.ruleset.rulesetId = query.records[0][0]
        else:
            # generate a new ruleset
            self.ruleset.save(copy=True, minus=False)

    def __setHandSeed(self):
        """set seed to a reproducable value, independent of what happend
        in previous hands/rounds.
        This makes it easier to reproduce game situations
        in later hands without having to exactly replay all previous hands"""
        if self.seed is not None:
            seedFactor = (self.roundsFinished + 1) * 10000 + self.rotated * 1000 + self.notRotated * 100
            self.randomGenerator.seed(self.seed * seedFactor)

    def clearHand(self):
        """empty all data"""
        if self.moves:
            for move in self.moves:
                del move
        self.moves = []
        for player in self.players:
            player.clearHand()
        self.__winner = None
        self.__activePlayer = None
        self.prevActivePlayer = None
        Hand.clearCache(self)
        self.dangerousTiles = list()
        self.discardedTiles.clear()
        assert self.visibleTiles.count() == 0

    def prepareHand(self):
        """prepares the next hand"""
        self.clearHand()
        if self.finished():
            self.close()
        else:
            if not self.isScoringGame():
                self.sortPlayers()
            self.hidePopups()
            self.__setHandSeed()
            self.wall.build()

    def initHand(self):
        """directly before starting"""
        Hand.clearCache(self)
        self.dangerousTiles = list()
        self.discardedTiles.clear()
        assert self.visibleTiles.count() == 0
        if Internal.field:
            Internal.field.prepareHand()
        self.__setHandSeed()

    def hidePopups(self):
        """hide all popup messages"""
        for player in self.players:
            player.hidePopup()

    def saveHand(self):
        """save hand to database, update score table and balance in status line"""
        self.__payHand()
        self.__saveScores()
        self.handctr += 1
        self.notRotated += 1
        self.roundHandCount += 1
        self.handDiscardCount = 0

    def __needSave(self):
        """do we need to save this game?"""
        if self.isScoringGame():
            return True
        elif self.belongsToRobotPlayer():
            return False
        else:
            return self.shouldSave # as the server told us

    def __saveScores(self):
        """save computed values to database, update score table and balance in status line"""
        if not self.__needSave():
            return
        scoretime = datetime.datetime.now().replace(microsecond=0).isoformat()
        for player in self.players:
            if player.hand:
                manualrules = '||'.join(x.rule.name for x in player.hand.usedRules)
            else:
                manualrules = m18n('Score computed manually')
            Query("INSERT INTO SCORE "
                "(game,hand,data,manualrules,player,scoretime,won,prevailing,wind,"
                "points,payments, balance,rotated,notrotated) "
                "VALUES(%d,%d,?,?,%d,'%s',%d,'%s','%s',%d,%d,%d,%d,%d)" % \
                (self.gameid, self.handctr, player.nameid,
                    scoretime, int(player == self.__winner),
                    WINDS[self.roundsFinished % 4], player.wind, player.handTotal,
                    player.payment, player.balance, self.rotated, self.notRotated),
                list([player.hand.string, manualrules]))
            if Debug.scores:
                self.debug('%s: handTotal=%s balance=%s %s' % (
                    player,
                    player.handTotal, player.balance, 'won' if player == self.winner else ''))
            for usedRule in player.hand.usedRules:
                rule = usedRule.rule
                if rule.score.limits:
                    tag = rule.function.__class__.__name__
                    if hasattr(rule.function, 'limitHand'):
                        tag = rule.function.limitHand.__class__.__name__
                    self.addCsvTag(tag)

    def savePenalty(self, player, offense, amount):
        """save computed values to database, update score table and balance in status line"""
        if not self.__needSave():
            return
        scoretime = datetime.datetime.now().replace(microsecond=0).isoformat()
        with Transaction():
            Query("INSERT INTO SCORE "
                "(game,penalty,hand,data,manualrules,player,scoretime,"
                "won,prevailing,wind,points,payments, balance,rotated,notrotated) "
                "VALUES(%d,1,%d,?,?,%d,'%s',%d,'%s','%s',%d,%d,%d,%d,%d)" % \
                (self.gameid, self.handctr, player.nameid,
                    scoretime, int(player == self.__winner),
                    WINDS[self.roundsFinished % 4], player.wind, 0,
                    amount, player.balance, self.rotated, self.notRotated),
                list([player.hand.string, offense.name]))
        if Internal.field:
            Internal.field.updateGUI()

    def maybeRotateWinds(self):
        """rules which make winds rotate"""
        result = list(x for x in self.ruleset.filterFunctions('rotate') if x.rotate(self))
        if result:
            if Debug.explain:
                if not self.belongsToRobotPlayer():
                    self.debug(result, prevHandId=True)
            self.rotateWinds()
        return bool(result)

    def rotateWinds(self):
        """rotate winds, exchange seats. If finished, update database"""
        self.rotated += 1
        self.notRotated = 0
        if self.rotated == 4:
            if not self.finished():
                self.roundsFinished += 1
            self.rotated = 0
            self.roundHandCount = 0
        if self.finished():
            endtime = datetime.datetime.now().replace(microsecond=0).isoformat()
            with Transaction():
                Query('UPDATE game set endtime = "%s" where id = %d' % \
                    (endtime, self.gameid))
        elif not self.belongsToPlayer():
            # the game server already told us the new placement and winds
            winds = [player.wind for player in self.players]
            winds = winds[3:] + winds[0:3]
            for idx, newWind in enumerate(winds):
                self.players[idx].wind = newWind
            if self.roundsFinished % 4 and self.rotated == 0:
                # exchange seats between rounds
                self.__exchangeSeats()

    def debug(self, msg, btIndent=None, prevHandId=False):
        """prepend game id"""
        if self.belongsToRobotPlayer():
            prefix = 'R'
        elif self.belongsToHumanPlayer():
            prefix = 'C'
        elif self.belongsToGameServer():
            prefix = 'S'
        else:
            logDebug(msg, btIndent=btIndent)
            return
        logDebug('%s%s: %s' % (prefix, self._prevHandId if prevHandId else self.handId(), msg),
            withGamePrefix=False, btIndent=btIndent)

    @staticmethod
    def __getNames(record):
        """get name ids from record
        and return the names"""
        names = []
        for idx in range(4):
            nameid = record[idx]
            try:
                name = Players.allNames[nameid]
            except KeyError:
                name = m18n('Player %1 not known', nameid)
            names.append(name)
        return names

    @classmethod
    def loadFromDB(cls, gameid, client=None):
        """load game by game id and return a new Game instance"""
        Internal.logPrefix = 'S' if Internal.isServer else 'C'
        qGame = Query("select p0,p1,p2,p3,ruleset,seed from game where id = %d" % gameid)
        if not qGame.records:
            return None
        rulesetId = qGame.records[0][4] or 1
        ruleset = Ruleset.cached(rulesetId)
        Players.load() # we want to make sure we have the current definitions
        game = cls(Game.__getNames(qGame.records[0]), ruleset, gameid=gameid,
                client=client, wantedGame=qGame.records[0][5])
        qLastHand = Query("select hand,rotated from score where game=%d and hand="
            "(select max(hand) from score where game=%d)" % (gameid, gameid))
        if qLastHand.records:
            (game.handctr, game.rotated) = qLastHand.records[0]

        qScores = Query("select player, wind, balance, won, prevailing from score "
            "where game=%d and hand=%d" % (gameid, game.handctr))
        # default value. If the server saved a score entry but our client did not,
        # we get no record here. Should we try to fix this or exclude such a game from
        # the list of resumable games?
        prevailing = 'E'
        for record in qScores.records:
            playerid = record[0]
            wind = str(record[1])
            player = game.players.byId(playerid)
            if not player:
                logError(
                'game %d inconsistent: player %d missing in game table' % \
                    (gameid, playerid))
            else:
                player.getsPayment(record[2])
                player.wind = wind
            if record[3]:
                game.winner = player
            prevailing = record[4]
        game.roundsFinished = WINDS.index(prevailing)
        game.handctr += 1
        game.notRotated += 1
        game.maybeRotateWinds()
        game.sortPlayers()
        game.wall.decorate()
        return game

    def finished(self):
        """The game is over after minRounds completed rounds"""
        if self.ruleset:
            # while initialising Game, ruleset might be None
            return self.roundsFinished >= self.ruleset.minRounds

    def __payHand(self):
        """pay the scores"""
        # pylint: disable=R0912
        # too many branches
        winner = self.__winner
        if winner:
            winner.wonCount += 1
            guilty = winner.usedDangerousFrom
            if guilty:
                payAction = self.ruleset.findUniqueOption('payforall')
            if guilty and payAction:
                if Debug.dangerousGame:
                    self.debug('%s: winner %s. %s pays for all' % \
                                (self.handId(), winner, guilty))
                guilty.hand.usedRules.append((payAction, None))
                score = winner.handTotal
                score = score * 6 if winner.wind == 'E' else score * 4
                guilty.getsPayment(-score)
                winner.getsPayment(score)
                return

        for player1 in self.players:
            if Debug.explain:
                if not self.belongsToRobotPlayer():
                    self.debug('%s: %s' % (player1, player1.hand.string))
                    for line in player1.hand.explain():
                        self.debug('   %s' % (line))
            for player2 in self.players:
                if id(player1) != id(player2):
                    if player1.wind == 'E' or player2.wind == 'E':
                        efactor = 2
                    else:
                        efactor = 1
                    if player2 != winner:
                        player1.getsPayment(player1.handTotal * efactor)
                    if player1 != winner:
                        player1.getsPayment(-player2.handTotal * efactor)

    def lastMoves(self, only=None, without=None, withoutNotifications=False):
        """filters and yields the moves in reversed order"""
        for idx in range(len(self.moves)-1, -1, -1):
            move = self.moves[idx]
            if withoutNotifications and move.notifying:
                continue
            if only:
                if move.message in only:
                    yield move
            elif without:
                if move.message not in without:
                    yield move
            else:
                yield move

    def throwDices(self):
        """sets random living and kongBox
        sets divideAt: an index for the wall break"""
        if self.belongsToGameServer():
            self.wall.tiles.sort(key=tileKey)
            self.randomGenerator.shuffle(self.wall.tiles)
        breakWall = self.randomGenerator.randrange(4)
        sideLength = len(self.wall.tiles) // 4
        # use the sum of four dices to find the divide
        self.divideAt = breakWall * sideLength + \
            sum(self.randomGenerator.randrange(1, 7) for idx in range(4))
        if self.divideAt % 2 == 1:
            self.divideAt -= 1
        self.divideAt %= len(self.wall.tiles)

    def dangerousFor(self, forPlayer, tile):
        """returns a list of explaining texts if discarding tile
        would be Dangerous game for forPlayer. One text for each
        reason - there might be more than one"""
        if isinstance(tile, Tile):
            tile = tile.element
        tile = tile.lower()
        result = []
        for dang, txt in self.dangerousTiles:
            if tile in dang:
                result.append(txt)
        for player in forPlayer.others():
            for dang, txt in player.dangerousTiles:
                if tile in dang:
                    result.append(txt)
        return result

    def computeDangerous(self, playerChanged=None):
        """recompute gamewide dangerous tiles. Either for playerChanged or for all players"""
        self.dangerousTiles = list()
        if playerChanged:
            playerChanged.findDangerousTiles()
        else:
            for player in self.players:
                player.findDangerousTiles()
        self._endWallDangerous()

    def _endWallDangerous(self):
        """if end of living wall is reached, declare all invisible tiles as dangerous"""
        if len(self.wall.living) <=5:
            allTiles = [x for x in defaultdict.keys(elements.occurrence) if x[0] not in 'fy']
            # see http://www.logilab.org/ticket/23986
            invisibleTiles = set(x for x in allTiles if x not in self.visibleTiles)
            msg = m18n('Short living wall: Tile is invisible, hence dangerous')
            self.dangerousTiles = list(x for x in self.dangerousTiles if x[1] != msg)
            self.dangerousTiles.append((invisibleTiles, msg))

    def appendMove(self, player, command, kwargs):
        """append a Move object to self.moves"""
        self.moves.append(Move(player, command, kwargs))
Exemplo n.º 43
0
    def __init__(self, names, ruleset, gameid=None, wantedGame=None, shouldSave=True, client=None):
        """a new game instance. May be shown on a field, comes from database if gameid is set

        Game.lastDiscard is the tile last discarded by any player. It is reset to None when a
        player gets a tile from the living end of the wall or after he claimed a discard.
        """
        # pylint: disable=R0915
        # pylint we need more than 50 statements
        self.players = Players() # if we fail later on in init, at least we can still close the program
        self._client = None
        self.client = client
        self.rotated = 0
        self.notRotated = 0 # counts hands since last rotation
        self.ruleset = None
        self.roundsFinished = 0
        self._currentHandId = None
        self._prevHandId = None
        self.seed = 0
        self.randomGenerator = CountingRandom(self)
        if self.isScoringGame():
            self.wantedGame = str(wantedGame)
            self.seed = wantedGame
        else:
            self.wantedGame = wantedGame
            _ = int(wantedGame.split('/')[0]) if wantedGame else 0
            self.seed = _ or int(self.randomGenerator.random() * 10**9)
        self.shouldSave = shouldSave
        self.__setHandSeed()
        self.activePlayer = None
        self.__winner = None
        self.moves = []
        self.myself = None   # the player using this client instance for talking to the server
        self.gameid = gameid
        self.playOpen = False
        self.autoPlay = False
        self.handctr = 0
        self.roundHandCount = 0
        self.handDiscardCount = 0
        self.divideAt = None
        self.lastDiscard = None # always uppercase
        self.visibleTiles = IntDict()
        self.discardedTiles = IntDict(self.visibleTiles) # tile names are always lowercase
        self.dangerousTiles = list()
        self.csvTags = []
        self._setGameId()
        self.__useRuleset(ruleset)
        # shift rules taken from the OEMC 2005 rules
        # 2nd round: S and W shift, E and N shift
        self.shiftRules = 'SWEN,SE,WE'
        field = Internal.field
        if field:
            field.game = self
            field.startingGame = False
            field.showWall()  # sets self.wall
        else:
            self.wall = Wall(self)
        self.assignPlayers(names)
        if self.belongsToGameServer():
            self.__shufflePlayers()
        if not self.isScoringGame() and '/' in self.wantedGame:
            roundsFinished, rotations, notRotated = self.__scanGameOption(self.wantedGame)
            for _ in range(roundsFinished * 4 + rotations):
                self.rotateWinds()
            self.notRotated = notRotated
        if self.shouldSave:
            self.saveNewGame()
        if field:
            self.__initVisiblePlayers()
            field.updateGUI()
            self.wall.decorate()
Exemplo n.º 44
0
  def __init__(self, mapSize, display, character_size, theworld):
    # Initialize the sprite base class
    super(Map, self).__init__()
    
    # Set our image to a new surface, the size of the World Map
    self.display = display
    self.mapSize = mapSize
    logging.debug ("mapSize is {0}".format(self.mapSize))
    self.character_size = character_size
    self.image = Surface(self.mapSize)
    
    # Fill the image with a green colour (specified as R,G,B)
    self.image.fill(colors.BLACK)
    
    self.world = theworld
    self.walls = [] # List to hold the walls
    self.wallgrid = [[[] for x in range(self.world.cols)] for y in range(self.world.rows)]  # [y][x] grid of arrays of walls in that grid square
    self.arts = []  # list to hold the arts
    self.shapes = []  # list to hold the shapes
    
    
    
    #print "DEBUG: Map.__init__(): rendering world:\n{0}".format(theworld.to_s())
    self.grid_cellheight = grid_cellheight = int(mapSize[1] / theworld.rows)
    self.grid_cellwidth = grid_cellwidth = int(mapSize[0] / theworld.cols)
    logging.debug ("cell size is {0} wide x {1} high".format(grid_cellwidth, grid_cellheight))
    self.displayGridSize = (int(display.getDisplaySize()[0] / grid_cellwidth), int(display.getDisplaySize()[1] / grid_cellheight))
    

    # NEXT: render the world map from the 'world' class argument
    
    for worldObj in sorted(theworld.objects, key=lambda obj: pacdefs.RENDER_ORDER[obj.type]):
      pacglobal.checkAbort()
      logging.debug ("rendering the next world object: {0}".format(worldObj))
      if worldObj.type == pacdefs.TYPE_PATH:
        left = worldObj.left * grid_cellwidth
        top = worldObj.top * grid_cellheight
        if worldObj.direction_h:
          right = (worldObj.left+worldObj.length) * grid_cellwidth
          bottom = (worldObj.top+worldObj.width) * grid_cellheight
        else:
          right = (worldObj.left+worldObj.width) * grid_cellwidth
          bottom = (worldObj.top+worldObj.length) * grid_cellheight
        width = right - left
        height = bottom - top
        rect = (left, top, width, height)
        pygame.draw.rect(self.image, (111,111,111), rect)
        

      elif worldObj.type == pacdefs.TYPE_ART:
        # let the sprite manager draw it
        pass

      elif worldObj.type == pacdefs.TYPE_INTERSECTION:
        # draw a grey rectangle
        left = worldObj.left * grid_cellwidth
        top = worldObj.top * grid_cellheight
        width = worldObj.width * grid_cellwidth
        height = worldObj.height * grid_cellheight
        #right = (worldObj['left']+worldObj['width']) * grid_cellwidth
        #bottom = (worldObj['top']+worldObj['length']) * grid_cellheight
        #topLt = (left, top)
        #topRt = (right, top)
        #bottomLt = (left, bottom)
        #bottomRt = (right, bottom)
        rect = (left, top, width, height)
        logging.debug ("intersection rect at {0}".format(rect))
        pygame.draw.rect(self.image, (222,222,222), rect)

      elif worldObj.type == pacdefs.TYPE_FIELD:
        # draw a brown rectangle
        left = worldObj.left * grid_cellwidth
        top = worldObj.top * grid_cellheight
        width = worldObj.width * grid_cellwidth
        height = worldObj.height * grid_cellheight
        rect = (left, top, width, height)
        #print "DEBUG: field rect at {0}".format(rect)
        pygame.draw.rect(self.image, (160,82,45), rect)

      elif worldObj.type == pacdefs.TYPE_ROOM:
        # calculate corners & dimensions
        left = worldObj.left * grid_cellwidth
        top = worldObj.top * grid_cellheight
        width = worldObj.width * grid_cellwidth
        height = worldObj.height * grid_cellheight
        right = left + width
        bottom = top + height
        logging.debug ("rendering ROOM {4} [vert={0}..{1}, horiz={2}..{3}]".format(top,bottom,left,right,worldObj.id))
        # define interior & paint it
        rect = (left, top, width, height)
        #print "DEBUG: room rect at {0}".format(rect)
        pygame.draw.rect(self.image, colors.BLUE, rect)
        #DEBUG MODE: draw the objectId in the middle
        #font = pygame.font.Font(None, 20)
        #textBitmap = font.render(str(worldObj.id), True, colors.BLACK)
        #self.image.blit(textBitmap, [left+(width/2), top+(height/2)])
          
        # draw 4 walls
        roomWalls = {}  # dictionary of side to array of wallDefs (each wallDef is a tuple of 2 points, each one an (x,y) tuple)
        # draw walls that have doors in them
        #NOTE: assumes no more than one door per wall
        num_doors = len(worldObj.doors.keys())
        if num_doors > 1: logging.debug ("multiple doors! Room has {0} doors.".format(num_doors))
        for side,doorpos in worldObj.doors.items():
          #need to keep track of which sides have been processed, 
          #add the defaults later for walls with no doors
          doorx = doorpos[0]
          doory = doorpos[1]
          logging.debug ("rendering ROOM {0} has a door at {1} on side {2}".format(worldObj.id,doorpos,side))
          if side == pacdefs.SIDE_N:
            doorLeft = doorx * grid_cellwidth
            doorRight = (doorx+1) * grid_cellwidth
            # add 2 walls, on either side of the door
            roomWalls[side] = []
            roomWalls[side].append([(left,top), (doorLeft,top)])
            roomWalls[side].append([(doorRight,top), (right,top)])
        
          if side == pacdefs.SIDE_E:
            doorTop = doory * grid_cellheight
            doorBottom = (doory+1) * grid_cellheight
            logging.debug ("rendering ROOM door top/bottom is {0}/{1}".format(doorTop,doorBottom))
            # add 2 walls, on either side of the door
            roomWalls[side] = []
            roomWalls[side].append([(right,top), (right,doorTop)])
            roomWalls[side].append([(right,doorBottom), (right,bottom)])
        
          if side == pacdefs.SIDE_S:
            doorLeft = doorx * grid_cellwidth
            doorRight = (doorx+1) * grid_cellwidth
            # add 2 walls, on either side of the door
            roomWalls[side] = []
            roomWalls[side].append([(left,bottom), (doorLeft,bottom)])
            roomWalls[side].append([(doorRight,bottom), (right,bottom)])
        
          if side == pacdefs.SIDE_W:
            doorTop = doory * grid_cellheight
            doorBottom = (doory+1) * grid_cellheight
            # add 2 walls, on either side of the door
            roomWalls[side] = []
            roomWalls[side].append([(left,top), (left,doorTop)])
            roomWalls[side].append([(left,doorBottom), (left,bottom)])
        # end of for each door (creating walls w/ doors)
          
        # check all directions and add a default wall if none is defined
        for side in pacdefs.SIDES:
          if side not in roomWalls.keys() or len(roomWalls[side]) == 0:
            logging.debug ("drawing default wall for side {0}".format(side))
            roomWalls[side] = []
            if side == pacdefs.SIDE_N: roomWalls[side].append([(left,top), (right,top)])
            if side == pacdefs.SIDE_E: roomWalls[side].append([(right,top), (right, bottom)])
            if side == pacdefs.SIDE_S: roomWalls[side].append([(right,bottom), (left,bottom)])
            if side == pacdefs.SIDE_W: roomWalls[side].append([(left,bottom), (left,top)])

        for walls in roomWalls.values():
          for wallPoints in walls:
            # create the wall def
            newwall = Wall(self.mapSize, wallPoints[0], wallPoints[1])
            # add to walls array
            self.addWall( newwall )
            # draw on image
            newwall.draw(self.image)

    # draw a border, registering each line as a wall
    topLt = (0, 0)
    topRt = (self.mapSize[0], 0)
    botLt = (0, self.mapSize[1])
    botRt = (self.mapSize[0], self.mapSize[1])
    wallDefs = [
      (topLt, topRt),
      (topRt, botRt),
      (botRt, botLt),
      (botLt, topLt)
    ]
    for wallPoints in wallDefs:
      newwall = Wall(self.mapSize, wallPoints[0], wallPoints[1])  # create the wall def
      self.addWall( newwall )  # add to walls array and index
      newwall.draw(self.image)  # draw on image
    
    # Create the sprite rectangle from the image
    self.rect = self.image.get_rect()
    
    # holds current effects happening on the map
    self.effects = []  # array of Effects
Exemplo n.º 45
0
	def __init__(self, canvas, jenkins_url, views):
		Wall.__init__(self, canvas, jenkins_url)
		self.views = views
Exemplo n.º 46
0
from Tkinter import *
from wall import Wall
from table import Table

width = 384
height = 512

ball_radius = 16

root = Tk()

table = Table(width, height)
wall1 = Wall(0,height/5,width*0.6,height*0.8)
wall1.setBlockingPixels(ball_radius, table)

w = Canvas(root, width=width, height = height)

w.create_line(wall1.x1, wall1.y1, wall1.x2, wall1.y2, fill="#1010FF")

w.pack()

root.mainloop()
Exemplo n.º 47
0
 def __init__(self, left, top):
     Wall.__init__(self, left, top)
     self.image, self.rect = load_image('wall.png', None)
     self.image = pygame.transform.scale(self.image, cfg.obstacle_size )
     self.rect.size = cfg.obstacle_size
     self.rect.topleft = left, top
Exemplo n.º 48
0
	def __init__(self, canvas, jenkins_url, score_view, dbname):
		Wall.__init__(self, canvas, jenkins_url)

		self.funnycats = FunnyCats(self.jenkins, score_view, dbname)
		self.funnycats.init()
		self.users_score = None