[Tutor] An Introduction and a question (continuing)

Kent Johnson kent37 at tds.net
Sat Jun 10 13:08:04 CEST 2006


Michael Sullivan wrote:
> OK.  I've got it working this far.  Now I want the script to generate
> eight pieces, each with a random colour.  Here's my current code:
> 
> #!/usr/bin/env python
> 
> import random
> import time
> import math
> 
> class LinePuzzlePiece:
>    """This class defines a single playing piece for LinePuzzle"""
>    def __init__(self):
>       random.seed(time)

The above statement initializes the random number generator with the 
time *module*, not the current time. The time module never changes. So 
every time you need a random number your are initializing the generator 
with the same constant. That's why you always get the same number.

The docs for random.seed() say, "If x is omitted or None, current system 
time is used; current system time is also used to initialize the 
generator when the module is first imported." So you could omit the time 
argument to use the actual time; better is to omit the call completely 
and let the module init itself when you load it.

>       index = int(math.floor(random.uniform(0, 8)))
>       colorlist = ["red", "blue", "green", "yellow", "purple", "cyan",
> "orange", "white"]
>       self.color = colorlist[index]

random.choice() would be simpler here.

Kent

> 
>    def printcolor(self):
>       print self.color
> 
> piececount = 0
> mypiece = ["", "", "", "", "", "", "", "", ""]
> while (piececount < 9):
>    mypiece[piececount] = LinePuzzlePiece()
>    mypiece[piececount].printcolor()
>    piececount += 1
> 
> The problem is that while eight pieces are created and assigned a
> colour, the colour is always the same.  I need the colours of the pieces
> to be in a somewhat random order.  What am I doing wrong?
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 




More information about the Tutor mailing list