Exemple #1
0
def test_save_load_global_window_size():
    x1 = Dice.roll()[0]
    y1 = Dice.roll()[0]
    prefs.save_global_window_size(window_name, x1, y1)
    x2, y2 = prefs.load_global_window_size(window_name)
    assert x2 == x1
    assert y2 == y1
Exemple #2
0
def test_save_load_global_window_size():
    x1 = Dice.roll()[0]
    y1 = Dice.roll()[0]
    prefs.save_global_window_size(window_name, x1, y1)
    x2, y2 = prefs.load_global_window_size(window_name)
    assert x2 == x1
    assert y2 == y1
Exemple #3
0
def test_save_load_window_position():
    x1 = Dice.roll()[0]
    y1 = Dice.roll()[0]
    prefs.save_window_position(playername, window_name, x1, y1)
    x2, y2 = prefs.load_window_position(playername, window_name)
    assert x2 == x1
    assert y2 == y1
Exemple #4
0
def test_save_load_window_position():
    x1 = Dice.roll()[0]
    y1 = Dice.roll()[0]
    prefs.save_window_position(playername, window_name, x1, y1)
    x2, y2 = prefs.load_window_position(playername, window_name)
    assert x2 == x1
    assert y2 == y1
Exemple #5
0
 def test_shuffle(self):
     s = set()
     lst = range(10)
     s.add(tuple(lst))
     num_shuffles = 100
     for unused in range(num_shuffles):
         Dice.shuffle(lst)
         s.add(tuple(lst))
     # We are highly unlikely to get a duplicate.  Though it's possible...
     assert len(s) == num_shuffles + 1
Exemple #6
0
 def test_shuffle(self):
     s = set()
     lst = range(10)
     s.add(tuple(lst))
     num_shuffles = 100
     for unused in range(num_shuffles):
         Dice.shuffle(lst)
         s.add(tuple(lst))
     # We are highly unlikely to get a duplicate.  Though it's possible...
     assert len(s) == num_shuffles + 1
Exemple #7
0
 def setup_method(self, method):
     self.trials = 600
     self.rolls = []
     self.bins = {}
     for unused in xrange(self.trials):
         num = Dice.roll()[0]
         self.rolls.append(num)
         self.bins[num] = self.bins.get(num, 0) + 1
Exemple #8
0
 def setup_method(self, method):
     self.trials = 600
     self.rolls = []
     self.bins = {}
     for unused in xrange(self.trials):
         num = Dice.roll()[0]
         self.rolls.append(num)
         self.bins[num] = self.bins.get(num, 0) + 1
Exemple #9
0
 def _breed_new_ai(self, cursor, old_player_ids):
     """Breed a new AI, from two weighted-random experienced parents."""
     query = """SELECT p.player_id, p.mu FROM player p
                WHERE p.class = 'CleverBot'"""
     cursor.execute(query)
     rows = cursor.fetchall()
     possible_parents = []
     for row in rows:
         mu = row["mu"]
         player_id = row["player_id"]
         if player_id in old_player_ids:
             possible_parents.append((mu, player_id))
     tup1 = Dice.weighted_random_choice(possible_parents)
     possible_parents.remove(tup1)
     tup2 = Dice.weighted_random_choice(possible_parents)
     player_id1 = tup1[1]
     info1 = self.get_player_info(player_id1)
     bp1 = BotParams.BotParams.fromstring(info1)
     player_id2 = tup2[1]
     info2 = self.get_player_info(player_id2)
     bp2 = BotParams.BotParams.fromstring(info2)
     bp3 = bp1.cross(bp2).mutate_random_field()
     bot = CleverBot.CleverBot("child", config.DEFAULT_AI_TIME_LIMIT, bp3)
     info = bot.player_info
     logging.info("player_info %s", info)
     query = """INSERT INTO player (class, info, mu, sigma)
                VALUES (?, ?, ?, ?)"""
     cursor.execute(query, ("CleverBot", info, DEFAULT_MU, DEFAULT_SIGMA))
     # And fetch the player_id.
     query = """SELECT player_id FROM player
                where class = ? AND info = ?"""
     cursor.execute(query, ("CleverBot", info))
     row = cursor.fetchone()
     player_id = row["player_id"]
     # And update the name.
     name = "ai%d" % player_id
     query = """UPDATE player SET name = ?
                WHERE player_id = ?"""
     cursor.execute(query, (name, player_id))
     logging.info("father %s %s", player_id1, bp1)
     logging.info("mother %s %s", player_id2, bp2)
     logging.info("baby %s %s %s", player_id, name, bp3)
     return player_id
