[Tutor] What's in a name?

Keith Winston keithwins at gmail.com
Fri Jan 3 09:37:12 CET 2014


Below you will find the full current version of my Chutes or Snakes &
Ladders game. I tried to reorganize it into a more OOP structure, and I
think I started succeeding, and then something might have gone wrong. There
is also something somewhat seriously wrong with it: if I run it as
__main__, it works fine, but if I run it after I've loaded it (by
candl(100) at the prompt, for example), it is way off: something isn't
being reset, and I'm sure it'd be obvious to someone, and I'm going to look
back at it, but I can't figure it out yet. Anyway, thanks for all the help
so far, I'll probably add persistence, maybe trivial GUI, and definitely
more stats/analysis (well, almost definitely)...


""" Chutes & Ladders Simulation
    Simulates a number of games of Chutes & Ladders (Snakes & Ladders).
    Chutes & Ladders are separate dictionaries to allow tracking of
separate stats.

    Gathers the results into a list of lists of individual game results
    in the form (per game) of [game_no, moves, len(chutes), len(ladders),
[chutes], [ladders]]

    There is some info redundancy in the list with the len members:
[chutes] and [ladders]
    are lists of the actual chutes and ladders encountered in each game
(named by key)
"""

import random
from timer2 import timer
from statistics import * # from whence comes mean, variance, stdev


# Landing on a chute causes one to slide down to the corresponding value.
chutes = {16: 6, 47: 26, 49: 11, 56: 53, 62: 19, 64: 60, 87: 24, 93: 73,
95: 75, 98:78}

# Landing on a ladder (key) causes one to climb up to the corresponding
value.
ladders = {1: 38, 4: 14, 9: 31, 21: 42, 28: 84, 36: 44, 51: 67, 71: 91,
80:100}

class games:
    """Game class for Chutes & Ladders."""

    def __init__(self):
        self.reset()

    def reset(self):
        self.move_count = 0
        self.num_chutes = 0
        self.num_ladders = 0
        self.chutes_list = []
        self.ladders_list = []

#    @timer
    def move(self):
        """Single move, with chutes, ladders, & out of bounds.
        Primary action is to move self.position, but returns a list
        that consists of either the chute or ladder if landed on, if either
        """

        roll = random.randint(1,6)
        tchutes = 0
        tladders = 0
        self.move_count += 1
        self.position += roll
        if self.position in chutes:
            tchutes = self.position
            self.position = chutes[self.position]
            self.num_chutes += 1
        elif self.position in ladders:
            tladders = self.position
            self.position = ladders[self.position]
            self.num_ladders += 1
        elif self.position > 100:  # move doesn't count, have to land
exactly
            self.position -= roll
        return [tchutes, tladders]  # only one will be != 0

#    @timer
    def play_game(self, step):
        """Single game"""

        self.position = 0
        self.reset()
        while self.position < 100:
            gamecandl = self.move()  # [chute, ladder] or [0, 0]
            if gamecandl[0] != 0: # populate chutes list
                self.chutes_list.append(gamecandl[0])
            if gamecandl[1] != 0:  # populate ladders list
                self.ladders_list.append(gamecandl[1])
        return [step, self.move_count, self.num_chutes, self.num_ladders,
self.chutes_list, self.ladders_list]

#    @timer
    def play_gameset(self, gamecount1):
        """A set of games, returning associated stats array"""

        return [self.play_game(i) for i in range(gamecount1)]


def candl(gamecount2):
    """ play a mess of games, return the results array """

    gname = games()
    game_array = gname.play_gameset(gamecount2)
    print_gameset_stats(game_array)
    print_candl_info(game_array)
#    print(game_array)

def print_gameset_stats(garray):

    print("Total number of games: ", len(garray))
    print("   Moves        Chutes        Ladders")
    for func in [mean, max, min, variance, stdev]:
            print("{moves:9.2f} {chutes:12.2f} {ladders:13.2f}
{stype}".format(
                moves=func(tgset[1] for tgset in garray),
                chutes=func(tgset[2] for tgset in garray),
                ladders=func(tgset[3] for tgset in garray),
                stype=func.__name__
                ))

def timing_report():

    print("game.total, count = ", p1.game.total, p1.game.count)
    print("move.total, count = ", p1.move.total, p1.move.count)

def print_candl_info(garray):
    """ Create two dictionaries with the same keys as chutes & ladders,
    but with the total number of times each c or l is traversed (in the
entire gameset)
    as the values. Then, print them. """

    chute_nums, ladder_nums = chutes, ladders
    summarize_game("chutes", chutes, 4, garray)
    summarize_game("ladders", ladders, 5, garray)

def summarize_game(game_name, game_nums, game_index, garray):
    for i in game_nums.keys(): game_nums[i] = 0

    for corl in game_nums:
        for game in garray:
            if corl in game[game_index]:
                game_nums[corl] += 1
    print("total ", game_name, "= ", sum(game_nums.values()))


if __name__ == "__main__":
    candl(100)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20140103/5321a602/attachment-0001.html>


More information about the Tutor mailing list