Module 5 - Section 0 - Repeat!

Site: ΕΛ/ΛΑΚ Moodle
Course: Python Lab
Book: Module 5 - Section 0 - Repeat!
Printed by: Guest user
Date: Sunday, 5 May 2024, 12:24 AM

Description

This section is a repetition of the previous modules

5.0.1 - While loop


Example

i = 0 while i < 10: print(i) i = i + 1

5.0.2 - Functions

Don't Repeat Yourself (DRY) and don't Write Everything Twice (WET)


5.0.3 - Pygame basics

For a new Pygame project we can start from the Pygame basic template

Let's review the series of commands :

import pygame # it imports the library pygame

pygame.init() # starts the pygame 

size = (700,500) # Set the width and height of the screen

screen = pygame.display.set_mode(size) # creates a window and name it screen

pygame.display.set_caption("My Game") # This is the name on the top of the window

done = False # We create a variable that is called done and when this variable turns to True, during the game, the game stops.

clock = pygame.time.Clock() # It controls the refresh rate

Event processing. 

for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True

screen.fill(WHITE) # background is WHITE. 

pygame.display.flip() # update the screen

clock.tick(60) # refresh 60 times a second

pygame.quit() # Close the window and quit.

5.0.4 - Drawing shapes and text

Pygame basic template

All the following commands are written inside the main loop inside section "# --- Drawing code should go here"

Draw a rectangle

pygame.draw.rect(screen, WHITE, [50, 50, 50, 50]) 

Draw a hollow circle 

pygame.draw.circle(screen, RED, [200, 140], 30, 5)

Draw an ellipse

pygame.draw.ellipse(screen, RED, [20, 20, 250, 100], 2)

Draw a polygon 

pygame.draw.polygon(screen, GREEN, [[50,100],[0,200],[200,200],[100,50]], 5)

Draw text

font = pygame.font.SysFont('Calibri', 25, True, False)
text = font.render("My text",True,BLACK)
screen.blit(text, [250, 250])