Exemple #10
0
 def _breed_new_ai(self, cursor, old_player_ids):
     """Breed a new AI, from two weighted-random experienced parents."""
     query = """SELECT p.player_id, p.mu FROM player p
                WHERE p.class = 'CleverBot'"""
     cursor.execute(query)
     rows = cursor.fetchall()
     possible_parents = []
     for row in rows:
         mu = row["mu"]
         player_id = row["player_id"]
         if player_id in old_player_ids:
             possible_parents.append((mu, player_id))
     tup1 = Dice.weighted_random_choice(possible_parents)
     possible_parents.remove(tup1)
     tup2 = Dice.weighted_random_choice(possible_parents)
     player_id1 = tup1[1]
     info1 = self.get_player_info(player_id1)
     bp1 = BotParams.BotParams.fromstring(info1)
     player_id2 = tup2[1]
     info2 = self.get_player_info(player_id2)
     bp2 = BotParams.BotParams.fromstring(info2)
     bp3 = bp1.cross(bp2).mutate_random_field()
     bot = CleverBot.CleverBot("child", config.DEFAULT_AI_TIME_LIMIT, bp3)
     info = bot.player_info
     logging.info("player_info %s", info)
     query = """INSERT INTO player (class, info, mu, sigma)
                VALUES (?, ?, ?, ?)"""
     cursor.execute(query, ("CleverBot", info, DEFAULT_MU, DEFAULT_SIGMA))
     # And fetch the player_id.
     query = """SELECT player_id FROM player
                where class = ? AND info = ?"""
     cursor.execute(query, ("CleverBot", info))
     row = cursor.fetchone()
     player_id = row["player_id"]
     # And update the name.
     name = "ai%d" % player_id
     query = """UPDATE player SET name = ?
                WHERE player_id = ?"""
     cursor.execute(query, (name, player_id))
     logging.info("father %s %s", player_id1, bp1)
     logging.info("mother %s %s", player_id2, bp2)
     logging.info("baby %s %s %s", player_id, name, bp3)
     return player_id
Exemple #11
0
 def test_weighted_random_choice(self):
     lst = [
         (0.4, 1),
         (0.3, 2),
         (0.2, 3),
         (0.1, 4),
     ]
     # Can use a Counter when we require Python 2.7
     counter = defaultdict(int)
     for trial in xrange(1000):
         tup = Dice.weighted_random_choice(lst)
         print tup
         counter[tup[1]] += 1
     print counter
     assert sum(counter.itervalues()) == 1000
     assert counter[1] > counter[2] > counter[3] > counter[4]
Exemple #12
0
 def test_weighted_random_choice(self):
     lst = [
         (0.4, 1),
         (0.3, 2),
         (0.2, 3),
         (0.1, 4),
     ]
     # Can use a Counter when we require Python 2.7
     counter = defaultdict(int)
     for trial in xrange(1000):
         tup = Dice.weighted_random_choice(lst)
         print tup
         counter[tup[1]] += 1
     print counter
     assert sum(counter.itervalues()) == 1000
     assert counter[1] > counter[2] > counter[3] > counter[4]
Exemple #13
0
            gtkcolor = gtk.gdk.color_parse("white")
            chit_scale = int(round(self.scale / Die.CHIT_SCALE_FACTOR))
            for ii, roll in enumerate(rolls):
                die = Die.Die(roll, ii < hits, scale=chit_scale)
                die.event_box.modify_bg(gtk.STATE_NORMAL, gtkcolor)
                row, col = self.row_and_column(ii)
                self.table.attach(die.event_box, col, col + 1, row, row + 1)
            ii += 1
            while ii < self.rows * self.columns:
                row, col = self.row_and_column(ii)
                chit = Chit.Chit(None, None, scale=chit_scale, name="Nothing")
                chit.event_box.modify_bg(gtk.STATE_NORMAL, gtkcolor)
                self.table.attach(chit.event_box, col, col + 1, row, row + 1)
                ii += 1
            self.show_all()


if __name__ == "__main__":
    from slugathon.util import guiutils, Dice

    window = gtk.Window()
    battle_dice = BattleDice(80)
    battle_dice.connect("destroy", guiutils.exit)
    window.add(battle_dice)
    window.show_all()
    rolls = Dice.roll(numrolls=12)
    action = Action.Strike(None, None, None, None, None, None, None, None,
                           rolls, sum(1 for roll in rolls if roll >= 4), 1)
    battle_dice.update(None, action, None)
    gtk.main()
