[Tutor] More or less final Chutes & Ladders

Keith Winston keithwins at gmail.com
Sat Jan 4 05:47:49 CET 2014


Here is what I think will be about the final version of C and L. I
rearranged it quite a bit (into 2 classes), fixed a bug or two, and
generally cleaned it up a bit. I haven't really polished it, but hopefully
it will be less difficult to read... which is to say, if anyone wants to go
through it AGAIN (at your leisure) I would appreciate comments on style,
etc.

Probably the biggest change is that I added a result() method to the
ChutesAndLadders class, that returns a list of the pertinent attributes of
each game (to be compiled into the array of games results that CandL_Array
class is all about).

Anyway, I sort of need to get off this since I need to do a lot more
reading on this language, though I may be back with early drafts of my
typing tutor before long... we'll see how that goes.

-- 
Keith

""" 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, [chutes], [ladders]]

"""

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 ChutesAndLadders:
    """Game class for Chutes & Ladders."""

    def __init__(self):
        self.reset()

    def reset(self):
        self.position = 0
        self.game_number = 0
        self.move_count = 0
        self.chutes_list = []
        self.ladders_list = []

    def results(self):
        return [self.game_number, self.move_count, 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)
        self.move_count += 1
        self.position += roll
        if self.position in chutes:
            self.chutes_list.append(self.position)
            self.position = chutes[self.position]
        elif self.position in ladders:
            self.ladders_list.append(self.position)
            self.position = ladders[self.position]
        elif self.position > 100:  # move doesn't count, have to land
exactly
            self.position -= roll
        return

#    @timer
    def play(self, game_no):
        """Single game"""

        self.reset()
        self.game_number = game_no
        while self.position < 100:
            self.move()
        return

class CandL_Array:
    """ Create & analyze an array of CandL games """

    candl_array = []
    def __init__(self):
        self.candl_array = []

#    @timer
    def populate(self, gamecount1):
        """populate candl_array with a set of games"""

        tgame = ChutesAndLadders()
        for i in range(gamecount1):
            tgame.play(i)
            self.candl_array.append(tgame.results())

    def print_stuff(self):
        self.print_gameset_stats(self.candl_array)
        self.print_candl_info(self.candl_array)

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

    def print_candl_info(self, 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. """

        self.chute_nums, self.ladder_nums = dict(chutes), dict(ladders)
        self.summarize_game("chutes", self.chute_nums, 2, garray)
        self.summarize_game("ladders", self.ladder_nums, 3, garray)

    def summarize_game(self, game_name, game_nums, game_index, garray):

        tgame_nums = game_nums
        for i in tgame_nums.keys(): game_nums[i] = 0

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

"""   def timing_report():

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

def run_CandL(gamecount):
    tarray = CandL_Array()
    tarray.populate(gamecount)
    tarray.print_stuff()

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


More information about the Tutor mailing list