Steves-Pixels-Modified-V1
598 líneas
# Star Pusher (a Sokoban clone)
from os import environ
# By Al Sweigart al@inventwithpython.com
# http://inventwithpython.com/pygame
# Released under a "Simplified BSD" license
import random, sys, copy, os, pygame
environ['PYGAME_HIDE_SUPPORT_PROMPT'] = "hide"
# hide pygame message
import pygame
import copy
import random
import sys
from win32gui import SetWindowPos
from pygame.locals import *
from pygame.locals import *
from PIL import Image, ImageFilter
FPS = 30 # frames per second to update the screen
# Code by:
WINWIDTH = 800 # width of the program's window, in pixels
# ..\ Ishan Jindal
WINHEIGHT = 600 # height in pixels
HALF_WINWIDTH = int(WINWIDTH / 2)
HALF_WINHEIGHT = int(WINHEIGHT / 2)
# The total width and height of each tile in pixels.
# Orignal Project by:
TILEWIDTH = 50
# ..\ Al Sweigart
TILEHEIGHT = 85
TILEFLOORHEIGHT = 40
CAM_MOVE_SPEED = 5 # how many pixels per frame the camera moves
# Based on:
# ..\ Retro Game - Sokoban
# The percentage of outdoor tiles that have additional
# GitHub Repo Link:
# decoration on them, such as a tree or rock.
# https://github.com/IshanJ25/Steves-Pixels
OUTSIDE_DECORATION_PCT = 20
BRIGHTBLUE = ( 0, 170, 255)
# This project is BSD 2-Clause Licensed
WHITE = (255, 255, 255)
# It is open-source under fair usage
BGCOLOR = BRIGHTBLUE
# Kindly mention Authors' names if you copy this code
TEXTCOLOR = WHITE
assets_folder = 'assets'
# !!! very important. all assets placed here
# leave empty string to disable if root folder
cheatcode = 'helpme'
# Don't tell anyone!
# leave empty string to disable
pygame.init()
screen_w = pygame.display.Info().current_w
screen_h = pygame.display.Info().current_h
color = {
'black': (50, 50, 50),
'blacker': (20, 20, 20),
'white': (240, 240, 240),
'gray': (150, 150, 150),
'red': (255, 50, 50),
'orange': (255, 150, 0),
'yellow': (255, 200, 0),
'green': (100, 200, 50),
'blue': (0, 220, 220),
'purple': (150, 100, 255),
}
image_dict = {'uncovered goal': pygame.image.load(f'{assets_folder}\\orange_pad.png'),
'covered goal': pygame.image.load(f'{assets_folder}\\green_pad.png'),
'pixel': pygame.image.load(f'{assets_folder}\\pixels.png'),
'wall': pygame.image.load(f'{assets_folder}\\wood.png'),
'inside floor': pygame.image.load(f'{assets_folder}\\sand.png'),
'outside floor': pygame.image.load(f'{assets_folder}\\grass.png'),
'title': pygame.image.load(f'{assets_folder}\\title.png'),
'solved': pygame.image.load(f'{assets_folder}\\solved.png'),
'p_front': pygame.image.load(f'{assets_folder}\\steve_front.png'),
'p_back': pygame.image.load(f'{assets_folder}\\steve_back.png'),
'p_left': pygame.image.load(f'{assets_folder}\\steve_left.png'),
'p_right': pygame.image.load(f'{assets_folder}\\steve_right.png'),
'rock': pygame.image.load(f'{assets_folder}\\rock.png'),
'tall tree': pygame.image.load(f'{assets_folder}\\bush.png'),
'cursor': pygame.image.load(f'{assets_folder}\\cursor.png'),
'cut_in': pygame.image.load(f'{assets_folder}\\start.png'),
'cut_out': pygame.image.load(f'{assets_folder}\\over.png'),
'creds': pygame.image.load(f'{assets_folder}\\credits.png')}
sound_dict = {'pause': f'{assets_folder}\\pause.mp3',
'resume': f'{assets_folder}\\resume.mp3',
'level_complete': f'{assets_folder}\\level.mp3',
'theme': f'{assets_folder}\\theme.mp3'}
##################################################
##################################################
############# EDITABLE PARAMETERS ###############
##################################################
##################################################
fullscreen = True
win_w = 1500
win_h = 800
# ignored if fullscreen
window_y_offset = 0.6
# offset y position of window by -60%
music_during_levels = True
tile_w = 50
tile_h = 85
tile_floor_height = 40
scale_map_int: int = 2
# choose among 1, 2, 3; 2 is optimal in fullscreen; Ignored if auto_scale is True
scale_map: int
auto_scale = True
title_transform = [[60, 75], 3]
# min and max percentage of title image wrt window size
# slowness wrt 60 fps
pause_blur = 25
pause_opacity = 150
# out of 255
lvl_complete_blur = 5
grass_decoration_percentage = 40
bg_color = color['black']
txt_color = color['white']
font_size = round(win_h / 25 * 0.75)
music_volume = [0.4, 0.08, 0.16]
# max, min, levels
if not music_during_levels:
music_volume[2] = 0
##################################################
##################################################
############# STANDARD DEFINITIONS ##############
##################################################
##################################################
UP = 'up'
UP = 'up'
DOWN = 'down'
DOWN = 'down'
LEFT = 'left'
LEFT = 'left'
RIGHT = 'right'
RIGHT = 'right'
fps_clock = pygame.time.Clock()
if not fullscreen:
screen = pygame.display.set_mode((win_w, win_h))
SetWindowPos(pygame.display.get_wm_info()['window'], -1,
round(screen_w / 2 - win_w / 2), round((screen_h / 2 - win_h / 2) * window_y_offset), 0, 0, 1)
else:
win_w = screen_w
win_h = screen_h
screen = pygame.display.set_mode((win_w, win_h), pygame.FULLSCREEN)
if not auto_scale:
scale_map = scale_map_int
else:
map_size_chunk = tile_w * tile_w * 100
window_area = win_w * win_h
tile_screen_percent = round(map_size_chunk / window_area * 100)
if tile_screen_percent <= 10:
scale_map = 3
elif tile_screen_percent <= 30:
scale_map = 2
else:
scale_map = 1
CAM_MOVE_SPEED = scale_map / 3
win_w_half = int(win_w / 2)
win_h_half = int(win_h / 2)
cursor_img = pygame.transform.scale(image_dict['cursor'], (32, 32))
pygame.mouse.set_visible(False)
pause_sound = pygame.mixer.Sound(sound_dict['pause'])
resume_sound = pygame.mixer.Sound(sound_dict['resume'])
level_sound = pygame.mixer.Sound(sound_dict['level_complete'])
music = pygame.mixer.music.load(sound_dict['theme'])
pygame.mixer.music.play(-1)
pygame.mixer.music.set_volume(music_volume[0])
##################################################
##################################################
##################################################
def main():
def main():
global FPSCLOCK, DISPLAYSURF, IMAGESDICT, TILEMAPPING, OUTSIDEDECOMAPPING, BASICFONT, PLAYERIMAGES, currentImage
global tile_mapping, grass_deco_mapping, basic_font, player_images, currentImage
global scale_map, tile_w, tile_h, tile_floor_height
# Pygame initialization and basic set up of the global variables.
tile_w *= scale_map
pygame.init()
tile_h *= scale_map
FPSCLOCK = pygame.time.Clock()
tile_floor_height *= scale_map
# Because the Surface object stored in DISPLAYSURF was returned
pygame.display.set_caption('Steve\'s Pixels')
# from the pygame.display.set_mode() function, this is the
pygame.display.set_icon(image_dict['cursor'])
# Surface object that is drawn to the actual computer screen
basic_font = pygame.font.Font(f'{assets_folder}\\AccordAlternate-Bold.ttf', font_size)
# when pygame.display.update() is called.
DISPLAYSURF = pygame.display.set_mode((WINWIDTH, WINHEIGHT))
pygame.display.set_caption('Star Pusher')
for i in image_dict:
BASICFONT = pygame.font.Font('freesansbold.ttf', 18)
if i not in ('title', 'solved', 'cursor', 'cut_in', 'cut_out', 'creds'):
image_dict[i] = pygame.transform.scale(image_dict[i], (tile_w, tile_h))
# A global dict value that will contain all the Pygame
tile_mapping = {'#': image_dict['wall'],
# Surface objects returned by pygame.image.load().
'o': image_dict['inside floor'],
IMAGESDICT = {'uncovered goal': pygame.image.load('RedSelector.png'),
' ': image_dict['outside floor']}
'covered goal': pygame.image.load('Selector.png'),
'star': pygame.image.load('Star.png'),
'corner': pygame.image.load('Wall_Block_Tall.png'),
'wall': pygame.image.load('Wood_Block_Tall.png'),
'inside floor': pygame.image.load('Plain_Block.png'),
'outside floor': pygame.image.load('Grass_Block.png'),
'title': pygame.image.load('star_title.png'),
'solved': pygame.image.load('star_solved.png'),
'princess': pygame.image.load('princess.png'),
'boy': pygame.image.load('boy.png'),
'catgirl': pygame.image.load('catgirl.png'),
'horngirl': pygame.image.load('horngirl.png'),
'pinkgirl': pygame.image.load('pinkgirl.png'),
'rock': pygame.image.load('Rock.png'),
'short tree': pygame.image.load('Tree_Short.png'),
'tall tree': pygame.image.load('Tree_Tall.png'),
'ugly tree': pygame.image.load('Tree_Ugly.png')}
# These dict values are global, and map the character that appears
grass_deco_mapping = {'0': image_dict['rock'],
# in the level file to the Surface object it represents.
'1': image_dict['tall tree']}
TILEMAPPING = {'x': IMAGESDICT['corner'],
'#': IMAGESDICT['wall'],
'o': IMAGESDICT['inside floor'],
' ': IMAGESDICT['outside floor']}
OUTSIDEDECOMAPPING = {'1': IMAGESDICT['rock'],
'2': IMAGESDICT['short tree'],
'3': IMAGESDICT['tall tree'],
'4': IMAGESDICT['ugly tree']}
# PLAYERIMAGES is a list of all possible characters the player can be.
# currentImage is the index of the player's current player image.
currentImage = 0
currentImage = 0
PLAYERIMAGES = [IMAGESDICT['princess'],
player_images = [image_dict['p_front'],
IMAGESDICT['boy'],
image_dict['p_back'],
IMAGESDICT['catgirl'],
image_dict['p_left'],
IMAGESDICT['horngirl'],
image_dict['p_right']]
IMAGESDICT['pinkgirl']]
startScreen() # show the title screen until the user presses a key
startScreen()
cutscene('start')
# Read in the levels from the text file. See the readLevelsFile() for
levels = readLevelsFile()
# details on the format of this file and how to make your own levels.
levels = readLevelsFile('starPusherLevels.txt')
currentLevelIndex = 0
currentLevelIndex = 0
# The main game loop. This loop runs a single level, when the user
while True:
# finishes that level, the next/previous level is loaded.
while True: # main game loop
# Run the level to actually start playing the game:
result = runLevel(levels, currentLevelIndex)
result = runLevel(levels, currentLevelIndex)
if result in ('solved', 'next'):
if result in ('solved', 'next'):
# Go to the next level.
currentLevelIndex += 1
currentLevelIndex += 1
if currentLevelIndex >= len(levels):
if currentLevelIndex >= len(levels):
# If there are no more levels, go back to the first one.
break
currentLevelIndex = 0
elif result == 'back':
pygame.mixer.music.set_volume(music_volume[0])
# Go to the previous level.
cutscene('over')
currentLevelIndex -= 1
creds()
if currentLevelIndex < 0:
# If there are no previous levels, go to the last one.
currentLevelIndex = len(levels)-1
elif result == 'reset':
pass # Do nothing. Loop re-calls runLevel() to reset the level
def runLevel(levels, levelNum):
def runLevel(levels, levelNum):
pygame.mixer.music.set_volume(music_volume[2])
global currentImage
global currentImage
levelObj = levels[levelNum]
levelObj = levels[levelNum]
mapObj = decorateMap(levelObj['mapObj'], levelObj['startState']['player'])
mapObj = decorateMap(levelObj['mapObj'], levelObj['startState']['player'])
gameStateObj = copy.deepcopy(levelObj['startState'])
gameStateObj = copy.deepcopy(levelObj['startState'])
mapNeedsRedraw = True # set to True to call drawMap()
mapNeedsRedraw = True
levelSurf = BASICFONT.render('Level %s of %s' % (levelNum + 1, len(levels)), 1, TEXTCOLOR)
levelSurf = basic_font.render(f'Level {levelNum + 1} of {len(levels)}', 1, txt_color)
levelRect = levelSurf.get_rect()
levelRect = levelSurf.get_rect()
levelRect.bottomleft = (20, WINHEIGHT - 35)
levelRect.bottomleft = (20, round(win_h - 2 * font_size * 4 / 3))
mapWidth = len(mapObj) * TILEWIDTH
mapWidth = len(mapObj) * tile_w
mapHeight = (len(mapObj[0]) - 1) * TILEFLOORHEIGHT + TILEHEIGHT
mapHeight = (len(mapObj[0]) - 1) * tile_floor_height + tile_h
MAX_CAM_X_PAN = abs(HALF_WINHEIGHT - int(mapHeight / 2)) + TILEWIDTH
MAX_CAM_X_PAN = abs(win_h_half - int(mapHeight / 2)) + tile_w
MAX_CAM_Y_PAN = abs(HALF_WINWIDTH - int(mapWidth / 2)) + TILEHEIGHT
MAX_CAM_Y_PAN = abs(win_w_half - int(mapWidth / 2)) + tile_h
levelIsComplete = False
levelIsComplete = False
# Track how much the camera has moved:
cameraOffsetX = 0
cameraOffsetX = 0
cameraOffsetY = 0
cameraOffsetY = 0
# Track if the keys to move the camera are being held down:
cameraUp = False
cameraUp = False
cameraDown = False
cameraDown = False
cameraLeft = False
cameraLeft = False
cameraRight = False
cameraRight = False
while True: # main game loop
solved_shown = False
# Reset these variables:
cheat_entered = ''
alphabets = ['a', 'b', 'c', 'd', 'e', 'f', 'g',
'h', 'i', 'j', 'k', 'l', 'm', 'n',
'o', 'p', 'q', 'r', 's', 't', 'u',
'v', 'w', 'x', 'y', 'z']
while True:
playerMoveTo = None
playerMoveTo = None
keyPressed = False
for event in pygame.event.get(): # event handling loop
for event in pygame.event.get():
if event.type == QUIT:
if event.type == QUIT:
# Player clicked the "X" at the corner of the window.
terminate()
pause_screen()
elif event.type == KEYDOWN:
elif event.type == KEYDOWN:
# Handle key presses
keyPressed = True
if event.key == K_LEFT:
playerMoveTo = LEFT
elif event.key == K_RIGHT:
playerMoveTo = RIGHT
elif event.key == K_UP:
playerMoveTo = UP
elif event.key == K_DOWN:
playerMoveTo = DOWN
# Set the camera move mode.
current_key = pygame.key.name(event.key)
elif event.key == K_a:
if current_key in alphabets and len(cheat_entered) < len(cheatcode):
if current_key == cheatcode[len(cheat_entered)]:
cheat_entered += current_key
else:
cheat_entered = ''
if solved_shown:
currentImage = 0
return 'solved'
if event.key == K_j:
cameraLeft = True
cameraLeft = True
elif event.key == K_d:
elif event.key == K_l:
cameraRight = True
cameraRight = True
elif event.key == K_w:
elif event.key == K_i:
cameraUp = True
cameraUp = True
elif event.key == K_s:
elif event.key == K_k:
cameraDown = True
cameraDown = True
elif event.key == K_n:
return 'next'
elif event.key == K_a or event.key == K_LEFT:
elif event.key == K_b:
currentImage = 2
return 'back'
playerMoveTo = LEFT
mapNeedsRedraw = True
elif event.key == K_d or event.key == K_RIGHT:
currentImage = 3
playerMoveTo = RIGHT
mapNeedsRedraw = True
elif event.key == K_w or event.key == K_UP:
currentImage = 1
playerMoveTo = UP
mapNeedsRedraw = True
elif event.key == K_s or event.key == K_DOWN:
currentImage = 0
playerMoveTo = DOWN
mapNeedsRedraw = True
elif event.key == K_ESCAPE:
elif event.key == K_ESCAPE:
terminate() # Esc key quits.
pause_screen()
elif event.key == K_BACKSPACE:
elif event.key == K_BACKSPACE:
return 'reset' # Reset the level.
currentImage = 0
elif event.key == K_p:
# Change the player image to the next one.
currentImage += 1
if currentImage >= len(PLAYERIMAGES):
# After the last player image, use the first one.
currentImage = 0
mapNeedsRedraw = True
mapNeedsRedraw = True
return 'reset'
elif event.type == KEYUP:
elif event.type == KEYUP:
# Unset the camera move mode.
if event.key == K_a:
if event.key == K_j:
cameraLeft = False
cameraLeft = False
elif event.key == K_d:
elif event.key == K_l:
cameraRight = False
cameraRight = False
elif event.key == K_w:
elif event.key == K_i:
cameraUp = False
cameraUp = False
elif event.key == K_s:
elif event.key == K_k:
cameraDown = False
cameraDown = False
if playerMoveTo != None and not levelIsComplete:
if playerMoveTo is not None and not levelIsComplete:
# If the player pushed a key to move, make the move
# (if possible) and push any stars that are pushable.
moved = makeMove(mapObj, gameStateObj, playerMoveTo)
moved = makeMove(mapObj, gameStateObj, playerMoveTo)
if moved:
if moved:
# increment the step counter.
gameStateObj['stepCounter'] += 1
gameStateObj['stepCounter'] += 1
mapNeedsRedraw = True
mapNeedsRedraw = True
if isLevelFinished(levelObj, gameStateObj):
if isLevelFinished(levelObj, gameStateObj):
# level is solved, we should show the "Solved!" image.
levelIsComplete = True
levelIsComplete = True
keyPressed = False
DISPLAYSURF.fill(BGCOLOR)
screen.fill(bg_color)
if mapNeedsRedraw:
if mapNeedsRedraw:
mapSurf = drawMap(mapObj, gameStateObj, levelObj['goals'])
mapSurf = drawMap(mapObj, gameStateObj, levelObj['goals'])
mapNeedsRedraw = False
mapNeedsRedraw = False
if cameraUp and cameraOffsetY < MAX_CAM_X_PAN:
if cameraUp and cameraOffsetY < MAX_CAM_X_PAN:
cameraOffsetY += CAM_MOVE_SPEED
cameraOffsetY += CAM_MOVE_SPEED
elif cameraDown and cameraOffsetY > -MAX_CAM_X_PAN:
elif cameraDown and cameraOffsetY > -MAX_CAM_X_PAN:
cameraOffsetY -= CAM_MOVE_SPEED
cameraOffsetY -= CAM_MOVE_SPEED
if cameraLeft and cameraOffsetX < MAX_CAM_Y_PAN:
if cameraLeft and cameraOffsetX < MAX_CAM_Y_PAN:
cameraOffsetX += CAM_MOVE_SPEED
cameraOffsetX += CAM_MOVE_SPEED
elif cameraRight and cameraOffsetX > -MAX_CAM_Y_PAN:
elif cameraRight and cameraOffsetX > -MAX_CAM_Y_PAN:
cameraOffsetX -= CAM_MOVE_SPEED
cameraOffsetX -= CAM_MOVE_SPEED
# Adjust mapSurf's Rect object based on the camera offset.
mapSurfRect = mapSurf.get_rect()
mapSurfRect = mapSurf.get_rect()
mapSurfRect.center = (HALF_WINWIDTH + cameraOffsetX, HALF_WINHEIGHT + cameraOffsetY)
mapSurfRect.center = (win_w_half + cameraOffsetX, win_h_half + cameraOffsetY)
# Draw mapSurf to the DISPLAYSURF Surface object.
screen.blit(mapSurf, mapSurfRect)
DISPLAYSURF.blit(mapSurf, mapSurfRect)
DISPLAYSURF.blit(levelSurf, levelRect)
screen.blit(levelSurf, levelRect)
stepSurf = BASICFONT.render('Steps: %s' % (gameStateObj['stepCounter']), 1, TEXTCOLOR)
stepSurf = basic_font.render('Steps: %s' % (gameStateObj['stepCounter']), 1, txt_color)
stepRect = stepSurf.get_rect()
stepRect = stepSurf.get_rect()
stepRect.bottomleft = (20, WINHEIGHT - 10)
stepRect.bottomleft = (20, round(win_h - font_size * 4 / 3))
DISPLAYSURF.blit(stepSurf, stepRect)
screen.blit(stepSurf, stepRect)
if cheat_entered == cheatcode != '':
levelIsComplete = True
if levelIsComplete:
if levelIsComplete:
# is solved, show the "Solved!" image until the player
# has pressed a key.
solvedRect = IMAGESDICT['solved'].get_rect()
solvedRect.center = (HALF_WINWIDTH, HALF_WINHEIGHT)
DISPLAYSURF.blit(IMAGESDICT['solved'], solvedRect)
if keyPressed:
old_w = image_dict['solved'].get_width()
return 'solved'
old_h = image_dict['solved'].get_height()
pygame.display.update() # draw DISPLAYSURF to the screen.
new_w = round(win_w / 2)
FPSCLOCK.tick()
new_h = round(old_h * new_w / old_w)
solved_img = pygame.transform.scale(image_dict['solved'], (new_w, new_h))
solvedRect = solved_img.get_rect()
solvedRect.x = round(win_w / 12)
solvedRect.y = round(win_h / 10)
solved_overlay = lvl_complete_blurry(solved_img, solvedRect)
if not solved_shown:
level_sound.play()
for i in range(0, 256, 4):
for event in pygame.event.get():
if event.type == QUIT:
pause_screen()
elif event.type == KEYDOWN:
if event.key == K_ESCAPE:
pause_screen()
currentImage = 0
return 'solved'
solved_overlay.set_alpha(i)
screen.blit(solved_overlay, (0, 0))
pygame.display.update()
fps_clock.tick(64)
solved_shown = True
else:
screen.blit(solved_overlay, (0, 0))
pygame.display.update()
fps_clock.tick()
def isWall(mapObj, x, y):
def isWall(mapObj, x, y):
"""Returns True if the (x, y) position on
the map is a wall, otherwise return False."""
if x < 0 or x >= len(mapObj) or y < 0 or y >= len(mapObj[x]):
if x < 0 or x >= len(mapObj) or y < 0 or y >= len(mapObj[x]):
return False # x and y aren't actually on the map.
return False
elif mapObj[x][y] in ('#', 'x'):
elif mapObj[x][y] in ('#', 'x'):
return True # wall is blocking
return True
return False
return False
def decorateMap(mapObj, startxy):
def decorateMap(mapObj, start_xy):
"""Makes a copy of the given map object and modifies it.
start_x, start_y = start_xy
Here is what is done to it:
* Walls that are corners are turned into corner pieces.
* The outside/inside floor tile distinction is made.
* Tree/rock decorations are randomly added to the outside tiles.
Returns the decorated map object."""
startx, starty = startxy # Syntactic sugar
# Copy the map object so we don't modify the original passed
mapObjCopy = copy.deepcopy(mapObj)
mapObjCopy = copy.deepcopy(mapObj)
# Remove the non-wall characters from the map data
for x in range(len(mapObjCopy)):
for x in range(len(mapObjCopy)):
for y in range(len(mapObjCopy[0])):
for y in range(len(mapObjCopy[0])):
if mapObjCopy[x][y] in ('$', '.', '@', '+', '*'):
if mapObjCopy[x][y] in ('$', '.', '@', '+', '*'):
mapObjCopy[x][y] = ' '
mapObjCopy[x][y] = ' '
# Flood fill to determine inside/outside floor tiles.
floodFill(mapObjCopy, start_x, start_y, ' ', 'o')
floodFill(mapObjCopy, startx, starty, ' ', 'o')
# Convert the adjoined walls into corner tiles.
for x in range(len(mapObjCopy)):
for x in range(len(mapObjCopy)):
for y in range(len(mapObjCopy[0])):
for y in range(len(mapObjCopy[0])):
if mapObjCopy[x][y] == '#':
if mapObjCopy[x][y] == ' ' and random.randint(0, 99) < grass_decoration_percentage:
if (isWall(mapObjCopy, x, y-1) and isWall(mapObjCopy, x+1, y)) or \
mapObjCopy[x][y] = random.choice(list(grass_deco_mapping.keys()))
(isWall(mapObjCopy, x+1, y) and isWall(mapObjCopy, x, y+1)) or \
(isWall(mapObjCopy, x, y+1) and isWall(mapObjCopy, x-1, y)) or \
(isWall(mapObjCopy, x-1, y) and isWall(mapObjCopy, x, y-1)):
mapObjCopy[x][y] = 'x'
elif mapObjCopy[x][y] == ' ' and random.randint(0, 99) < OUTSIDE_DECORATION_PCT:
mapObjCopy[x][y] = random.choice(list(OUTSIDEDECOMAPPING.keys()))
return mapObjCopy
return mapObjCopy
def isBlocked(mapObj, gameStateObj, x, y):
def isBlocked(mapObj, gameStateObj, x, y):
"""Returns True if the (x, y) position on the map is
blocked by a wall or star, otherwise return False."""
if isWall(mapObj, x, y):
if isWall(mapObj, x, y):
return True
return True
elif x < 0 or x >= len(mapObj) or y < 0 or y >= len(mapObj[x]):
elif x < 0 or x >= len(mapObj) or y < 0 or y >= len(mapObj[x]):
return True # x and y aren't actually on the map.
return True
elif (x, y) in gameStateObj['stars']:
elif (x, y) in gameStateObj['pixels']:
return True # a star is blocking
return True
return False
return False
def makeMove(mapObj, gameStateObj, playerMoveTo):
def makeMove(mapObj, gameStateObj, playerMoveTo):
"""Given a map and game state object, see if it is possible for the
player_x, player_y = gameStateObj['player']
player to make the given move. If it is, then change the player's
position (and the position of any pushed star). If not, do nothing.
Returns True if the player moved, otherwise False."""
# Make sure the player can move in the direction they want.
playerx, playery = gameStateObj['player']
# This variable is "syntactic sugar". Typing "stars" is more
pixels = gameStateObj['pixels']
# readable than typing "gameStateObj['stars']" in our code.
stars = gameStateObj['stars']
# The code for handling each of the directions is so similar aside
# from adding or subtracting 1 to the x/y coordinates. We can
# simplify it by using the xOffset and yOffset variables.
if playerMoveTo == UP:
if playerMoveTo == UP:
xOffset = 0
xOffset = 0
yOffset = -1
yOffset = -1
elif playerMoveTo == RIGHT:
elif playerMoveTo == RIGHT:
xOffset = 1
xOffset = 1
yOffset = 0
yOffset = 0
elif playerMoveTo == DOWN:
elif playerMoveTo == DOWN:
xOffset = 0
xOffset = 0
yOffset = 1
yOffset = 1
elif playerMoveTo == LEFT:
elif playerMoveTo == LEFT:
xOffset = -1
xOffset = -1
yOffset = 0
yOffset = 0
# See if the player can move in that direction.
if isWall(mapObj, player_x + xOffset, player_y + yOffset):
if isWall(mapObj, playerx + xOffset, playery + yOffset):
return False
return False
else:
else:
if (playerx + xOffset, playery + yOffset) in stars:
if (player_x + xOffset, player_y + yOffset) in pixels:
# There is a star in the way, see if the player can push it.
if not isBlocked(mapObj, gameStateObj, playerx + (xOffset*2), playery + (yOffset*2)):
if not isBlocked(mapObj, gameStateObj, player_x + (xOffset * 2), player_y + (yOffset * 2)):
# Move the star.
ind = stars.index((playerx + xOffset, playery + yOffset))
ind = pixels.index((player_x + xOffset, player_y + yOffset))
stars[ind] = (stars[ind][0] + xOffset, stars[ind][1] + yOffset)
pixels[ind] = (pixels[ind][0] + xOffset, pixels[ind][1] + yOffset)
else:
else:
return False
return False
# Move the player upwards.
gameStateObj['player'] = (playerx + xOffset, playery + yOffset)
gameStateObj['player'] = (player_x + xOffset, player_y + yOffset)
return True
return True
def startScreen():
def startScreen():
"""Display the start screen (which has the title and instructions)
title_img = image_dict['title']
until the player presses a key. Returns None."""
# Position the title image.
title_w = title_img.get_width()
titleRect = IMAGESDICT['title'].get_rect()
title_h = title_img.get_height()
topCoord = 50 # topCoord tracks where to position the top of the text
titleRect.top = topCoord
titleRect.centerx = HALF_WINWIDTH
topCoord += titleRect.height
# Unfortunately, Pygame's font & text system only shows one line at
upper_limit = title_transform[0][1]
# a time, so we can't use strings with \n newline characters in them.
lower_limit = title_transform[0][0]
# So we will use a list with each line in it.
instructionText = ['Push the stars over the marks.',
'Arrow keys to move, WASD for camera control, P to change character.',
'Backspace to reset level, Esc to quit.',
'N for next level, B to go back a level.']
# Start with drawing a blank color to the entire window:
fps = 60
DISPLAYSURF.fill(BGCOLOR)
# Draw the title image to the window:
counter = title_transform[1]
DISPLAYSURF.blit(IMAGESDICT['title'], titleRect)
counter_limit = 100
check_divisibilty_of = counter
# Position and draw the text.
title_image_size_factor = lower_limit
for i in range(len(instructionText)):
size_change_factor = +1
instSurf = BASICFONT.render(instructionText[i], 1, TEXTCOLOR)
instRect = instSurf.get_rect()
topCoord += 10 # 10 pixels will go in between each line of text.
instRect.top = topCoord
instRect.centerx = HALF_WINWIDTH
topCoord += instRect.height # Adjust for the height of the line.
DISPLAYSURF.blit(instSurf, instRect)
while True: # Main loop for the start screen.
new_title_w = round(win_w * lower_limit / 100)
new_title_h = round(title_h * new_title_w / title_w)
title_x = round((win_w - new_title_w) / 2)
title_yy = round(win_h * 2 / 7)
instructionText = ['Push all the Pixel-Crystals in the portals!',
'',
'Movement: WASD/Arrow keys',
'Camera control: I-J-K-L',
'Exit game: Escape',
'Reset level: Backspace',
'Continue: Enter']
while True:
if counter % check_divisibilty_of == 0:
if title_image_size_factor <= lower_limit:
size_change_factor = +1
if title_image_size_factor >= upper_limit:
size_change_factor = -1
title_image_size_factor += size_change_factor
new_title_w = win_w * title_image_size_factor / 100
new_title_h = title_h * new_title_w / title_w
title_x = round((win_w - new_title_w) / 2)
title_y = title_yy - round(new_title_h / 2)
screen.fill(bg_color)
screen.blit(pygame.transform.scale(title_img, (new_title_w, new_title_h)),
(title_x, title_y - round(new_title_h / 2)))
topCoord = round(win_h * 4 / 9)
for i in range(len(instructionText)):
instSurf = basic_font.render(instructionText[i], 1, txt_color)
instRect = instSurf.get_rect()
topCoord += 10
instRect.top = topCoord
instRect.centerx = win_w_half
topCoord += instRect.height
screen.blit(instSurf, instRect)
cur_func()
pygame.display.update()
for event in pygame.event.get():
for event in pygame.event.get():
if event.type == QUIT:
if event.type == QUIT:
terminate()
terminate()
elif event.type == KEYDOWN:
elif event.type == KEYDOWN:
if event.key == K_ESCAPE:
if event.key == K_ESCAPE:
terminate()
terminate()
return # user has pressed a key, so return.
elif event.key == K_RETURN:
return
# Display the DISPLAYSURF contents to the actual screen.
fps_clock.tick(fps)
counter += 1
if counter > counter_limit:
counter = 2
def cutscene(state: str):
if state == 'start':
img = image_dict['cut_in']
elif state == 'over':
img = image_dict['cut_out']
else:
return
img_w_old = img.get_width()
img_h_old = img.get_height()
img_rect = img.get_rect()
img_rect.w = win_w
img_rect.h = round(img_h_old * img_rect.w / img_w_old, 2)
img_rect.x = 0
img_rect.y = round(win_h / 2 - img_rect.h / 2)
if win_w / win_h <= img_w_old / img_h_old:
img_rect.w = win_w
img_rect.h = round(img_h_old * img_rect.w / img_w_old, 2)
img_rect.x = 0
img_rect.y = round(win_h / 2 - img_rect.h / 2)
elif win_w / win_h > img_w_old / img_h_old:
img_rect.h = win_h
img_rect.w = round(img_w_old * img_rect.h / img_h_old)
img_rect.x = round(win_w / 2 - img_rect.w / 2)
img_rect.y = 0
alpha = 0
img = pygame.transform.scale(img, (img_rect.w, img_rect.h))
for alpha in range(0, 256, 8):
for event in pygame.event.get():
if event.type == QUIT:
pause_screen()
elif event.type == KEYDOWN:
if event.key == K_ESCAPE:
pause_screen()
else:
done = True
img.set_alpha(alpha)
pygame.draw.rect(screen, color['blacker'], pygame.Rect(0, 0, win_w, win_h))
screen.blit(img, img_rect)
pygame.display.update()
pygame.display.update()
FPSCLOCK.tick()
fps_clock.tick(32)
img.set_alpha(255)
done = False
while not done:
for event in pygame.event.get():
if event.type == QUIT:
pause_screen()
elif event.type == KEYDOWN:
if event.key == K_ESCAPE:
pause_screen()
else:
done = True
pygame.draw.rect(screen, color['blacker'], pygame.Rect(0, 0, win_w, win_h))
screen.blit(img, img_rect)
pygame.display.update()
fps_clock.tick(60)
return
def readLevelsFile(filename):
def creds():
assert os.path.exists(filename), 'Cannot find the level file: %s' % (filename)
img = image_dict['creds']
mapFile = open(filename, 'r')
# Each level must end with a blank line
content = mapFile.readlines() + ['\r\n']
mapFile.close()
levels = [] # Will contain a list of level objects.
img_w_old = img.get_width()
img_h_old = img.get_height()
img_rect = img.get_rect()
img_rect.w = win_w
img_rect.h = round(img_h_old * img_rect.w / img_w_old, 2)
img_rect.x = 0
img_rect.y = round(win_h / 2 - img_rect.h / 2)
if win_w / win_h <= img_w_old / img_h_old:
img_rect.w = win_w
img_rect.h = round(img_h_old * img_rect.w / img_w_old, 2)
img_rect.x = 0
img_rect.y = round(win_h / 2 - img_rect.h / 2)
elif win_w / win_h > img_w_old / img_h_old:
img_rect.h = win_h
img_rect.w = round(img_w_old * img_rect.h / img_h_old)
img_rect.x = round(win_w / 2 - img_rect.w / 2)
img_rect.y = 0
alpha = 0
img = pygame.transform.scale(img, (img_rect.w, img_rect.h))
for alpha in range(0, 256, 8):
for event in pygame.event.get():
if event.type == QUIT:
pass
img.set_alpha(alpha)
pygame.draw.rect(screen, color['blacker'], pygame.Rect(0, 0, win_w, win_h))
screen.blit(img, img_rect)
pygame.display.update()
fps_clock.tick(32)
img.set_alpha(255)
done = False
while not done:
for event in pygame.event.get():
if event.type == QUIT:
done = True
elif event.type == KEYDOWN:
done = True
pygame.draw.rect(screen, color['blacker'], pygame.Rect(0, 0, win_w, win_h))
screen.blit(img, img_rect)
pygame.display.update()
fps_clock.tick(60)
return
def cur_func():
cur_x, cur_y = pygame.mouse.get_pos()
cur_rect = cursor_img.get_rect()
cur_rect.x = round(cur_x - cur_rect.w / 2)
cur_rect.y = round(cur_y - cur_rect.h / 2)
screen.blit(cursor_img, cur_rect)
def readLevelsFile():
# FORMAT:',
# @ - Steve
# $ - Pixel
# . - Goal
# # - Wall
# <space> - space
content = [
' ',
' ######',
' # $.#',
' #@ #',
' ######',
' ',
'',
' ',
' #########',
' # #',
' # . $ #',
' # @ #',
' # $ . #',
' # #',
' #########',
' ',
'',
'#########',
'# #',
'# ##### #',
'# # #',
'##### # #',
'# # #',
'# #### #',
' # @#.$ #',
' ### #',
' ####',
'',
' ',
' ####### ',
' #@# #',
' # # $ #',
' # ## ## ',
' ## .# ',
' ### # ',
' ## ',
' ',
'',
' ',
' ###########',
' # #',
' # . . . #',
' ## ##### ##',
' # $ $ $ #',
' # @ #',
' #########',
' ',
''
]
levels = []
levelNum = 0
levelNum = 0
mapTextLines = [] # contains the lines for a single level's map.
mapTextLines = []
mapObj = [] # the map object made from the data in mapTextLines
mapObj = []
for lineNum in range(len(content)):
for lineNum in range(len(content)):
# Process each line that was in the level file.
line = content[lineNum].rstrip('\r\n')
line = content[lineNum].rstrip('\r\n')
if ';' in line:
# Ignore the ; lines, they're comments in the level file.
line = line[:line.find(';')]
if line != '':
if line != '':
# This line is part of the map.
mapTextLines.append(line)
mapTextLines.append(line)
elif line == '' and len(mapTextLines) > 0:
elif line == '' and len(mapTextLines) > 0:
# A blank line indicates the end of a level's map in the file.
# Convert the text in mapTextLines into a level object.
# Find the longest row in the map.
maxWidth = -1
maxWidth = -1
for i in range(len(mapTextLines)):
for i in range(len(mapTextLines)):
if len(mapTextLines[i]) > maxWidth:
if len(mapTextLines[i]) > maxWidth:
maxWidth = len(mapTextLines[i])
maxWidth = len(mapTextLines[i])
# Add spaces to the ends of the shorter rows. This
# ensures the map will be rectangular.
for i in range(len(mapTextLines)):
for i in range(len(mapTextLines)):
mapTextLines[i] += ' ' * (maxWidth - len(mapTextLines[i]))
mapTextLines[i] += ' ' * (maxWidth - len(mapTextLines[i]))
# Convert mapTextLines to a map object.
for x in range(len(mapTextLines[0])):
for x in range(len(mapTextLines[0])):
mapObj.append([])
mapObj.append([])
for y in range(len(mapTextLines)):
for y in range(len(mapTextLines)):
for x in range(maxWidth):
for x in range(maxWidth):
mapObj[x].append(mapTextLines[y][x])
mapObj[x].append(mapTextLines[y][x])
# Loop through the spaces in the map and find the @, ., and $
start_x = None
# characters for the starting game state.
start_y = None
startx = None # The x and y for the player's starting position
goals = []
starty = None
pixels = []
goals = [] # list of (x, y) tuples for each goal.
stars = [] # list of (x, y) for each star's starting position.
for x in range(maxWidth):
for x in range(maxWidth):
for y in range(len(mapObj[x])):
for y in range(len(mapObj[x])):
if mapObj[x][y] in ('@', '+'):
if mapObj[x][y] == '@':
# '@' is player, '+' is player & goal
start_x = x
startx = x
start_y = y
starty = y
if mapObj[x][y] == '.':
if mapObj[x][y] in ('.', '+', '*'):
# '.' is goal, '*' is star & goal
goals.append((x, y))
goals.append((x, y))
if mapObj[x][y] in ('$', '*'):
if mapObj[x][y] == '$':
# '$' is star
pixels.append((x, y))
stars.append((x, y))
# Basic level design sanity checks:
assert startx != None and starty != None, 'Level %s (around line %s) in %s is missing a "@" or "+" to mark the start point.' % (levelNum+1, lineNum, filename)
assert len(goals) > 0, 'Level %s (around line %s) in %s must have at least one goal.' % (levelNum+1, lineNum, filename)
assert len(stars) >= len(goals), 'Level %s (around line %s) in %s is impossible to solve. It has %s goals but only %s stars.' % (levelNum+1, lineNum, filename, len(goals), len(stars))
# Create level object and starting game state object.
gameStateObj = {'player': (start_x, start_y),
gameStateObj = {'player': (startx, starty),
'stepCounter': 0,
'stepCounter': 0,
'stars': stars}
'pixels': pixels}
levelObj = {'width': maxWidth,
levelObj = {'width': maxWidth,
'height': len(mapObj),
'height': len(mapObj),
'mapObj': mapObj,
'mapObj': mapObj,
'goals': goals,
'goals': goals,
'startState': gameStateObj}
'startState': gameStateObj}
levels.append(levelObj)
levels.append(levelObj)
# Reset the variables for reading the next map.
mapTextLines = []
mapTextLines = []
mapObj = []
mapObj = []
gameStateObj = {}
gameStateObj = {}
levelNum += 1
levelNum += 1
return levels
return levels
def floodFill(mapObj, x, y, oldCharacter, newCharacter):
def floodFill(mapObj, x, y, oldCharacter, newCharacter):
"""Changes any values matching oldCharacter on the map object to
newCharacter at the (x, y) position, and does the same for the
positions to the left, right, down, and up of (x, y), recursively."""
# In this game, the flood fill algorithm creates the inside/outside
# floor distinction. This is a "recursive" function.
# For more info on the Flood Fill algorithm, see:
# http://en.wikipedia.org/wiki/Flood_fill
if mapObj[x][y] == oldCharacter:
if mapObj[x][y] == oldCharacter:
mapObj[x][y] = newCharacter
mapObj[x][y] = newCharacter
if x < len(mapObj) - 1 and mapObj[x+1][y] == oldCharacter:
if x < len(mapObj) - 1 and mapObj[x + 1][y] == oldCharacter:
floodFill(mapObj, x+1, y, oldCharacter, newCharacter) # call right
floodFill(mapObj, x + 1, y, oldCharacter, newCharacter)
if x > 0 and mapObj[x-1][y] == oldCharacter:
if x > 0 and mapObj[x - 1][y] == oldCharacter:
floodFill(mapObj, x-1, y, oldCharacter, newCharacter) # call left
floodFill(mapObj, x - 1, y, oldCharacter, newCharacter)
if y < len(mapObj[x]) - 1 and mapObj[x][y+1] == oldCharacter:
if y < len(mapObj[x
floodFill(mapObj, x, y+1, oldCharacter, newCharacter) # call down
if y > 0 and mapObj[x][y-1] == oldCharacter:
floodFill(mapObj, x, y-1, oldCharacter, newCharacter) # call up
def drawMap(mapObj, gameStateObj, goals):
"""Draws the map to a Surface object, including the player and
stars. This function does not call pygame.display.update(), nor
does it draw the "Level" and "Steps" text in the corner."""
# mapSurf will be the single Surface object that the tiles are drawn
# on, so that it is easy to position the entire map on the DISPLAYSURF
# Surface object. First, the width and height must be calculated.
mapSurfWidth = len(mapObj) * TILEWIDTH
mapSurfHeight = (len(mapObj[0]) - 1) * TILEFLOORHEIGHT + TILEHEIGHT
mapSurf = pygame.Surface((mapSurfWidth, mapSurfHeight))
mapSurf.fill(BGCOLOR) # start with a blank color on the surface.
# Draw the tile sprites onto this surface.
for x in range(len(mapObj)):
for y in range(len(mapObj[x])):
spaceRect = pygame.Rect((x * TILEWIDTH, y * TILEFLOORHEIGHT, TILEWIDTH, TILEHEIGHT))
if mapObj[x][y] in TILEMAPPING:
baseTile = TILEMAPPING[mapObj[x][y]]
elif mapObj[x][y] in OUTSIDEDECOMAPPING:
baseTile = TILEMAPPING[' ']
# First draw the base ground/wall tile.
mapSurf.blit(baseTile, spaceRect)
if mapObj[x][y] in OUTSIDEDECOMAPPING:
# Draw any tree/rock decorations that are on this tile.
mapSurf.blit(OUTSIDEDECOMAPPING[mapObj[x][y]], spaceRect)
elif (x, y) in gameStateObj['stars']:
if (x, y) in goals:
# A goal AND star are on this space, draw goal first.
mapSurf.blit(IMAGESDICT['covered goal'], spaceRect)
# Then draw the star sprite.
mapSurf.blit(IMAGESDICT['star'], spaceRect)
elif (x, y) in goals:
# Draw a goal without a star on it.
mapSurf.blit(IMAGESDICT['uncovered goal'], spaceRect)
# Last draw the player on the board.
if (x, y) == gameStateObj['player']:
# Note: The value "currentImage" refers
# to a key in "PLAYERIMAGES" which has the
# specific player image we want to show.
mapSurf.blit(PLAYERIMAGES[currentImage], spaceRect)
return mapSurf
def isLevelFinished(levelObj, gameStateObj):
"""Returns True if all the goals have stars in them."""
for goal in levelObj['goals']:
if goal not in gameStateObj['stars']:
# Found a space with a goal but no star on it.
return False
return True
def terminate():
pygame.quit()
sys.exit()
if __name__ == '__main__':
main()