Exemple #14
0
    def get_weighted_random_player_id(self, excludes=(), highest_mu=False):
        """Return a player_id.  Exclude any player_ids in excludes.

        If there are fewer than GENERATION_SIZE AI player_id in the database,
        add a new AI (by mutating the default) and return its player_id.

        If highest_mu is not None, then return the eligible player_id with
        the highest mu.

        If there are fewer than GENERATION_SIZE AI player_ids in the database
        with sigma <= BREEDING_SIGMA_THRESHOLD, breed a new AI (by
        crossing two parent AIs with sigma <= BREEDING_SIGMA_THRESHOLD,
        chosen randomly weighted by mu), and return its player_id.

        Otherwise, choose an existing player_id randomly, weighted by low
        sigma, and return it.
        """
        with self.connection:
            cursor = self.connection.cursor()
            total_ai_count = 0

            query = """SELECT player_id, mu, sigma FROM player p
                       WHERE p.class='CleverBot'"""
            cursor.execute(query)
            rows = cursor.fetchall()
            young_player_ids = set()
            old_player_ids = set()
            for row in rows:
                player_id = row["player_id"]
                sigma = row["sigma"]
                if sigma <= BREEDING_SIGMA_THRESHOLD:
                    old_player_ids.add(player_id)
                else:
                    young_player_ids.add(player_id)
            young_ai_count = len(young_player_ids)
            old_ai_count = len(old_player_ids)
            total_ai_count = young_ai_count + old_ai_count

            if highest_mu:
                # Pick the eligible AI with the highest mu and return its
                # player_id.
                query = """SELECT player_id, mu FROM player
                           WHERE class = 'CleverBot'
                           ORDER BY mu DESC"""
                cursor.execute(query)
                rows = cursor.fetchall()
                for row in rows:
                    player_id = row["player_id"]
                    if player_id not in excludes:
                        logging.info("picked high-mu AI %s", player_id)
                        return player_id

            if young_ai_count < GENERATION_SIZE and old_ai_count >= 2:
                # Not enough young AIs, so breed one.
                return self._breed_new_ai(cursor, old_player_ids)

            else:
                candidates = []
                # Pick an existing young AI randomly, weighted by low sigma,
                # and return its player_id.
                query = """SELECT player_id, sigma FROM player
                           WHERE class = 'CleverBot'"""
                cursor.execute(query)
                rows = cursor.fetchall()
                for row in rows:
                    player_id = row["player_id"]
                    sigma = row["sigma"]
                    if (player_id in young_player_ids
                            and player_id not in excludes):
                        candidates.append((1.0 / sigma, player_id))
                if candidates:
                    tup = Dice.weighted_random_choice(candidates)
                    player_id = tup[1]
                    logging.info("picked random AI %s", player_id)
                    return player_id
                else:
                    # No eligible AIs available, so either breed or spawn
                    # a new one.
                    if total_ai_count < GENERATION_SIZE:
                        return self._spawn_new_ai(cursor)
                    elif old_ai_count >= 2:
                        return self._breed_new_ai(cursor, old_player_ids)
                    else:
                        return self._spawn_new_ai(cursor)
Exemple #15
0
        ctx.paint()
        with tempfile.NamedTemporaryFile(prefix="slugathon",
                                         suffix=".png",
                                         delete=False) as tmp_file:
            tmp_path = tmp_file.name
        self.surface.write_to_png(tmp_path)
        pixbuf = gtk.gdk.pixbuf_new_from_file(tmp_path)
        os.remove(tmp_path)
        self.event_box = gtk.EventBox()
        self.event_box.chit = self
        self.image = gtk.Image()
        self.image.set_from_pixbuf(pixbuf)
        self.event_box.add(self.image)
        self.location = None  # (x, y) of top left corner

    def show(self):
        self.event_box.show()
        self.image.show()


if __name__ == "__main__":
    from slugathon.util import Dice

    die = Die(Dice.roll()[0], scale=45)
    window = gtk.Window()
    window.connect("destroy", gtk.main_quit)
    window.add(die.event_box)
    window.show()
    die.show()
    gtk.main()
Exemple #16
0
 def _roll_movement(self):
     self.movement_roll = Dice.roll()[0]
     action = Action.RollMovement(self.game.name, self.name,
                                  self.movement_roll, self.mulligans_left)
     self.notify(action)
Exemple #17
0
        ctx.set_source_surface(input_surface)
        ctx.paint()
        with tempfile.NamedTemporaryFile(prefix="slugathon",
                                         suffix=".png",
                                         delete=False) as tmp_file:
            tmp_path = tmp_file.name
        self.surface.write_to_png(tmp_path)
        pixbuf = gtk.gdk.pixbuf_new_from_file(tmp_path)
        os.remove(tmp_path)
        self.event_box = gtk.EventBox()
        self.event_box.chit = self
        self.image = gtk.Image()
        self.image.set_from_pixbuf(pixbuf)
        self.event_box.add(self.image)
        self.location = None    # (x, y) of top left corner

    def show(self):
        self.event_box.show()
        self.image.show()

if __name__ == "__main__":
    from slugathon.util import Dice

    die = Die(Dice.roll()[0], scale=45)
    window = gtk.Window()
    window.connect("destroy", gtk.main_quit)
    window.add(die.event_box)
    window.show()
    die.show()
    gtk.main()
