/* jquery */ /* jquery accordion style*/ /* jquery init */

Learn Python - PyGame Complete App

Over the last few posts we've looked at PyGame installation, events, event handling, colour definition, initialisation and drawing.

Now it's time to put all the ingredients together in the form of a complete app.

Here's the listing:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
35
35
36
37
38
39
40
41
# PyGame Skeleton

import pygame, sys, random

def check_events(pos):
  # loop through all events
  for event in pygame.event.get():
    if event.type == pygame.QUIT:
      sys.quit()
    if event.type == pygame.MOUSEBUTTONDOWN:
      # draw a coloured disc at the current mouse position
      discSize = random.randint(5,50)
      r = random.randint(100,255)
      g = random.randint(100,255)
      b = random.randint(100,255)
      discCol = [r,g,b]
      pygame.draw.circle(screen, discCol, pos, discSize)

def run():
  # get mouse position
  pos = pygame.mouse.get_pos()

  # check events
  check_events(pos)

  # update the screen with what we've drawn
  pygame.display.flip()

  # control the draw update speed
  clock.tick(50)

# initialise pygame
pygame.init()
screen = pygame.display.set_mode([500,400])
screen.fill(pygame.Color('black'))
pygame.display.set_caption("My Game")
clock = pygame.time.Clock()

# loop until the user clicks the close button
while True:
  run()

Take this basic structure and add your own enhancements. Maybe additional event handling or drawing different shapes.

I hope you've enjoyed this series. Happy coding.

Visit my Raspberry Pi page for news, reviews, advice and tutorials.

No comments: