8.26: Generating Pieces with the getNewPiece() Function
- Page ID
- 14602
def getNewPiece(): # return a random new piece in a random rotation and color shape = random.choice(list(PIECES.keys())) newPiece = {'shape': shape, 'rotation': random.randint(0, len(PIECES[shape]) - 1), 'x': int(BOARDWIDTH / 2) - int(TEMPLATEWIDTH / 2), 'y': -2, # start it above the board (i.e. less than 0) 'color': random.randint(0, len(COLORS)-1)} return newPiece
The getNewPiece()
function generates a random piece that is positioned at the top of the board. First, to randomly choose the shape of the piece, we create a list of all the possible shapes by calling list(SHAPES.keys())
on line 3 [365]. The keys()
dictionary method returns a value of the data type "dict_keys", which must be converted to a list value with the list()
function before being passed to random.choice()
. This is because the random.choice()
function only accepts list values for its parameter. The random.choice()
function then randomly returns the value of an item from the list.
The piece data structures are simply a dictionary value with the keys 'shape'
, 'rotation'
, 'x'
, 'y'
, and 'color'
.
The value for the 'rotation'
key is a random integer between 0
to one less than however many possible rotations there are for that shape. The number of rotations for a shape can be found from the expression len(SHAPES[shape])
.
Notice that we don’t store the list of string values (like the ones store in the constants like S_SHAPE_TEMPLATE
) in each piece data structure to represent the boxes of each piece. Instead, we just store an index for the shape and rotation which refer to the PIECES
constant.
The 'x'
key’s value is always set to the middle of the board (also accounting for the width of the pieces themselves, which is found from our TEMPLATEWIDTH
constant). The 'y'
key’s value is always set to -2
to place it slightly above the board. (The top row of the board is row 0.)
Since the COLORS
constant is a tuple of the different colors, selecting a random number from 0
to the length of COLORS
(subtracting one) will give us a random index value for the piece’s color.
Once all of the values in the newPiece
dictionary are set, the getNewPiece()
function returns newPiece
.