Example #1
0
    def runOne(self, entry):
        resultsAccumulator = yacpdb.indexer.predicate.AnalysisResultAccumulator(
            self.pstor)
        for k in ["solution", "stipulation", "algebraic"]:
            if k not in entry:
                raise Exception("No %s" % k)

        print(entry.get("id", "0"), len(entry['solution']))
        visitor = validate.DummyVisitor()
        try:
            solution = parser.parse(entry["solution"], debug=0)
            board = model.Board()
            board.fromAlgebraic(entry["algebraic"])
            board.stm = board.getStmByStipulation(entry["stipulation"])
            solution.traverse(board, visitor)  # assign origins
            solution.size = visitor.count
        except Exception:
            raise RuntimeError("invalid solution")

        if solution.size > 140:
            raise RuntimeError("solution too long")

        self.analyze(entry, solution, board, resultsAccumulator)

        return resultsAccumulator
Example #2
0
 def validate(self, key, validator):
     e = tests.unit.data.problems[key]
     solution = p2w.parser.parser.parse(e["solution"], debug=0, lexer=p2w.lexer.lexer)
     b = model.Board()
     b.fromAlgebraic(e["algebraic"])
     b.stm = b.getStmByStipulation(e["stipulation"])
     solution.traverse(b, validator)
Example #3
0
 def prepare(self, e):
     solution = p2w.parser.parser.parse(e["solution"], debug=0, lexer=p2w.lexer.lexer)
     b = model.Board()
     b.fromAlgebraic(e["algebraic"])
     b.stm = b.getStmByStipulation(e["stipulation"])
     solution.traverse(b, validate.DummyVisitor()) # assign origins
     return solution, b
Example #4
0
def main():
    # Set up model component
    grid = model.Board()
    # Set up view component
    game_view = view.GameView(600, 600)
    grid_view = view.GridView(game_view, len(grid.tiles))
    grid.add_listener(grid_view)
    # Handle control component responsibility here
    commands = keypress.Command(game_view)

    grid.place_tile(value=2)

    # Game continues until there is no empty
    # space for a tile
    while grid.has_empty():
        grid.place_tile()
        cmd = commands.next()
        if cmd == keypress.LEFT:
            grid.left()
        elif cmd == keypress.RIGHT:
            grid.right()
        elif cmd == keypress.UP:
            grid.up()
        elif cmd == keypress.DOWN:
            grid.down()
        elif cmd == keypress.CLOSE:
            # Ended game by closing window
            print(f"Your score: {grid.score()}")
            sys.exit(0)
        else: 
            assert cmd == keypress.UNMAPPED

    game_view.lose(grid.score())
Example #5
0
 def rightBottom(self, e):
     story = []
     if e is None:
         return story
     parts = []
     if 'solution' in e:
         story.append(
             reportlab.platypus.Preformatted(
                 wrapParagraph(
                     e['solution'],
                     50),
                 self.style_pre))
     if 'keywords' in e:
         parts.append('<i>' + ', '.join(e['keywords']) + '</i>')
     if 'comments' in e:
         parts.append('<br/>'.join(e['comments']))
     story.append(reportlab.platypus.Paragraph(
         '<font face="%s" size=%d>%s</font>' % (
             FONT_FAMILY,
             FONT_SIZE['rightpane'],
             '<br/><br/>'.join(parts)
         ), self.style
     ))
     if 'algebraic' in e:
         b = model.Board()
         b.fromAlgebraic(e['algebraic'])
         story.append(self.fenLine(b))
     return story
Example #6
0
def validate(entry, propagate_exceptions=True):

    r = {'success': False, "errors": []}

    if not "solution" in entry or entry["solution"].strip() == "":
        r["errors"].append("No solution")
        return r

    if not "algebraic" in entry:
        r["errors"].append("No position")
        return r

    if not "stipulation" in entry:
        r["errors"].append("No stipulation")
        return r

    if not validateStipulation(entry["stipulation"], r):
        return r

    try:
        solution = parser.parse(entry["solution"], debug=0)
        b = model.Board()
        b.fromAlgebraic(entry["algebraic"])
        b.stm = b.getStmByStipulation(entry["stipulation"])
        solution.traverse(b, SemanticValidationVisitor())
    except Exception as ex:
        if propagate_exceptions:
            raise ex
        r["errors"].append(str(ex))
        return r

    return {'success': True, 'orthodox': not model.hasFairyElements(entry)}
