CS Pro P-1
CS Pro P-1
C O M P UT E R S C IE N C E
I N V E S T IG A T O R Y P R O J EC T
PAGE 1
INTRODUCTION
The Mario Game In Python, This Mario Game Code In Python is
design in Graphical User Interface(GUI ) that uses PyGame library.
Talking about the gameplay, the story is, The princess toadstool of
the mushroom kingdom has been kidnapped by the notorious King
Koopa and the toads of the mushroom kingdom have been held
captive in the many castles of King Koopa. It's up to Mario to save
the princess and defeat King Koopa and his minions.
PAGE 2
SETTING UP THE ENVIRONMENT
We want to set up our game environment so that we can start
designing our game. At the highest level, we’ll have three modules in
your code: the game module, the level module, and the sprite
module. The game module will contain game logic (i.e., what
happens when a player dies), and the level module will include game
design (i.e., what the level looks like).
The sprite module will contain our sprites (i.e., your characters,
coins, blocks, etc.). It’s important to separate our game design and
game logic because we want to minimize the dependencies between
our modules so that they are easier to understand and modify.
PAGE 3
REQUIREMENTS
REQUIRED MODULES:
1. Pygame
2. Scipy
MINIMUM REQUIREMENT:
S.NO NAME SOFTWARE
1 Operating Windows 10
System
2 Processor 2.4 GHz Dual
Core
3 Memory 4 GB RAM
4 Graphics Intel HD
Graphics 4000
5 Storage 2GB available
space
RECOMMENDED REQUIREMENTS:
S.NO NAME SOFTWARE
1 Operating Windows 10
System
2 Processor 3.0 GHz Quad
Core
3 Memory 8 GB RAM
4 Graphics NVIDIA GeForce
GTX 660
5 Storage 2GB available
space
PAGE 4
DESIGNING THE LEVELS AND SPRITES
Now that we have our environment set up for the Mario game in
Python, it’s time to create the level for the game. A level represents
the game space that includes the general environment and obstacles
that the player needs to overcome (e.g., ground, grass, rocks, trees,
mountains, vines, clouds, and rivers). We can create the level using
a graphical editor like Tiled. There are also many visual-level design
tools available online.
Once after the level is designed, we will need to save it as an image
file (.png) and then load it into your Python IDE.
PAGE 5
MAKING THE LEVEL MORE INTERACTIVE
To make the level more interactive add sounds whenever a power-up
is collected, or the player picks up a coin. Also, make vines come
down from the top of the level when a player goes down a level. We
can make ground disappear when a player goes down a level and
make rocks fall down from the top of the level.
We can also make vines come down from the bottom of the level
when the player goes up a level. We can make the ground appear
when a player goes up a level, and rocks appear at the bottom when
a player goes down a level. We can also make water flow from the
top to the bottom when a player goes down a level .
LEVEL-1
LEVEL-2
PAGE 6
ADDING THE TITLE SCREEN AND GAME
OVER SCREEN
TITLE SCREEN:
ON-GAME SCREEN:
PAGE 7
SOURCE CODE
MAIN PY FILE:
import pygame
def main():
pygame.init()
screen = pygame.display.set_mode(windowSize)
max_frame_rate = 60
sound = Sound()
menu.update()
clock = pygame.time.Clock()
if mario.pause:
mario.pauseObj.update()
else:
level.drawLevel(mario.camera)
dashboard.update()
mario.update()
pygame.display.update()
clock.tick(max_frame_rate)
PAGE 8
return 'restart'
COMPILE FILE:
import py2exe
import glob
setup(
# this is the file that is run when you start the game from the command line.
console=["main.py"],
# data files - these are the non-python files, like images and sounds
data_files=[
("sprites", glob.glob("sprites\\*.json")),
("levels", glob.glob("levels\\*.json")),
("", ["settings.json"]),
],
ANIMATION:
class Animation:
self.images = images
self.timer = 0
self.index = 0
self.image = self.images[self.index]
self.idleSprite = idleSprite
self.airSprite = airSprite
self.deltaTime = deltaTime
def update(self):
self.timer += 1
if self.timer % self.deltaTime == 0:
self.index += 1
else:
PAGE 9
self.index = 0
self.image = self.images[self.index]
def idle(self):
self.image = self.idleSprite
def inAir(self):
self.image = self.airSprite
CAMERA:
class Camera:
self.entity = entity
self.x = self.pos.x * 32
self.y = self.pos.y * 32
def move(self):
xPosFloat = self.entity.getPosIndexAsFloat().x
self.pos.x = -xPosFloat + 10
self.x = self.pos.x * 32
self.y = self.pos.y * 32
COLLIDER:
class Collider:
self.entity = entity
self.level = level.level
self.levelObj = level
self.result = []
def checkX(self):
if self.leftLevelBorderReached() or self.rightLevelBorderReached():
return
try:
rows = [
self.level[self.entity.getPosIndex().y],
PAGE 10
self.level[self.entity.getPosIndex().y + 1],
self.level[self.entity.getPosIndex().y + 2],
except Exception:
return
if self.entity.rect.colliderect(tile.rect):
if self.entity.vel.x > 0:
self.entity.rect.right = tile.rect.left
self.entity.vel.x = 0
if self.entity.vel.x < 0:
self.entity.rect.left = tile.rect.right
self.entity.vel.x = 0
def checkY(self):
self.entity.onGround = False
try:
rows = [
self.level[self.entity.getPosIndex().y],
self.level[self.entity.getPosIndex().y + 1],
self.level[self.entity.getPosIndex().y + 2],
except Exception:
try:
self.entity.gameOver()
except Exception:
self.entity.alive = None
return
PAGE 11
if tile.rect is not None:
if self.entity.rect.colliderect(tile.rect):
if self.entity.vel.y > 0:
self.entity.onGround = True
self.entity.rect.bottom = tile.rect.top
self.entity.vel.y = 0
if "JumpTrait" in self.entity.traits:
self.entity.traits["JumpTrait"].reset()
if "bounceTrait" in self.entity.traits:
self.entity.traits["bounceTrait"].reset()
if self.entity.vel.y < 0:
self.entity.rect.top = tile.rect.bottom
self.entity.vel.y = 0
def rightLevelBorderReached(self):
self.entity.rect.x = (self.levelObj.levelLength - 1) * 32
self.entity.vel.x = 0
return True
def leftLevelBorderReached(self):
if self.entity.rect.x < 0:
self.entity.rect.x = 0
self.entity.vel.x = 0
return True
DASHBOARD :
import pygame
class Dashboard(Font):
self.state = "menu"
self.screen = screen
PAGE 12
self.levelName = ""
self.points = 0
self.coins = 0
self.ticks = 0
self.time = 0
def update(self):
if self.state != "menu":
# update Time
self.ticks += 1
if self.ticks == 60:
self.ticks = 0
self.time += 1
x += size//2
else:
x += size
def coinString(self):
return "{:02d}".format(self.coins)
def pointString(self):
return "{:06d}".format(self.points)
def timeString(self):
return "{:03d}".format(self.time)
PAGE 13
ENTITY COLLIDER:
class EntityCollider:
self.entity = entity
if self.entity.rect.colliderect(target.rect):
if (
rect1.collidepoint(rect2.bottomleft)
or rect1.collidepoint(rect2.bottomright)
or rect1.collidepoint(rect2.midbottom)
):
if rect2.collidepoint(
(rect1.midleft[0] / 2, rect1.midleft[1] / 2)
else:
if self.entity.vel.y > 0:
class CollisionState:
self.isColliding = _isColliding
self.isTop = _isTop
FONT:
import pygame
class Font(Spritesheet):
Spritesheet.__init__(self, filename=filePath)
PAGE 14
self.charSprites = self.loadFont()
def loadFont(self):
font = {}
row = 0
charAt = 0
if charAt == 16:
charAt = 0
row += 1
font.update(
char: self.image_at(
charAt,
row,
2,
colorkey=pygame.color.Color(0, 0, 0),
xTileSize=8,
yTileSize=8
charAt += 1
return font
GAUSSIANBLUR:
import pygame
class GaussianBlur:
self.kernel_size = kernelsize
pxa = pygame.surfarray.array3d(srfc)
PAGE 15
pygame.surfarray.blit_array(nSrfc, blurred)
del pxa
return nSrfc
INPUT:
import pygame
import sys
class Input:
self.mouseX = 0
self.mouseY = 0
self.entity = entity
def checkForInput(self):
events = pygame.event.get()
self.checkForKeyboardInput()
self.checkForMouseInput(events)
self.checkForQuitAndRestartInputEvents(events)
def checkForKeyboardInput(self):
pressedKeys = pygame.key.get_pressed()
self.entity.traits["goTrait"].direction = -1
self.entity.traits["goTrait"].direction = 1
else:
self.entity.traits['goTrait'].direction = 0
self.entity.traits['jumpTrait'].jump(isJumping)
self.entity.traits['goTrait'].boost = pressedKeys[K_LSHIFT]
if self.isRightMouseButtonPressed(events):
self.entity.levelObj.addKoopa(
PAGE 16
)
self.entity.levelObj.addGoomba(
self.entity.levelObj.addRedMushroom(
if self.isLeftMouseButtonPressed(events):
self.entity.levelObj.addCoin(
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
self.entity.pause = True
self.entity.pauseObj.createBackgroundBlur()
return self.checkMouse(events, 1)
return self.checkMouse(events, 3)
for e in events:
return True
return False
LEVELS:
import json
import pygame
PAGE 17
from classes.Tile import Tile
class Level:
self.sprites = Sprites()
self.dashboard = dashboard
self.sound = sound
self.screen = screen
self.level = None
self.levelLength = 0
self.entityList = []
data = json.load(jsonData)
self.loadLayers(data)
self.loadObjects(data)
self.loadEntities(data)
self.levelLength = data["length"]
try:
except:
PAGE 18
# if no entities in Level
pass
layers = []
for x in range(*data["level"]["layers"]["sky"]["x"]):
layers.append(
Tile(self.sprites.spriteCollection.get("sky"), None)
for y in range(*data["level"]["layers"]["sky"]["y"])
+[
Tile(
self.sprites.spriteCollection.get("ground"),
for y in range(*data["level"]["layers"]["ground"]["y"])
for x, y in data["level"]["objects"]["bush"]:
self.addBushSprite(x, y)
for x, y in data["level"]["objects"]["cloud"]:
self.addCloudSprite(x, y)
for x, y, z in data["level"]["objects"]["pipe"]:
self.addPipeSprite(x, y, z)
for x, y in data["level"]["objects"]["sky"]:
for x, y in data["level"]["objects"]["ground"]:
self.level[y][x] = Tile(
self.sprites.spriteCollection.get("ground"),
PAGE 19
pygame.Rect(x * 32, y * 32, 32, 32),
entity.update(cam)
if entity.alive is None:
self.entityList.remove(entity)
try:
if self.level[y][x].sprite.redrawBackground:
self.screen.blit(
self.sprites.spriteCollection.get("sky").image,
self.level[y][x].sprite.drawSprite(
x + camera.pos.x, y, self.screen
self.updateEntities(camera)
except IndexError:
return
try:
except IndexError:
return
try:
PAGE 20
# add pipe head
self.level[y][x] = Tile(
self.sprites.spriteCollection.get("pipeL"),
self.level[y][x + 1] = Tile(
self.sprites.spriteCollection.get("pipeR"),
self.sprites.spriteCollection.get("pipe2L"),
self.sprites.spriteCollection.get("pipe2R"),
except IndexError:
return
try:
self.level[y][x + 1] = Tile(
self.sprites.spriteCollection.get("bush_2"), None
self.level[y][x + 2] = Tile(
self.sprites.spriteCollection.get("bush_3"), None
except IndexError:
return
PAGE 21
def addCoinBox(self, x, y):
self.entityList.append(
CoinBox(
self.screen,
self.sprites.spriteCollection,
x,
y,
self.sound,
self.dashboard,
self.entityList.append(
RandomBox(
self.screen,
self.sprites.spriteCollection,
x,
y,
item,
self.sound,
self.dashboard,
self
self.entityList.append(
CoinBrick(
self.screen,
PAGE 22
self.sprites.spriteCollection,
x,
y,
self.sound,
self.dashboard
self.entityList.append(
self.entityList.append(
self.entityList.append(
MATHS:
class Vec2D:
self.x = x
self.y = y
MENU:
import json
import sys
import os
import pygame
class Menu:
self.screen = screen
PAGE 23
self.sound = sound
self.start = False
self.inSettings = False
self.state = 0
self.level = level
self.music = True
self.sfx = True
self.currSelectedLevel = 1
self.levelNames = []
self.inChoosingLevel = False
self.dashboard = dashboard
self.levelCount = 0
self.spritesheet = Spritesheet("./img/title_screen.png")
self.menu_banner = self.spritesheet.image_at(
0,
60,
2,
colorkey=[255, 0, 220],
ignoreTileSize=True,
xTileSize=180,
yTileSize=88,
self.menu_dot = self.spritesheet.image_at(
self.menu_dot2 = self.spritesheet.image_at(
self.loadSettings("./settings.json")
def update(self):
self.checkInput()
if self.inChoosingLevel:
return
PAGE 24
self.drawMenuBackground()
self.dashboard.update()
if not self.inSettings:
self.drawMenu()
else:
self.drawSettings()
def drawDot(self):
if self.state == 0:
elif self.state == 1:
elif self.state == 2:
try:
data = json.load(jsonData)
if data["sound"]:
self.music = True
self.sound.music_channel.play(self.sound.soundtrack, loops=-1)
else:
self.music = False
if data["sfx"]:
self.sfx = True
self.sound.allowSFX = True
else:
self.sound.allowSFX = False
PAGE 25
self.sfx = False
self.music = False
self.sound.allowSFX = False
self.sfx = False
self.saveSettings("./settings.json")
json.dump(data, outfile)
def drawMenu(self):
self.drawDot()
self.screen.blit(
self.level.sprites.spriteCollection.get("sky").image,
(x * 32, y * 32),
self.screen.blit(
self.level.sprites.spriteCollection.get("ground").image,
(x * 32, y * 32),
if withBanner:
self.screen.blit(
self.level.sprites.spriteCollection.get("mario_idle").image,
PAGE 26
(2 * 32, 12 * 32),
self.screen.blit(
self.screen.blit(
self.screen.blit(
self.screen.blit(
self.screen.blit(
def drawSettings(self):
self.drawDot()
if self.music:
else:
if self.sfx:
else:
def chooseLevel(self):
self.drawMenuBackground(False)
PAGE 27
self.inChoosingLevel = True
self.levelNames = self.loadLevelNames()
self.drawLevelChooser()
def drawLevelChooser(self):
j=0
offset = 75
textOffset = 90
if self.currSelectedLevel == i+1:
else:
if i < 3:
else:
j += 1
def loadLevelNames(self):
files = []
res = []
for r, d, f in os.walk("./levels"):
for file in f:
files.append(os.path.join(r, file))
for f in files:
res.append(os.path.split(f)[1].split(".")[0])
PAGE 28
self.levelCount = len(res)
return res
def checkInput(self):
events = pygame.event.get()
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
if self.inChoosingLevel or self.inSettings:
self.inChoosingLevel = False
self.inSettings = False
else:
pygame.quit()
sys.exit()
if self.inChoosingLevel:
if self.currSelectedLevel > 3:
self.currSelectedLevel -= 3
self.drawLevelChooser()
if self.state > 0:
self.state -= 1
if self.inChoosingLevel:
self.currSelectedLevel += 3
self.drawLevelChooser()
if self.state < 2:
self.state += 1
if self.currSelectedLevel > 1:
PAGE 29
self.currSelectedLevel -= 1
self.drawLevelChooser()
self.currSelectedLevel += 1
self.drawLevelChooser()
if self.inChoosingLevel:
self.inChoosingLevel = False
self.dashboard.state = "start"
self.dashboard.time = 0
self.level.loadLevel(self.levelNames[self.currSelectedLevel-1])
self.dashboard.levelName = self.levelNames[self.currSelectedLevel-1].split("Level")[1]
self.start = True
return
if not self.inSettings:
if self.state == 0:
self.chooseLevel()
elif self.state == 1:
self.inSettings = True
self.state = 0
elif self.state == 2:
pygame.quit()
sys.exit()
else:
if self.state == 0:
if self.music:
self.sound.music_channel.stop()
self.music = False
else:
self.sound.music_channel.play(self.sound.soundtrack, loops=-1)
self.music = True
self.saveSettings("./settings.json")
PAGE 30
elif self.state == 1:
if self.sfx:
self.sound.allowSFX = False
self.sfx = False
else:
self.sound.allowSFX = True
self.sfx = True
self.saveSettings("./settings.json")
elif self.state == 2:
self.inSettings = False
pygame.display.update()
PAUSE:
import pygame
import sys
class Pause:
self.screen = screen
self.entity = entity
self.dashboard = dashboard
self.state = 0
self.spritesheet = Spritesheet("./img/title_screen.png")
self.dot = self.spritesheet.image_at(
self.gray_dot = self.spritesheet.image_at(
def update(self):
PAGE 31
self.dashboard.drawText("CONTINUE", 150, 280, 32)
self.drawDot()
pygame.display.update()
self.checkInput()
def drawDot(self):
if self.state == 0:
elif self.state == 1:
def checkInput(self):
events = pygame.event.get()
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RETURN:
if self.state == 0:
self.entity.pause = False
elif self.state == 1:
self.entity.restart = True
if self.state > 0:
self.state -= 1
if self.state < 1:
self.state += 1
def createBackgroundBlur(self):
SOUND:
PAGE 32
from pygame import mixer
class Sound:
def __init__(self):
self.music_channel = mixer.Channel(0)
self.music_channel.set_volume(0.2)
self.sfx_channel = mixer.Channel(1)
self.sfx_channel.set_volume(0.2)
self.allowSFX = True
self.soundtrack = mixer.Sound("./sfx/main_theme.ogg")
self.coin = mixer.Sound("./sfx/coin.ogg")
self.bump = mixer.Sound("./sfx/bump.ogg")
self.stomp = mixer.Sound("./sfx/stomp.ogg")
self.jump = mixer.Sound("./sfx/small_jump.ogg")
self.death = mixer.Sound("./sfx/death.wav")
self.kick = mixer.Sound("./sfx/kick.ogg")
self.brick_bump = mixer.Sound("./sfx/brick-bump.ogg")
self.powerup = mixer.Sound('./sfx/powerup.ogg')
self.powerup_appear = mixer.Sound('./sfx/powerup_appears.ogg')
self.pipe = mixer.Sound('./sfx/pipe.ogg')
if self.allowSFX:
self.sfx_channel.play(sfx)
self.music_channel.play(music)
SPRITE:
class Sprite:
self.image = image
self.colliding = colliding
self.animation = animation
self.redrawBackground = redrawBackground
PAGE 33
if self.animation is None:
screen.blit(self.image, dimensions)
else:
self.animation.update()
screen.blit(self.animation.image, dimensions)
SPRITESHEET:
import pygame
class Spritesheet(object):
try:
self.sheet = pygame.image.load(filename)
self.sheet = pygame.image.load(filename)
if not self.sheet.get_alpha():
self.sheet.set_colorkey((0, 0, 0))
except pygame.error:
raise SystemExit
xTileSize=16, yTileSize=16):
if ignoreTileSize:
else:
image = pygame.Surface(rect.size)
if colorkey == -1:
image.set_colorkey(colorkey, pygame.RLEACCEL)
return pygame.transform.scale(
TILE:
PAGE 34
import pygame
class Tile:
self.sprite = sprite
self.rect = rect
try:
except Exception:
pass
COINS:
class Coin(EntityBase):
self.screen = screen
self.spriteCollection = spriteCollection
self.animation = copy(self.spriteCollection.get("coin").animation)
self.type = "Item"
if self.alive:
self.animation.update()
COINBOX:
class CoinBox(EntityBase):
self.screen = screen
PAGE 35
self.spriteCollection = spriteCollection
self.animation = copy(self.spriteCollection.get("CoinBox").animation)
self.type = "Block"
self.triggered = False
self.time = 0
self.maxTime = 10
self.sound = sound
self.dashboard = dashboard
self.vel = 1
self.animation.update()
else:
self.animation.image = self.spriteCollection.get("empty").image
self.time += 1
self.rect.y -= self.vel
else:
self.time += 1
self.rect.y += self.vel
self.screen.blit(
self.spriteCollection.get("sky").image,
COINBRICK:
class CoinBrick(EntityBase):
PAGE 36
def __init__(self, screen, spriteCollection, x, y, sound, dashboard, gravity=0):
self.screen = screen
self.spriteCollection = spriteCollection
self.image = self.spriteCollection.get("bricks").image
self.type = "Block"
self.triggered = False
self.sound = sound
self.dashboard = dashboard
self.image = self.spriteCollection.get("empty").image
self.screen.blit(
self.spriteCollection.get("sky").image,
ENTITY BASE:
import pygame
class EntityBase(object):
self.vel = Vec2D()
self.gravity = gravity
self.traits = None
self.alive = True
self.active = True
self.bouncing = False
self.timeAfterDeath = 5
self.timer = 0
PAGE 37
self.type = ""
self.onGround = False
self.obeyGravity = True
def applyGravity(self):
if self.obeyGravity:
self.vel.y += self.gravity
def updateTraits(self):
try:
trait.update()
except AttributeError:
pass
def getPosIndex(self):
def getPosIndexAsFloat(self):
GOOMBA:
class Goomba(EntityBase):
self.spriteCollection = spriteColl
self.animation = Animation(
self.spriteCollection.get("goomba-1").image,
self.spriteCollection.get("goomba-2").image,
PAGE 38
self.screen = screen
self.type = "Mob"
self.dashboard = level.dashboard
self.EntityCollider = EntityCollider(self)
self.levelObj = level
self.sound = sound
self.textPos = Vec2D(0, 0)
if self.alive:
self.applyGravity()
self.drawGoomba(camera)
self.leftrightTrait.update()
self.checkEntityCollision()
else:
self.onDead(camera)
self.animation.update()
if self.timer == 0:
self.setPointsTextStartPosition(self.rect.x + 3, self.rect.y)
self.movePointsTextUpAndDraw(camera)
self.drawFlatGoomba(camera)
else:
self.alive = None
self.timer += 0.1
self.screen.blit(
self.spriteCollection.get("goomba-flat").image,
PAGE 39
(self.rect.x + camera.x, self.rect.y),
self.textPos = Vec2D(x, y)
self.textPos.y += -0.5
def checkEntityCollision(self):
collisionState = self.EntityCollider.check(ent)
if collisionState.isColliding:
if ent.type == "Mob":
self._onCollisionWithMob(ent, collisionState)
self.alive = False
self.sound.play_sfx(self.sound.brick_bump)
ITEM:
class Item(Dashboard):
self.ItemPos = Vec2D(x, y)
self.itemVel = Vec2D(0, 0)
self.screen = screen
self.coin_animation = copy(collection.get("coin-item").animation)
self.sound_played = False
if not self.sound_played:
self.sound_played = True
dashboard.points += 100
PAGE 40
sound.play_sfx(sound.coin)
self.coin_animation.update()
self.itemVel.y -= 0.5
self.ItemPos.y += self.itemVel.y
self.itemVel.y += 0.5
self.ItemPos.y += self.itemVel.y
self.screen.blit(
self.itemVel.y = -0.75
self.ItemPos.y += self.itemVel.y
MARIO:
import pygame
spriteCollection = Sprites().spriteCollection
PAGE 41
smallAnimation = Animation(
spriteCollection["mario_run1"].image,
spriteCollection["mario_run2"].image,
spriteCollection["mario_run3"].image,
],
spriteCollection["mario_idle"].image,
spriteCollection["mario_jump"].image,
bigAnimation = Animation(
spriteCollection["mario_big_run1"].image,
spriteCollection["mario_big_run2"].image,
spriteCollection["mario_big_run3"].image,
],
spriteCollection["mario_big_idle"].image,
spriteCollection["mario_big_jump"].image,
class Mario(EntityBase):
self.sound = sound
self.input = Input(self)
self.inAir = False
self.inJump = False
self.powerUpState = 0
self.invincibilityFrames = 0
self.traits = {
"jumpTrait": JumpTrait(self),
"bounceTrait": bounceTrait(self),
PAGE 42
self.levelObj = level
self.screen = screen
self.EntityCollider = EntityCollider(self)
self.dashboard = dashboard
self.restart = False
self.pause = False
def update(self):
if self.invincibilityFrames > 0:
self.invincibilityFrames -= 1
self.updateTraits()
self.moveMario()
self.camera.move()
self.applyGravity()
self.checkEntityCollision()
self.input.checkForInput()
def moveMario(self):
self.rect.y += self.vel.y
self.collision.checkY()
self.rect.x += self.vel.x
self.collision.checkX()
def checkEntityCollision(self):
collisionState = self.EntityCollider.check(ent)
if collisionState.isColliding:
if ent.type == "Item":
self._onCollisionWithItem(ent)
self._onCollisionWithBlock(ent)
self._onCollisionWithMob(ent, collisionState)
PAGE 43
self.levelObj.entityList.remove(item)
self.dashboard.points += 100
self.dashboard.coins += 1
self.sound.play_sfx(self.sound.coin)
if not block.triggered:
self.dashboard.coins += 1
self.sound.play_sfx(self.sound.bump)
block.triggered = True
self.powerup(1)
self.killEntity(mob)
self.sound.play_sfx(self.sound.powerup)
self.sound.play_sfx(self.sound.stomp)
self.rect.bottom = mob.rect.top
self.bounce()
self.killEntity(mob)
self.sound.play_sfx(self.sound.stomp)
self.rect.bottom = mob.rect.top
mob.timer = 0
self.bounce()
mob.alive = False
elif collisionState.isColliding and mob.alive and not mob.active and not mob.bouncing:
mob.bouncing = True
mob.leftrightTrait.direction = -1
mob.rect.x += -5
self.sound.play_sfx(self.sound.kick)
else:
mob.rect.x += 5
PAGE 44
mob.leftrightTrait.direction = 1
self.sound.play_sfx(self.sound.kick)
if self.powerUpState == 0:
self.gameOver()
elif self.powerUpState == 1:
self.powerUpState = 0
self.traits['goTrait'].updateAnimation(smallAnimation)
x, y = self.rect.x, self.rect.y
self.invincibilityFrames = 60
self.sound.play_sfx(self.sound.pipe)
def bounce(self):
self.traits["bounceTrait"].jump = True
if ent.__class__.__name__ != "Koopa":
ent.alive = False
else:
ent.timer = 0
ent.leftrightTrait.speed = 1
ent.alive = True
ent.active = False
ent.bouncing = False
self.dashboard.points += 100
def gameOver(self):
srf.set_alpha(128)
self.sound.music_channel.stop()
self.sound.music_channel.play(self.sound.death)
srf.fill((0, 0, 0))
pygame.draw.circle(
PAGE 45
srf,
i,
pygame.display.update()
self.input.checkForInput()
while self.sound.music_channel.get_busy():
pygame.display.update()
self.input.checkForInput()
self.restart = True
def getPos(self):
self.rect.x = x
self.rect.y = y
if self.powerUpState == 0:
if powerupID == 1:
self.powerUpState = 1
self.traits['goTrait'].updateAnimation(bigAnimation)
self.invincibilityFrames = 20
PAGE 46
BIBILIOGRAPHY
• https://github.com/explore
• https://www.wikipedia.org/
• https://codewithcurious.com/projects/
PAGE 47