简体   繁体   中英

How do you implement a random number into python

so i am making a basic game in python (on a raspberry pi) and for ax coordinate i need it to be random and it wont work when i use random.randint() and therefore i dont know what to do:

as said i need x to be a random number and y to stay as -2

def getNewPiece():
    shape = random.choice(list(PIECES.keys()))
    newPiece = {'shape': shape,
                'rotation': random.randint(0, len(PIECES[shape]) - 1),
                'x': random.randint(),
                'y': -2 , 
                'color': random.randint(0, len(COLORS)-1)}
    return newPiece

You actually need to pass in your range from which the random int needs to be generated.

random.randint(1,10)

where 1 and 10 are included in the random picking. Therefore, the method above will return any integer between 1 & 10 (inclusive). For a different range, just specify different start and end parameters.

Documentation: random.randint

You can also use randrange ,

Syntax is random.randrange([start], stop[, step])

Example ,

>>> from random import randrange
>>> print randrange(10)
5

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM