vendredi 3 novembre 2017

How do I randomly select an item from a list

This is a Raspberry Pi Sense Hat project. I will post the code below but heres what it is supposed to do:

The sense hat is a grid of 8x8 LEDs (although i am using a digital emulator version onscreen) I have written a dice roller program, and so far I have the 6 numbers coded, and I have them flashing/playing through in an animation (to simulate a rolling effect) I now want to add a random.choice() to display one of the 6 numbers randomly at the end.

My problem: The method I know only really works for a very simple list, eg:

mylist = ['choiceA', 'choiceB', 'choiceC']

and using:

print(random.choice(mylist))

My version doesn't have the quotes because I dont want to print 'choiceA' as it is written in the list, choiceA is a variable containing more code.

I am going to post the whole program so you can see exactly what I am doing...apologies if its a bit lengthy for a question on here, and it may not be the most professional method of coding as I am learning the hard way...by myself

NOTE: the very last line of code is my idea of how I thought it would work. it is commented:

from sense_emu import SenseHat
import random
import time

sense = SenseHat()

b = [0,255,255]
w = [255,255,255]

# Number 1
imageA = [
w,w,w,w,w,w,w,w,
w,w,w,w,w,w,w,w,
w,w,w,w,w,w,w,w,
w,w,w,b,b,w,w,w,
w,w,w,b,b,w,w,w,
w,w,w,w,w,w,w,w,
w,w,w,w,w,w,w,w,
w,w,w,w,w,w,w,w
]

# Number 2
imageB = [
w,w,w,w,w,w,w,w,
w,w,w,w,w,w,w,w,
w,w,w,w,w,w,w,w,
w,b,b,w,w,b,b,w,
w,b,b,w,w,b,b,w,
w,w,w,w,w,w,w,w,
w,w,w,w,w,w,w,w,
w,w,w,w,w,w,w,w
]

# Number 3
imageC = [
w,w,w,w,w,w,w,w,
w,w,w,b,b,w,w,w,
w,w,w,b,b,w,w,w,
w,w,w,w,w,w,w,w,
w,w,w,w,w,w,w,w,
w,b,b,w,w,b,b,w,
w,b,b,w,w,b,b,w,
w,w,w,w,w,w,w,w
]

# Number 4
imageD = [
w,w,w,w,w,w,w,w,
w,b,b,w,w,b,b,w,
w,b,b,w,w,b,b,w,
w,w,w,w,w,w,w,w,
w,w,w,w,w,w,w,w,
w,b,b,w,w,b,b,w,
w,b,b,w,w,b,b,w,
w,w,w,w,w,w,w,w
]

# Number 5
imageE = [
b,b,w,w,w,w,b,b,
b,b,w,w,w,w,b,b,
w,w,w,w,w,w,w,w,
w,w,w,b,b,w,w,w,
w,w,w,b,b,w,w,w,
w,w,w,w,w,w,w,w,
b,b,w,w,w,w,b,b,
b,b,w,w,w,w,b,b
]

# Number 6
imageF = [
w,b,b,w,w,b,b,w,
w,b,b,w,w,b,b,w,
w,w,w,w,w,w,w,w,
w,b,b,w,w,b,b,w,
w,b,b,w,w,b,b,w,
w,w,w,w,w,w,w,w,
w,b,b,w,w,b,b,w,
w,b,b,w,w,b,b,w]

diceList = [imageA, imageB, imageC, imageD, imageE, imageF]

while True:
    for image in diceList:
        sense.set_pixels(image)
        time.sleep(0.1)

#sense.set_pixels(random.choice(dicelist))

If I un-comment the last line, the animation still keeps playing through, it doesn't display my random choice

NOTE: This code will run on the sensehat emulator website but the import id slightly different (Im running my emulator from Raspbian OS):

http://ift.tt/2aHBkpo

If you did want to try it out on the site,I am 99% certain you need to edit the first import to this:

from sense_hat import SenseHat




Aucun commentaire:

Enregistrer un commentaire