Example #7
0
 def test_bounds_odd_shape(self):
     """Non-square board to make sure we're using row and column
     correctly.
     """
     board = model.Board(rows=2,cols=4)
     self.assertTrue(board.in_bounds(Vec(0,0)))
     self.assertTrue(board.in_bounds(Vec(1,3)))
     self.assertFalse(board.in_bounds(Vec(3,1)))
Example #8
0
 def test_slide_already_at_edge(self):
     """A tile already at the edge can't slide farther that way"""
     board = model.Board()
     board.from_list([[0, 0, 0, 0], [0, 0, 0, 4], [0, 0, 0, 0],
                      [0, 0, 0, 0]])
     board.slide(Vec(1, 3), Vec(0, 1))  # To the right
     self.assertEqual(
         board.to_list(),
         [[0, 0, 0, 0], [0, 0, 0, 4], [0, 0, 0, 0], [0, 0, 0, 0]])
Example #9
0
 def test_CanParseOrthodox(self):
     e = tests.unit.data.problems['orthodox']
     solution = p2w.parser.parser.parse(e["solution"],
                                        debug=0,
                                        lexer=p2w.lexer.lexer)
     b = model.Board()
     b.fromAlgebraic(e["algebraic"])
     b.stm = b.getStmByStipulation(e["stipulation"])
     solution.traverse(b, validate.DummyVisitor())  # to assign origins
Example #10
0
 def test_move_merge_up(self):
     board = model.Board()
     board.from_list([[4, 0, 2, 2], [2, 0, 2, 2], [2, 2, 4, 0],
                      [2, 2, 2, 2]])
     board.up()
     expected = [[4, 4, 8, 4], [4, 0, 2, 2], [2, 0, 0, 0], [0, 0, 0, 0]]
     actual = board.to_list()
     # board_diff(actual, expected)
     self.assertEqual(actual, expected)
Example #11
0
 def test_move_all_up(self):
     """Simple slide with no merges"""
     board = model.Board()
     board.from_list([[2, 0, 0, 0], [0, 2, 0, 0], [0, 0, 2, 0],
                      [0, 0, 0, 2]])
     board.up()
     self.assertEqual(
         board.to_list(),
         [[2, 2, 2, 2], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]])
Example #12
0
 def test_slide_merge(self):
     """Equal tiles merge when they meet"""
     board = model.Board()
     board.from_list([[2, 0, 0, 0], [0, 2, 2, 4], [0, 0, 2, 0],
                      [0, 0, 0, 2]])
     board.slide(Vec(1, 1), Vec(0, 1))
     self.assertEqual(
         board.to_list(),
         [[2, 0, 0, 0], [0, 0, 4, 4], [0, 0, 2, 0], [0, 0, 0, 2]])
Example #13
0
 def test_slide_into_obstacle(self):
     """A tile should stop when it reaches another tile"""
     board = model.Board()
     board.from_list([[2, 0, 0, 0], [0, 2, 4, 0], [0, 0, 2, 0],
                      [0, 0, 0, 2]])
     board.slide(Vec(1, 1), Vec(0, 1))  # Space 1,0 is empty
     self.assertEqual(
         board.to_list(),
         [[2, 0, 0, 0], [0, 2, 4, 0], [0, 0, 2, 0], [0, 0, 0, 2]])
Example #14
0
 def test_empty_wont_slide(self):
     """Sliding an empty position has no effect"""
     board = model.Board()
     board.from_list([[2, 0, 0, 0], [0, 2, 0, 0], [0, 0, 2, 0],
                      [0, 0, 0, 2]])
     board.slide(Vec(1, 0), Vec(0, 1))  # Space 1,0 is empty
     self.assertEqual(
         board.to_list(),
         [[2, 0, 0, 0], [0, 2, 0, 0], [0, 0, 2, 0], [0, 0, 0, 2]])
Example #15
0
 def TestLose(self):
     board = model.Board()
     board.from_list([[4, 32, 2, 32],
                      [32, 4, 32, 4],
                      [4, 32, 4, 32],
                      [32, 4, 32, 4]])
     actual = board.to_list
     expected = board.score()
     self.assertEqual(actual, expected)
