how to make a game using pygame code example
Example 1: how to setup pygame
import pygame
import sys
pygame.init()
clock = pygame.time.Clock()
FPS = 30
screen_width = 600
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))
while True:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
Example 2: simple game with python
import pygame
from pygame.locals import *
pygame.init()
width, height = 640, 480
screen=pygame.display.set_mode((width, height))
player = pygame.image.load("resources/images/dude.png")
while 1:
screen.fill(0)
screen.blit(player, (100,100))
pygame.display.flip()
for event in pygame.event.get():
if event.type==pygame.QUIT:
pygame.quit()
exit(0)
Example 3: how to make a game in pygame for beginners
import pygame
pygame.init()
screen = pygame.display.set_mode((400, 300))
done = False
is_blue = True
x = 30
y = 30
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
is_blue = not is_blue
pressed = pygame.key.get_pressed()
if pressed[pygame.K_UP]: y -= 3
if pressed[pygame.K_DOWN]: y += 3
if pressed[pygame.K_LEFT]: x -= 3
if pressed[pygame.K_RIGHT]: x += 3
if is_blue: color = (0, 128, 255)
else: color = (255, 100, 0)
pygame.draw.rect(screen, color, pygame.Rect(x, y, 60, 60))
pygame.display.flip()