How to create a memory puzzle game with Python and Pygame (#001)
In order to create our full game, we first need to set up a window and fill the window with white background color.
import pygame, sys from pygame.locals import * pygame.init() SCREEN_SIZE = (640,480) # main screen set up screen = pygame.display.set_mode(SCREEN_SIZE) pygame.display.set_caption('Puzzle Game') # color setup WHITE = (255,255,255) screen.fill(WHITE) # set backgroud color to white while True: for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() pygame.display.update()
Explanation
import pygame, os
from pygame.locals import *
We need to import all the necessary modules into our source file, which is the same for all pygame applications.
pygame.init()
After importing all the necessary modules, we need to initialize the pygame module.
SCREEN_SIZE = (640,480)
# main screen set up
screen = pygame.display.set_mode(SCREEN_SIZE)
pygame.display.set_caption('Puzzle Game')
Next, we just create the main game screen with a screen size 640*480 and leave other parameters to the pygame moudle to decide. And also we need to set the window caption to whatever name you want.
# color setup
WHITE = (255,255,255)
screen.fill(WHITE)
For now, we just need one white color which is the background color of the main window and set its background color to white.
# set backgroud color to white
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
Every game should have a game loop, our game loop is the while loop. In oder to quite the game safely, we need to use pygame's event handling mechanism. We iterate through all the events returnted by the pygame.event.get() method, if the event is a quit event, we quit the game by invoking pygame.quit() and sys.exit().
pygame.display.update()
And now, press F5 or run the module inside your IDLE. You should see the following screen shot.
Congratulations, we have created our main game dislpay. Now, you can quit the screen by clicking the 'x' on the right corner of the game window.
Comments
Post a Comment