If you want to learn how to do a game with python you have to learn how to use the module pygame. We will take a tour through some basic stuffs.
In this first example we will set a screen of 400×300 dimensions, with a loop in wich you will draw circles as you move the mouse in the window.
You start with
pygame init()
then you define the screen and give the window a title
screen = pygame.display.set_mode((400,300)) pygame.display.set_caption('A bit Racey')
To control the frame rate:
clock = pygame.time.Clock()
then you start the infinite loop with:
while loop:
It will listen to every event that happens:
for event in pygame.event.get():
To be able to close the windows properly:
if event.type == pygame.QUIT: loop = False
Then you get the position of the mouse to make the circle related to this position:
pos = pygame.mouse.get_pos()
So, you draw the circle with screen (the display object), the color, the center coordinates (that are the position of the mouse that we get above) and the radius and the width.
pygame.draw.circle(screen, (0,0,255), pos, 15, 1)
Then you update the screen
pygame.display.update()
and you make it do it for 60 frames for second
clock.tick(60)
When you click the quit button, the window will close:
pygame.quit()
The entire code to make this pygame app
Here are two images of this pygame app in wich you can “draw” on the window. You move the mouse and a circle is drawn making these shapes you can see in the images below. With some little changes you could:
- draw only when you press the mouse
- change color when you press the keyboard
- change the dimentions of the ‘brush’
- change the shape of the brush
- ecc.
import pygame pygame.init() screen = pygame.display.set_mode((400,300)) pygame.display.set_caption('A bit Racey') clock = pygame.time.Clock() loop = True while loop: for event in pygame.event.get(): if event.type == pygame.QUIT: loop = False pos = pygame.mouse.get_pos() pygame.draw.circle(screen, (0,0,255), pos, 15, 1) pygame.display.update() clock.tick(60) pygame.quit() # quit()
You can make the mouse invisible if you want:
pygame.mouse.set_visible
()If the bool argument is true, the mouse cursor will be visible. This will return the previous visible state of the cursor.hide or show the mouse cursorset_visible(bool) -> bool
The video about the first tutorial for pygame and python
Maybe in the next video we will see how to make the changes I wrote about above.
To be continued