Exemple #18
0
    def get_weighted_random_player_id(self, excludes=(), highest_mu=False):
        """Return a player_id.  Exclude any player_ids in excludes.

        If there are fewer than GENERATION_SIZE AI player_id in the database,
        add a new AI (by mutating the default) and return its player_id.

        If highest_mu is not None, then return the eligible player_id with
        the highest mu.

        If there are fewer than GENERATION_SIZE AI player_ids in the database
        with sigma <= BREEDING_SIGMA_THRESHOLD, breed a new AI (by
        crossing two parent AIs with sigma <= BREEDING_SIGMA_THRESHOLD,
        chosen randomly weighted by mu), and return its player_id.

        Otherwise, choose an existing player_id randomly, weighted by low
        sigma, and return it.
        """
        with self.connection:
            cursor = self.connection.cursor()
            total_ai_count = 0

            query = """SELECT player_id, mu, sigma FROM player p
                       WHERE p.class='CleverBot'"""
            cursor.execute(query)
            rows = cursor.fetchall()
            young_player_ids = set()
            old_player_ids = set()
            for row in rows:
                player_id = row["player_id"]
                sigma = row["sigma"]
                if sigma <= BREEDING_SIGMA_THRESHOLD:
                    old_player_ids.add(player_id)
                else:
                    young_player_ids.add(player_id)
            young_ai_count = len(young_player_ids)
            old_ai_count = len(old_player_ids)
            total_ai_count = young_ai_count + old_ai_count

            if highest_mu:
                # Pick the eligible AI with the highest mu and return its
                # player_id.
                query = """SELECT player_id, mu FROM player
                           WHERE class = 'CleverBot'
                           ORDER BY mu DESC"""
                cursor.execute(query)
                rows = cursor.fetchall()
                for row in rows:
                    player_id = row["player_id"]
                    if player_id not in excludes:
                        logging.info("picked high-mu AI %s", player_id)
                        return player_id

            if young_ai_count < GENERATION_SIZE and old_ai_count >= 2:
                # Not enough young AIs, so breed one.
                return self._breed_new_ai(cursor, old_player_ids)

            else:
                candidates = []
                # Pick an existing young AI randomly, weighted by low sigma,
                # and return its player_id.
                query = """SELECT player_id, sigma FROM player
                           WHERE class = 'CleverBot'"""
                cursor.execute(query)
                rows = cursor.fetchall()
                for row in rows:
                    player_id = row["player_id"]
                    sigma = row["sigma"]
                    if player_id in young_player_ids and player_id not in excludes:
                        candidates.append((1.0 / sigma, player_id))
                if candidates:
                    tup = Dice.weighted_random_choice(candidates)
                    player_id = tup[1]
                    logging.info("picked random AI %s", player_id)
                    return player_id
                else:
                    # No eligible AIs available, so either breed or spawn
                    # a new one.
                    if total_ai_count < GENERATION_SIZE:
                        return self._spawn_new_ai(cursor)
                    elif old_ai_count >= 2:
                        return self._breed_new_ai(cursor, old_player_ids)
                    else:
                        return self._spawn_new_ai(cursor)
Exemple #19
0
 def _roll_movement(self):
     self.movement_roll = Dice.roll()[0]
     action = Action.RollMovement(self.game.name, self.name,
                                  self.movement_roll, self.mulligans_left)
     self.notify(action)
Exemple #20
0
            gtkcolor = gtk.gdk.color_parse("white")
            chit_scale = int(round(self.scale / Die.CHIT_SCALE_FACTOR))
            for ii, roll in enumerate(rolls):
                die = Die.Die(roll, ii < hits, scale=chit_scale)
                die.event_box.modify_bg(gtk.STATE_NORMAL, gtkcolor)
                row, col = self.row_and_column(ii)
                self.table.attach(die.event_box, col, col + 1, row, row + 1)
            ii += 1
            while ii < self.rows * self.columns:
                row, col = self.row_and_column(ii)
                chit = Chit.Chit(None, None, scale=chit_scale, name="Nothing")
                chit.event_box.modify_bg(gtk.STATE_NORMAL, gtkcolor)
                self.table.attach(chit.event_box, col, col + 1, row, row + 1)
                ii += 1
            self.show_all()


if __name__ == "__main__":
    from slugathon.util import guiutils, Dice

    window = gtk.Window()
    battle_dice = BattleDice(80)
    battle_dice.connect("destroy", guiutils.exit)
    window.add(battle_dice)
    window.show_all()
    rolls = Dice.roll(numrolls=12)
    action = Action.Strike(None, None, None, None, None, None, None, None,
                           rolls, sum(1 for roll in rolls if roll >= 4), 1)
    battle_dice.update(None, action, None)
    gtk.main()