pythonpython-2.x

Need help simplifying - generating random items from a pre-set list


I know there's an easier way to do this. It is supposed to be a "Simon" like game where you generate 5 random colors from the list and the user enters the colors. Each turn it should keep the 1st color the same and add a new random color, which is where my trouble is coming in.

import random
# Create a list of colors.
colors = ['Yellow', 'Green', 'Red', 'Blue']

# Generate random colors from the list. 
color1 = random.choice(colors)
color2 = random.choice(colors)
color3 = random.choice(colors)
color4 = random.choice(colors)
color5 = random.choice(colors)

 
# Simon displays the 5 color choices, adding 1 each turn. 
   
print "Simon says: ", color1
raw_input ("What did Simon say? ")

print "Simon says: ", color1, color2
raw_input ("What did Simon say? ")

print "Simon says: ", color1, color2, color3
raw_input ("What did Simon say? ")

print "Simon says: ", color1, color2, color3, color4
raw_input ("What did Simon say? ")

print "Simon says: ", color1, color2, color3, color4, color5
raw_input ("What did Simon say? ")

My first try looked like this but was not working either:

# Create a list of colors.
colors = ['Yellow', 'Green', 'Red', 'Blue']


# Display the color list, adding one random color each turn. Prompt the
# user to enter the colors after each is added.
for i in range (5):
    import random
    color = random.choice(colors)
      
    print "Simon says: " ,color

    raw_input ("What did Simon say? ")
    colors.append(colors)
    print "Simon says: " , (color)

Solution

  • You are almost there. Your issue is to try and modify your original 4-color list. Just initialize a new, empty list for the gameplay:

    # Create a list of colors.
    colors = ['Yellow', 'Green', 'Red', 'Blue']
    
    # Display the color list, adding one random color each turn. Prompt the
    # user to enter the colors after each is added.
    chosen_colors = []
    for i in range (5):
        import random
        color = random.choice(colors)
        chosen_colors.append(color)
        print "Simon says: " ,chosen_colors
        raw_input ("What did Simon say? ")
    

    Now you should find a way to check if the answer is correct or not.