Game Save with Shelve

From TRCCompSci - AQA Computer Science
Revision as of 14:24, 17 July 2018 by Admin (talk | contribs) (Created page with "=Example to Use= Have a look at this code: <syntaxhighlight lang=python> import pygame from pygame.locals import * pygame.init() screen=pygame.display.set_mode((640,480)) c...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Example to Use

Have a look at this code:

import pygame
from pygame.locals import *

pygame.init()
screen=pygame.display.set_mode((640,480))

class Block(object):
    sprite = pygame.image.load("dirt.png").convert_alpha()
    def __init__(self, x, y):
        self.rect = self.sprite.get_rect(centery=y, centerx=x)

blocklist = []

while True:
    screen.fill((25,30,90))
    mse = pygame.mouse.get_pos()
    key = pygame.key.get_pressed()

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

        if event.type==MOUSEBUTTONDOWN:
            if not any(block.rect.collidepoint(mse) for block in blocklist):
                x=(int(mse[0]) / 32)*32
                y=(int(mse[1]) / 32)*32
                blocklist.append(Block(x+16,y+16))

    for b in blocklist:
        screen.blit(b.sprite, b.rect)

    pygame.display.flip()

It creates a class called Block, and a list called blocklist. Everytime you press the mouse button a block will be created at the mouse position and it will be added to the blocklist. The game loop cycles through each block in the blocklist and blits it to the screen.