Pygame Book – part 3 – background and mouse click event

A little improvement in this part of the “Pygame book” a new series of tutorials about pygame intented to give a sort of template to make a 2d game, probably a platform.

You can find the repository with the files and a self made file browser, that you see in the video below.

There are few things added to the code, just a way to color the screen and change it clicking the mouse.

# This is imported by game.py
# pygame_book 3: added background color and control mouse click - 2.1.2020
import pygame as pg


class Game:

	def __init__(self, w, h):
		"Initialize main surface (screen) and starting the loop"
		self.window_size(w, h)
		self.main_surface()
		self.loop()

	def window_size(self, w, h):
		"Define the width and height of the window"
		self.width = w
		self.height = h
		self.size = self.width, self.height

	def main_surface(self):
		"Creates the main surface of the screen"
		self.screen = pg.display.set_mode(self.size)

	def close_window(self, event, game_on):
		"Close the window with the x button or Esc"
		quit = event.type == pg.QUIT
		escape = event.type == pg.KEYDOWN and event.key == pg.K_ESCAPE
		if quit or escape:
			game_on = 0
		return game_on

	def user_interactions(self, event):
		"Checks for the mouse input"
		mousepressed = event.type == pg.MOUSEBUTTONDOWN
		if mousepressed:
			print("Mouse pressed")
			self.screen_color((225, 245, 0))

	def screen_color(self, color):
		"Gives the screen a color"
		self.screen.fill(color)

	def loop(self):
		"The loop that make the game go on"
		game_on = 1
		self.screen_color((225, 128, 0))
		while game_on:
			# User Interaction control
			for event in pg.event.get():
				# Control Escape and Quit click to close the window
				game_on = self.close_window(event, game_on)
				# Controls if you click the mouse button
				self.user_interactions(event)
			pg.display.update()
		pg.quit()

if __name__ == "__main__":
    game = Game(16*50, 8*50)

Subscribe to the newsletter for updates
Tkinter templates
My youtube channel

Twitter: @pythonprogrammi - python_pygame

Videos

Speech recognition game

Pygame's Platform Game

Other Pygame's posts