Example #16
0
 def test_slide_right_to_edge(self):
     """A tile should stop just when it reaches the edge"""
     board = model.Board()
     board.from_list([[0, 0, 0, 0], [0, 0, 2, 0], [0, 0, 0, 0],
                      [0, 0, 0, 0]])
     board.slide(Vec(1, 2), Vec(0, 1))  # Slide the 2 right
     self.assertEqual(
         board.to_list(),
         [[0, 0, 0, 0], [0, 0, 0, 2], [0, 0, 0, 0], [0, 0, 0, 0]])
Example #17
0
 def test_from_to(self):
     """to_list and from_list should be inverse"""
     board = model.Board()
     board.place_tile()
     board.place_tile(value=32)
     board.place_tile()
     as_list = board.to_list()
     board.from_list(as_list)
     again = board.to_list()
     self.assertEqual(as_list, again)
Example #18
0
 def test_bounds_default_shape(self):
     board = model.Board()
     self.assertTrue(board.in_bounds(Vec(0,0)))
     self.assertTrue(board.in_bounds(Vec(3,3)))
     self.assertTrue(board.in_bounds(Vec(1,2)))
     self.assertTrue(board.in_bounds(Vec(0,3)))
     self.assertFalse(board.in_bounds(Vec(-1,0))) # off the top
     self.assertFalse(board.in_bounds(Vec(1,-1))) # off the left
     self.assertFalse(board.in_bounds(Vec(4,3)))  # off the bottom
     self.assertFalse(board.in_bounds(Vec(1,4)))  # off the right
Example #19
0
 def test_move_merge_right(self):
     board = model.Board()
     board.from_list([[2, 0, 2, 0],
                      [2, 2, 2, 0],
                      [2, 2, 0, 0],
                      [2, 2, 2, 2]])
     board.right()
     self.assertEqual(board.to_list(),
                       [[0, 0, 0, 4],
                        [0, 0, 2, 4],  # Must work from right to left
                        [0, 0, 0, 4],
                        [0, 0, 4, 4]]) # Tile stops sliding when it merges
Example #20
0
    def instantiateModel(self, gameKey, owner):
        board = model.Board()
        board.gameKey = gameKey
        board.dateTimeCreated = datetime.datetime.now()
        board.resources = self.resources
        board.hexProduces = self.hexProduces
        board.playerColors = self.colors
        board.owner = owner
        board.gamePhase = 0
        board.minimumPlayers = self.minimumPlayers
        board.dice = self.dice

        board.put()

        for d in self.developments:
            dt = model.DevelopmentType(parent=board,
                                       location=d["location"],
                                       name=d["name"],
                                       playerStart=d["playerStart"])
            dt.put()
            for (r, a) in d["cost"].items():
                dtc = model.DevelopmentTypeCost(parent=dt,
                                                resource=r,
                                                amount=a)
                dtc.put()

        for i in range(len(self.gamePhases)):
            gp_desc = self.gamePhases[i][0]
            gp = model.GamePhase(parent=board, phase=gp_desc, order=i)
            gp.put()
            for j in range(len(self.gamePhases[i][1])):
                tp_desc = self.gamePhases[i][1][j]
                tp = model.TurnPhase(parent=gp, phase=tp_desc, order=j)
                tp.put()

        j = 0
        for i in range(len(self.boardTemplate["hexes"])):
            h = self.boardTemplate["hexes"][i]
            hex = model.Hex(parent=board,
                            x=h["x"],
                            y=h["y"],
                            type=self.hexTypes[i])

            if self.hexTypes[i] == "desert":
                hex.value = 0
            else:
                hex.value = self.hexValues[j]
                j += 1

            hex.put()

        self.__createVertexAndEdgesFromHexesModel(board)
        return board
Example #21
0
def create_players_model(player_names, view, controller):

    if len(player_names) > 5 or len(player_names) < 3:
        raise ValueError('Wrong number of players.')

    players = []
    for p_name in player_names:
        p = mod.Player(p_name, view, controller)

        # Add board empty board
        p.board = mod.Board()
        players.append(p)

    return players
