Skip to main content
Engineering LibreTexts

4.27: Step 2 – Shuffling and Truncating the List of All Icons

  • Page ID
    14471
  •     random.shuffle(icons) # randomize the order of the icons list
        numIconsUsed = int(BOARDWIDTH * BOARDHEIGHT / 2) # calculate how many icons are needed
        icons = icons[:numIconsUsed] * 2 # make two of each
        random.shuffle(icons)
    

    But remember, there may be more possible combinations than spaces on the board. We need to calculate the number of spaces on the board by multiplying BOARDWIDTH by BOARDHEIGHT. Then we divide that number by 2 because we will have pairs of icons. On a board with 70 spaces, we’d only need 35 different icons, since there will be two of each icon. This number will be stored in numIconsUsed.

    Line 3 [141] uses list slicing to grab the first numIconsUsed number of icons in the list. (If you’ve forgotten how list slicing works, check out http://invpy.com/slicing.) This list has been shuffled on line 1 [139], so it won’t always be the same icons each game. Then this list is replicated by using the * operator so that there are two of each of the icons. This new doubled up list will overwrite the old list in the icons variable. Since the first half of this new list is identical to the last half, we call the shuffle() method again to randomly mix up the order of the icons.