# 13. Random Numbers¶ Now if our games do the same thing each time the game runs, that’s not very interesting. At the end of this chapter we’ll introduce random numbers. That is, we can have the computer roll the dice to change up the game each time we run it. Random numbers are heavily used in computer science for programs that involve games or simulations.

## 13.1. The `randrange` Function¶

By default, Python does not know how to make random numbers. It is necessary to have Python import a code library that can create random numbers. So to use random numbers, the first thing that should appear at the top of the program is an import statement:

```import random
```

Just like with pygame, it is important not to create a file with the same name as what is being imported. Creating a file called random.py will cause Python to start importing that file instead of the system library that creates random numbers.

After this, random numbers can be created with the `randrange` function. For example, this code creates random numbers from 0 to 49. By default the lower bound is 0.

Random number from 0 to 49
```my_number = random.randrange(50)
```

The next code example generates random numbers from 100 to 200. Just like the range function the second parameter specifies an upper-bound that is not inclusive. Therefore if you want random numbers up to and including 200, specify 201.

Random number from 100 to 200
```my_number = random.randrange(100, 201)
```

## 13.2. Random Chance¶

Often in games there is a random chance of something happening. How do we program this? It isn’t too hard. Here’s an example where we have a 1 in 5 chance of meeting a dragon:

Random Chance of Something Happening
``` 1import random
2
3
4# The line below will "roll the dice" 20 times.
5# Don't copy this 'for' loop into your program.
6# It is just here so we can try this example over and over.
7for i in range(20):
8
9    # The line below will roll a random number 0-4.
10    # If we roll a '0' then print that we encountered a dragon.
11    if random.randrange(5) == 0:
12        print("DRAGON!!!")
13    else:
14        print("No dragon.")
```

This code repeats twenty times. Inside the loop, we “roll the dice” and get a number between 0 and 4. If we roll a 0, then we encounter a dragon. Otherwise we don’t.

## 13.3. The `random` Function¶

All of the prior code generates integer numbers. If a floating point number is desired, a programmer may use the `random` function.

The code below generates a random number from 0 to 1 such as 0.4355991106620656.

Random floating point number from 0 to 1
```my_number = random.random()
```

With some simple math, this number can be adjusted. For example, the code below generates a random floating point number between 10 and 15:

Random floating point number between 10 and 15

```my_number = random.random() * 5 + 10
```

## 13.4. Number Guessing Game Example¶

Here is the code for the number guessing game at the start of the chapter.

``` 1"""
2Random Number Guessing Game
3"""
4import random
5
6
7def main():
8
9    print("Hi! I'm thinking of a random number between 1 and 100.")
10
11    # NEW CONCEPT
12    # Create a secret number
13    secret_number = random.randrange(1, 101)
14
16    user_attempt_number = 1
17
18    # Set user guess to something secret number can't be, so we can
19    # get our 'while' loop started.
20    user_guess = 0
21
22    # NEW CONCEPT
23    # Loop until user_guess our secret number, or we run out of attempts.
24    while user_guess != secret_number and user_attempt_number < 8:
25
26        # Tell the user what attempt we are on, and get their guess:
27        print("--- Attempt", user_attempt_number)
28        user_input_text = input("Guess what number I am thinking of: ")
29        user_guess = int(user_input_text)
30
31        # Print if we are too high or low, or we got it.
32        if user_guess > secret_number:
33            print("Too high.")
34        elif user_guess < secret_number:
35            print("Too low.")
36        else:
37            print("You got it!")
38
39        # Add to the attempt count
40        user_attempt_number += 1
41
42    # Here, check to see if the user didn't guess the answer, and ran out of tries.
43    # Let her know what the number was, so she doesn't spend the rest of her life
44    # wondering.
45    if user_guess != secret_number:
46        print("Aw, you ran out of tries. The number was " + str(secret_number) + ".")
47
48# Call the main function
49main()
```

## 13.5. Mudball Example¶

This is a fun text-only game that two players can play. It uses a few concepts we haven’t covered yet.

```  1"""
2This is a sample text-only game that demonstrates the use of functions.
3The game is called "Mudball" and the players take turns lobbing mudballs
4at each other until someone gets hit.
5"""
6
7import math
8import random
9
10
11def print_instructions():
12    """ This function prints the instructions. """
13
14    # You can use the triple-quote string in a print statement to
15    # print multiple lines.
16    print("""
17Welcome to Mudball! The idea is to hit the other player with a mudball.
18Enter your angle (in degrees) and the amount of PSI to charge your gun
19with.
20        """)
21
22
23def calculate_distance(psi, angle_in_degrees):
24    """ Calculate the distance the mudball flies. """
26    distance = .5 * psi ** 2 * math.sin(angle_in_radians) * math.cos(angle_in_radians)
27    return distance
28
29
30def get_user_input(name):
31    """ Get the user input for psi and angle. Return as a list of two
32    numbers. """
33    # Later on in the 'exceptions' chapter, we will learn how to modify
34    # this code to not crash the game if the user types in something that
35    # isn't a valid number.
36    psi = float(input(name + " charge the gun with how many psi? "))
37    angle = float(input(name + " move the gun at what angle? "))
38    return psi, angle
39
40
41def get_player_names():
42    """ Get a list of names from the players. """
43    print("Enter player names. Enter as many players as you like.")
44    done = False
45    players = []
46    while not done:
47        player = input("Enter player (hit enter to quit): ")
48        if len(player) > 0:
49            players.append(player)
50        else:
51            done = True
52
53    print()
54    return players
55
56
57def process_player_turn(player_name, distance_apart):
58    """ The code runs the turn for each player.
59    If it returns False, keep going with the game.
60    If it returns True, someone has won, so stop. """
61    psi, angle = get_user_input(player_name)
62
63    distance_mudball = calculate_distance(psi, angle)
64    difference = distance_mudball - distance_apart
65
66    # By looking ahead to the chapter on print formatting, these
67    # lines could be made to print the numbers is a nice formatted
68    # manner.
69    if difference > 1:
70        print("You went", difference, "yards too far!")
71    elif difference < -1:
72        print("You were", difference * -1, "yards too short!")
73    else:
74        print("Hit!", player_name, "wins!")
75        return True
76
77    print()
78    return False
79
80
81def main():
82    """ Main program. """
83
84    # Get the game started.
85    print_instructions()
86    player_names = get_player_names()
87    distance_apart = random.randrange(50, 150)
88
89    # Keep looking until someone wins
90    done = False
91    while not done:
92        # Loop for each player
93        for player_name in player_names:
94            # Process their turn
95            done = process_player_turn(player_name, distance_apart)
96            # If someone won, 'break' out of this loop and end the game.
97            if done:
98                break
99
100if __name__ == "__main__":
101    main()
```

## 13.6. Online Coding Problems¶

Practice on-line by completing the first set of coding problems available here:

https://repl.it/community/classrooms/174286

All problems beginning with `04` can be done with the knowledge from this chapter.