Example #22
0
def readCvv(fileName, encoding):
    h = open(unicode(fileName), 'r')
    contents = "\n".join([x.strip() for x in h.readlines()])
    contents = unicode(contents.decode(encoding))
    h.close()
    entries = []
    for chunk in contents.split("\n\n"):
        lines = chunk.strip().split("\n")
        if len(lines) < 2:
            continue
        # removing Dg[x]=new Array line
        lines = lines[1:]
        # removing trailing semicolon
        lines[-1] = lines[-1][:-1]
        # changing brackets to square brackets:
        chunk = ''.join(lines)
        chunk = '[' + chunk[1:-1] + ']'
        e = yaml.load(chunk)

        # creating yacpdb-like entry
        entry = {}
        board = model.Board()
        imitators = []
        for i in xrange(64):
            code = e[i >> 3][i % 8]
            if code:
                if code == 20:
                    imitators.append(model.idxToAlgebraic(i))
                else:
                    board.add(fancyCodeToPiece(code), i)
        entry['algebraic'] = board.toAlgebraic()
        if e[8][0] != '':
            entry['authors'] = [e[8][0]]
        if e[9][0] != '':
            entry['source'] = e[9][0]
        if e[10][0] != '':
            entry['solution'] = "\n".join(e[10][0].split('\\n'))
        extra = e[11][0].split('\\n')
        stip_cond = extra[0].split(' ')
        entry['stipulation'] = stip_cond[0]
        entry['options'] = []
        if len(imitators):
            entry['options'].append('Imitator ' + ''.join(imitators))
        if len(stip_cond) > 1:
            entry['options'].extend(parseConditions(stip_cond[1:]))
        if len(extra) > 1:
            entry['twins'] = parseTwins(extra[1:])

        entries.append(entry)
    return entries
Example #23
0
 def __init__(self):
     """
     Setup objects and initial state. Creates a Clock, Board, View, PhysicsEngine, and InputManager
     """
     pygame.init()
     self.clock = pygame.time.Clock()
     self.board = model.Board(
         settings.num_rows + 2,
         settings.num_cols)  # adding the two hidden rows
     self.view = view.View(self.board, settings.block_width,
                           settings.hidden_row_fraction)
     self.input_manager = InputManager()
     self.engine = engine.PhysicsEngine(self.board, self.input_manager)
     self.game_state = GameState.initialized
Example #24
0
def multiplayer():
    board = model.Board(seed=BOARD_SEED)
    board.populate(DENSITY, CEILING)
    seed = JAR_SEED or random.getrandbits(32)
    players = []
    for i in range(PLAYERS):
        b = board.copy()
        j = model.Jar(1, seed)
        e = engine.Engine()
        if i == 0 and HUMAN:
            e = None
        player = model.Player(b, j, e)
        players.append(player)
    return players
Example #25
0
def create_board(state, tiles, buildings, colonists):

    board = mod.Board()
    for (tile_type, occupancy) in state['island_spaces']:
        tile_to_add = next(tiles[tile_type])
        if occupancy == 1:
            tile_to_add.occupy(next(colonists))
        board.set_island_tile(tile_to_add)

    for (building_type, b_prop) in state['city_spaces']:
        building_to_add = next(buildings[building_type])
        building_to_add.add_colonists(
            [next(colonists) for i in range(b_prop['occupancy'])])
        board.set_city_tile(building_to_add)
    return board
Example #26
0
 def to_yacpdb_struct(self):
     r = {'options': [], 'conditions': []}
     if self.info['author']:
         r['authors'] = self.info['author'].split(';')
     if self.info['source']:
         r['source'] = {'name': self.info['source']}
     if self.info['distinction']:
         d = model.Distinction()
         parts = self.info['distinction'].split('°')
         d.lo = model.myint(parts[0])
         if len(parts) > 1:
             d.hi = model.myint(parts[1])
         tail = ('°'.join(parts[1:])).lower()
         if len(parts) == 1:
             tail = self.info['distinction'].lower()
         if 'special' in tail:
             d.special = True
         if 'priz' in tail or 'prix' in tail:
             d.name = 'Prize'
         if 'hono' in tail or 'menti' in tail or 'hm' in tail or 'dicser' in tail:
             d.name = 'HM'
         if 'com' in tail or 'cm' in tail or 'c.' in tail or 'elisme' in tail:
             d.name = 'Comm.'
         if 'place' in tail:
             d.name = 'Place'
         distinction = "%s, (%s)" % (str(d), self.info['distinction'])
         r['award'] = {
             'tourney': r.get('source', {}).get('name', ''),
             'distinction': distinction
         }
     if len(self.comments):
         r['comments'] = self.comments
     if self.is_maximummer:
         r['conditions'].append('BlackMaximummer')
     r['stipulation'] = self.stipulation
     b = model.Board()
     b.fromFen(self.fen)
     r['algebraic'] = b.toAlgebraic()
     if self.is_duplex:
         r['options'].append('Duplex')
     if len(self.twins):
         r['twins'] = {}
         offset = [1, 0][self.is_zero]
         for i, twin in enumerate(self.twins):
             r['twins'][chr(ord('a') + i + offset)] = twin
     return copy.deepcopy(r)
Example #27
0
def run(weights, rain=False):
    players = []
    board = model.Board()
    board.populate(0.25, 6)
    seed = random.getrandbits(32)
    for w in weights:
        b = board.copy()
        j = model.Jar(1, seed)
        e = engine.Engine(w)
        p = model.Player(b, j, e)
        players.append(p)
    winners = []
    losers = []
    done = set()
    while True:
        germs = [p.board.germ_count for p in players]
        print germs
        #print group([p.display() for p in players[:10]])
        if len(done) == len(players):
            break
        for p in players:
            if p in done:
                continue
            if p.state == model.OVER or p.jar.count > 250:
                losers.append(p)
                done.add(p)
            if p.state == model.WIN:
                winners.append(p)
                done.add(p)
        for p in players:
            if p in done:
                continue
            c = p.update()
            if rain and len(c) > 1:
                for q in players:
                    if p == q:
                        continue
                    q.rain.extend(c)
    losers.reverse()
    rank = winners + losers
    rank = [players.index(p) for p in rank]
    print 'Rank:', rank
    return rank
Example #28
0
def validate(entry, propagate_exceptions=True):

    try:
        jsonschema.validate(instance=entry, schema=json_schema)
        validateStipulation(entry["stipulation"])
        solution = parser.parse(entry["solution"], debug=0)
        b = model.Board()
        b.fromAlgebraic(entry["algebraic"])
        b.stm = b.getStmByStipulation(entry["stipulation"])
        solution.traverse(b, SemanticValidationVisitor())
    except (jsonschema.ValidationError, StipulationError) as ex:
        if propagate_exceptions:
            raise ex
        return {'success': False, "errors": [ex.message]}
    except Exception as ex:
        if propagate_exceptions:
            raise ex
        return {'success': False, "errors": [str(ex)]}

    return {'success': True, 'orthodox': not model.hasFairyElements(entry)}
Example #29
0
 def leftBottom(self, e):
     story = []
     if e is None:
         return story
     b = model.Board()
     if e.has_key('algebraic'):
         b.fromAlgebraic(e['algebraic'])
     x = unicode(self.board2Html(b).decode("ISO-8859-1"))
     story.append(BorderedParagraph('<para autoLeading="max">'+x+'</para>', self.style))
     s_left = ''
     if e.has_key('stipulation'):
         s_left = e['stipulation']
     story.append(self.subscript(s_left, b.getPiecesCount()))
     story.append(reportlab.platypus.Paragraph(\
         '<font face="%s" size=%d>%s</font>' % (
             FONT_FAMILY,
             FONT_SIZE['footer'],
             ExportDocument.solver(e, self.Lang) + '<br/>' + ExportDocument.legend(b)
             ), self.style
         ))
     return story
Example #30
0
 def leftBottom(self, e):
     story = []
     if e is None:
         return story
     b = model.Board()
     if 'algebraic' in e:
         b.fromAlgebraic(e['algebraic'])
     story.append(self.getBoardTable(b))
     s_left = ''
     if 'stipulation' in e:
         s_left = e['stipulation']
     s_middle = reportlab.platypus.Paragraph(
         '<font face="%s" size=%d>%s</font>' %
         (FONT_FAMILY,
          FONT_SIZE['footer'],
          ExportDocument.solver(
              e,
              self.Lang) +
          '<br/>' +
          ExportDocument.legend(b)),
         self.style_center)
     story.append(self.subscript(s_left, s_middle, b.getPiecesCount()))
     return story