THE MOUSE IS an extremely versatile tool. Mice are simple to use and make interaction with the computer via GUIs very straightforward.
In this adventure, you’ll learn how to use the mouse with Python and PyGame
. You’ll learn how to check for mouse clicks and find the position of the mouse pointer. By building on these basic things, you’ll create some cool programs including a moving target game, a mesh drawer and a trail that follows the mouse around the window.
The mouse position uses coordinates to determine its position like other PyGame
programs. Values for the coordinates are most frequently represented by x and y variables. The top-left corner has the coordinates 0, 0, with these x and y values increasing as the mouse moves farther to the right and downwards.
Let’s dive into using the mouse with Python and PyGame
.
This first program will get the current position of the mouse and display it. The program is meant to show you how to get the mouse position; it doesn’t do much else.
In this program, you press the left button on the mouse in order to display the value of the mouse position. As you move the mouse around the PyGame
window the value of the mouse position will change. When you click again in the window, the new value will be displayed.
To keep things simple, the program will print the mouse’s position in the Python shell when the mouse is clicked.
mousePos.py
in a new folder called Adventure 7
.PyGame
window:
import pygame
pygame.init()
windowSize = [400, 300]
screen = pygame.display.set_mode(windowSize)
clock = pygame.time.Clock()
done = False
while not done:
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONDOWN:
pos = pygame.mouse.get_pos()
print pos
if event.type == pygame.QUIT:
done = True
pygame.quit()
In Adventure 3, you learned how to make buttons with Tkinter
. Unlike Tkinter
, PyGame
doesn’t have an inbuilt way to create buttons easily because it is made to create games and other multimedia. However, with a small amount of code you can create an area in the PyGame
window that works like a button.
You’re going to create a program that will create a rectangle in the middle of the window. When you click on the rectangle it will change the colour of the window, but when you click elsewhere in the window it will do nothing.
You’ll then build upon this code to create a game where you have to click on a moving target.
You can see the finished program in Figure 7-2.
Time to get going.
button.py
in the Adventure 7
folder.PyGame
window:
import pygame
pygame.init()
windowSize = [400, 300]
screen = pygame.display.set_mode(windowSize)
clock = pygame.time.Clock()
btnColour
colour variable is the colour for the button:
black = pygame.color.Color("#000000")
white = pygame.color.Color("#FFFFFF")
btnColour = pygame.color.Color("#A45C8F")
False
and the default position of the mouse. Add this code now:
btnWidth = 50
btnLength = 20
btnX = (windowSize[0] - btnWidth) / 2
btnY = (windowSize[1] - btnLength) / 2
toggled = False
pos = (0, 0)
True
, it will make the background colour of the window black, otherwise it will be white.
done = False
while not done:
if toggled:
screen.fill(black)
else:
screen.fill(white)
toggled
variable, thereby changing the colour of the background:
pygame.draw.rect(screen, btnColour, [btnX, btnY,
btnWidth, btnLength])
if btnX <= pos[0] <= btnX + btnWidth and btnY <=
pos[1] <= btnY + btnLength:
toggled = not toggled
pos = [0, 0]
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONDOWN:
pos = pygame.mouse.get_pos()
if event.type == pygame.QUIT:
done = True
pygame.display.flip()
clock.tick(10)
pygame.quit()
Now that you can create a clickable area in the PyGame
window, let’s modify the code to turn it into a game.
In the game, the clickable area will move around the window randomly. When the player clicks the area they will get points, but the difficulty of the game will also increase, making the random movements of the button more erratic and therefore harder to click.
In Figure 7-3 you can see that the button you created in the last program will now move around the window.
button.py
in the Adventure 7
folder.movingTarget.py
in the Adventure 7
folder.import random
toggled = False
pos = (0, 0)
points = 0
if btnX <= pos[0] <= btnX + btnWidth and
btnY <= pos[1] <= btnY + btnLength:
toggled = not toggled
pos = (0, 0)
points += 1
btnX += random.randint(-1 - points, 1 + points)
btnY += random.randint(-1 - points, 1 + points)
print points
With some minor modifications to the program you can make quite a drastic change to its effects. In this program, you’ll create an explosion effect that will appear every time you click in the window.
The colour of the explosions will be randomised every time you click the mouse.
explosions.py
in the Adventure 7
folder.import pygame
import random
pygame.init()
def randColour():
r = random.randint(0, 255)
g = random.randint(0, 255)
b = random.randint(0, 255)
return (r, g, b)
windowSize = [400, 300]
screen = pygame.display.set_mode(windowSize)
clock = pygame.time.Clock()
black = pygame.color.Color("#000000")
colour = randColour()
count = 0
click = False
limit = 30
pos = (0, 0)
done = False
while not done:
screen.fill(black)
if click and count < limit:
pygame.draw.circle(screen, colour, pos, count)
count += 1
if count >= limit:
click = False
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONDOWN:
pos = pygame.mouse.get_pos()
click = True
count = 0
colour = randColour()
if event.type == pygame.QUIT:
done = True
pygame.display.flip()
clock.tick(60)
pygame.quit()
Flexibility is one of benefits of using PyGame
with Python. So far in this adventure, you’ve seen several variations on programs that use the mouse position and mouse clicks.
The next program will show you how flexible PyGame
and Python can be. The program will allow you to draw lines that look like a 3D mesh. A 3D mesh is a collection of joined lines that are used to make 3D models. This program will create something that looks like a 3D mesh but doesn’t work like one—it just looks similar.
You can see an example of this program in Figure 7-5.
When you click on the window the program will create a new point in the mesh. Every following click will create a new point in the mesh. The program will limit the number of points in the mesh to 10 points, after which it will delete the oldest point and update the mesh.
mesh.py
in the Adventure 7
folder.import pygame
pygame.init()
windowSize = [400, 300]
screen = pygame.display.set_mode(windowSize)
clock = pygame.time.Clock()
points = []
black = pygame.color.Color("#000000")
white = pygame.color.Color("#FFFFFF")
done = False
while not done:
screen.fill(black)
if len(points) > 10:
del points[0]
if len(points) > 1:
pygame.draw.lines(screen, white, True, points)
for point in points:
pygame.draw.line(screen, white, point, [point[0], windowSize[1]])
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONDOWN:
pos = pygame.mouse.get_pos()
points.append(pos)
if event.type == pygame.QUIT:
done = True
pygame.display.flip()
clock.tick(10)
pygame.quit()
This final program in this adventure creates a trail of lines behind the mouse. The difference between this program and the others in the adventure is that it doesn’t use mouse clicks, just the position of the mouse. The mouse trails program not only looks cool, it also shows you how you can follow the mouse’s position without needing to click any buttons.
Look at Figure 7-6 to see the trails following the mouse.
mouseTrails.py
in the Adventure 7
folder.PyGame
window, creates a list for the points of the trail that will be stored and also creates two variables that store colours:
import pygame
pygame.init()
windowSize = [400, 300]
screen = pygame.display.set_mode(windowSize)
clock = pygame.time.Clock()
points = []
white = pygame.color.Color("#FFFFFF")
black = pygame.color.Color("#000000")
done = False
while not done:
screen.fill(black)
pos = pygame.mouse.get_pos()
if pos[0] != 0 and pos[1] != 0:
points.append(pos)
if len(points) >= 20:
del points[0]
if len(points) >= 2:
pygame.draw.aalines(screen, white, False, points)
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
pygame.display.flip()
clock.tick(30)
pygame.quit()
Python Command Quick Reference Table |
|
Command |
Description |
|
When any mouse button is pressed, a |
|
This function finds the position of the mouse and returns the x and y values as a tuple. |
|
A range check is used to check if one value is between two others. If it is, it will evaluate to |
|
To check the number of items in a list (and any other collections, such as tuples), the |
|
To add an item to the end of a list, the |
|
To delete an item from a list, the |
|
The |
|
The |
Achievement Unlocked: Skilled manipulator of the mouse to create superb programs with PyGame
.