def addEnemy( room ): if room.isLeaf == False: return if room == playerRoom: return prob = 1.4 while random.random() < prob: rect = room.rect while True: pos = rect.p1 + ( rect.dim * Math2D.Point( random.uniform( 0.2, 0.8 ), random.uniform( 0.2, 0.8 ) ) ) pos = Math2D.IntPoint( pos ) if not self.world._map.isBlocked( pos.x, pos.y ): break enemy = Entity() enemy.target = player enemy.onRemove.append( self.addScore ) enemy.addComponent( Position( pos.x, pos.y ) ) enemy.addComponent( TurnTaker( ai = TurnTakerAi() ) ) enemy.addComponent( Renderable( chr(1) ) ) enemy.addComponent( CharacterComponent( random.choice( enemyCharacter ) ) ) self.world.addEntity( enemy ) prob *= 0.7
def live(m, p, rDetec, dt): # recuperation de la position du mob mX, mY = Entity.getPosition(m) mvX, mvY = Entity.getSpeed(m) keepSameDirection = bool(random.getrandbits(1)) if not keepSameDirection: direction = [(0,8),(0,-8),(-16,0),(16,0)] mvX, mvY = direction[random.randint(0,3)] # Gestion des transitions oldState = m["state"] newState = state(m, p, rDetec) if oldState != newState: transition = True else: transition = False if newState == "angry" and transition == True: mvX, mvY = 2*mvX, 2*mvY elif newState == "freeze" and transition == True: mvX, mvY = 0, 0 Entity.setSpeed(m, mvX, mvY) return Entity.simulate(m, dt)
def launchArrow(r, entity): arrow = Arrow.create() ax, ay = Entity.getPosition(entity) evx, evy = Entity.getDirection(entity) ax, ay = ax + evx, ay + evy Arrow.setPosition(arrow, ax, ay) Arrow.setSpeed(arrow, evx*60, evy*30) Arrow.setDamage(arrow, Entity.getDamage(entity)*Entity.getStrength(entity)) r["arrows"].append(arrow)
def interact(g, settings, keyRead): # Actualiser les nouvelles touches du fichier settings: keyM = g["keyManager"] for keyName in keyM: for k in settings: if keyName == k: keyM[keyName] = settings[k] player = Dungeon.getPlayer(g["dungeon"]) playerSpeedValue = 15 if keyM["Up"] == keyRead: Entity.setSpeed(player, 0, -playerSpeedValue) elif keyM["Down"] == keyRead: Entity.setSpeed(player, 0, playerSpeedValue) elif keyM["Left"] == keyRead: Entity.setSpeed(player, -playerSpeedValue*2, 0) elif keyM["Right"] == keyRead: Entity.setSpeed(player, playerSpeedValue*2, 0) elif keyM["Shoot"] == keyRead: Dungeon.launchArrow(g["dungeon"], player) elif keyM["Chest"] == keyRead: Dungeon.openChest(g["dungeon"])
def execute(self, *arg, **kw): if hasattr(self,'_Connection__close_with_result'): tmp = self._Connection__close_with_result self._Connection__close_with_result=False if hasattr(self,'__close_with_result'): tmp2 = self.__close_with_result self.__close_with_result=False try: if not self.is_refreshing: self.is_refreshing = True Entity.refresh_views(arg[0], self) except Exception, instance: print "Unexpected error while performing refresh:", instance
def state(m, p, rDetec): # recuperation de la position du mob mX, mY = Entity.getPosition(m) # recuperation de la position du joueur pX, pY = Entity.getPosition(p) # Position du joueur par rapport au mob: playerPosition = math.sqrt((pX-mX)**2 + (pY-mY)**2) if playerPosition <= rDetec: m["state"] = "angry" else: m["state"] = "freeze" return m["state"]
def run(g, dt): if Dungeon.run(g["dungeon"], dt) == "win": return "win" player = Dungeon.getPlayer(g["dungeon"]) if Entity.getHealth(player) <= 0: return "lose" return "run"
def show(r): # Affichage du fond for y in range(0, len(r["background"])): for x in range(0, len(r["background"][y])): Utils.goto(x+2, y+2) Utils.write(r["background"][y][x]+"\n") # Affichage des coffres for currentChest in r["chests"]: x, y = Chest.getPosition(currentChest) Utils.goto(x+2, y+2) Utils.write("C") # Affichage des entités for currentEntity in r["entity"]: Entity.show(currentEntity) # Affichage des projectiles for currentArrow in r["arrows"]: Arrow.show(currentArrow)
def getEntityByPosition(r, x, y, skipEntity = None): # On parcourt la liste des entités de la salle for currentEntity in r["entity"]: if currentEntity != skipEntity: ex, ey = Entity.getPosition(currentEntity) ex, ey = int(round(ex)), int(round(ey)) if (ex, ey) == (int(round(x)), int(round(y))): return currentEntity return -1
def show(g): Dungeon.show(g["dungeon"]) # -- Interface du joueur -- player = Dungeon.getPlayer(g["dungeon"]) offsetX = 84 offsetY = 2 # Clear for i in range(1, 41): Utils.goto(offsetX, i+1) Utils.write(29*" "+"\n") # Link Utils.goto(offsetX+1, offsetY+1) Utils.write("Link", "green") # Health health = Entity.getHealth(player) maxHealth = Entity.getMaxHealth(player) Utils.goto(offsetX+1, offsetY+3) Utils.write("Health : " + str(health) + " / " + str(maxHealth)) Utils.goto(offsetX+1, offsetY+4) healthBar = int(round((health/maxHealth)*10))*"♥ " Utils.write(healthBar.decode("utf-8"), "red") # Strength strength = Entity.getStrength(player) Utils.goto(offsetX+1, offsetY+6) Utils.write("Strength : + " + str(int((strength-1)*100)) + "%") # Resistance resistance = Entity.getResistance(player) Utils.goto(offsetX+1, offsetY+8) Utils.write("Resistance : + " + str(int((resistance-1)*100)) + "%") # Damage damage = Entity.getDamage(player) Utils.goto(offsetX+1, offsetY+10) Utils.write("Damage : " + str(damage))
def show(a): direction = Entity.getDirection(a) sprite = "*" if direction == (1, 0): sprite = "→" elif direction == (-1, 0): sprite = "←" elif direction == (0, 1): sprite = "↓" elif direction == (0, -1): sprite = "↑" Utils.goto(int(round(a["x"]+2)), int(round(a["y"]+2))) Utils.write(sprite.decode("utf-8"))
def create(dungeonName, roomName): # -- Initialisation du dictionnaire -- r = dict() r["background"]=[] r["entity"]=[] r["chests"]=[] r["arrows"]=[] r["upRoom"]=None r["downRoom"]=None r["leftRoom"]=None r["rightRoom"]=None # -- Parsage du fichier XML correspondant -- path = "./assets/rooms/" + dungeonName + "/" + roomName + ".xml" doc = parse(path) rootBeacon = doc.documentElement # Récupération du background background = rootBeacon.getElementsByTagName("background")[0].firstChild.nodeValue.split("\n", 41) del background[0] del background[-1] for line in background: r["background"].append(list(line)) # Récupération des mobs mobs = rootBeacon.getElementsByTagName("mob") nb_mobs = mobs.length for i in range(nb_mobs): mob = Mob.create() Entity.setType(mob, mobs[i].getAttribute("type")) Entity.setPosition(mob, int(mobs[i].getAttribute("x")), int(mobs[i].getAttribute("y"))) Entity.setHealth(mob, int(mobs[i].getAttribute("health"))) Entity.setStrength(mob, float(mobs[i].getAttribute("strength"))) Entity.setResistance(mob, float(mobs[i].getAttribute("resistance"))) Entity.setDamage(mob, int(mobs[i].getAttribute("damage"))) Entity.setSprite(mob, strip(mobs[i].firstChild.nodeValue)) r["entity"].append(mob) # Récupération des coffres chests = rootBeacon.getElementsByTagName("chest") nb_chests = chests.length for i in range(nb_chests): chest = Chest.create() Chest.setPosition(chest, int(chests[i].getAttribute("x")), int(chests[i].getAttribute("y"))) # Ajout des items items = chests[i].childNodes for item in items: if item.nodeName == "bonus": bonus = Bonus.create() Bonus.setName(bonus, item.getAttribute("name")) Bonus.setAmount(bonus, float(item.getAttribute("amount"))) Chest.addBonus(chest, bonus) elif item.nodeName == "bow": bow = Bow.create() Bow.setName(bow, item.getAttribute("name")) Bow.setDamage(bow, int(item.getAttribute("damage"))) Bow.setSprite(bow, item.firstChild.nodeValue) Chest.addItem(chest, bow) r["chests"].append(chest) return r
def getEntityPosition(r, type): for currentEntity in r["entity"]: if Entity.getType(currentEntity) == type: return Entity.getPosition(currentEntity)
#Start Graphics pygame.init() #Screen clock = pygame.time.Clock() screen = pygame.display.set_mode((1280, 960)) screen_rect = screen.get_rect() #Booleans startButtonClicked = False pauseMenuButton = False spawning = True buying = [False, False, False] #Ints playerHealthCount = 100 #Entities towers = Entity.spawnTowers() waves = Entity.Waves() #Menu Stuff menu = Gui.Menu("images/Pause Menu.png") startMenu = Gui.Menu("images/Start Screen/Start Screen.png") IntestinesBackground = Level.Sprite("images/Level1 Background.png") while True: while startButtonClicked == False: #main menu code for event in pygame.event.get(): if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1: if startMenu.startScreenStartButton.rect.collidepoint(pygame.mouse.get_pos()): startButtonClicked = True elif startMenu.startScreenQuitButton.rect.collidepoint(pygame.mouse.get_pos()): sys.exit() startMenu.drawStartMenu(screen)
from random import uniform import math import numpy as np import Entity width = 800 height = 600 pygame.init() my_characters = [] number_of_characters = 1 for x in range(0,number_of_characters): my_characters.append(Entity.Entity(randint(0,200),randint(10,500),1,math.pi,100,800)) my_characters[x].vel = pygame.math.Vector2(uniform(0,0.2),uniform(0,0.2)) gameDisplay = pygame.display.set_mode((width,height)) pygame.display.set_caption('A bit Racey') clock = pygame.time.Clock() crashed = False mouse_pos = pygame.math.Vector2() flow_width = width/24 flow_height = height/24 while not crashed: for event in pygame.event.get(): if event.type == pygame.QUIT:
def _parseEntities(self): entities = [] for entity in self.mazeData['Entities']: newEntity = Entity() newEntity.id = entity['id'] newEntity.speed = entity['speed'] newEntity.target = entity['target'] newEntity.preferences = entity['preferences'] if 'direction' in entity.keys(): newEntity.direction = entity['direction'] newEntity.position = self._findEntityPosition(newEntity.id) entities.append(newEntity) idList = [entity['id'] for entity in self.mazeData['Entities']] targetList = [entity['target'] for entity in self.mazeData['Entities']] if 'G' not in idList: goal = Entity() goal.id = 'G' goal.position = self.mazeTiles.FindEntityPositionFromTiles(goal.id) entities.append(goal) if 'Z' in targetList and not 'Z' in idList: target = Entity() target.id = 'Z' target.position = self.mazeTiles.FindEntityPositionFromTiles(target.id) entities.append(target) return entities
def __init__(self, image, ai, stats): Entity.__init__(image) self.ai = ai set_Statistics(stats)
def main(): gameRunning = True im = Image.open("graphics/map4.png", "r") pixels = list(im.getdata()) myMap = Map(Globals.gTileSize) # create a map from the image myMap.loadMap(pixels, im.size[0], im.size[1]) graphicsMgr = GraphicsManager(myMap) myPathfinder = Pathfinder(myMap) path = None startCoord = (0, 0) endCoord = (0, 0) ninja1 = Entity("ninja", myPathfinder) ninja2 = Entity("ninja", myPathfinder) ninja1.setPosition((0, 6)) ninja2.setPosition((5, 0)) ninjas = [ninja1, ninja2] Globals.gEntities = [ninja1, ninja2] ninja1.setPath( myPathfinder.findPath( ninja1.getTilePos(), (9, 0) ) ) ninja2.setPath( myPathfinder.findPath( ninja2.getTilePos(), (2, 10) ) ) ninja1.ChangeState(Globals.gStates["MoveAlongPath"]) ninja2.ChangeState(Globals.gStates["MoveAlongPath"]) selectedNinja = ninja1 ninja1.select() Globals.gDeltaTime = time.clock() - Globals.gDeltaTime while(gameRunning): for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: sys.exit() if event.type == pygame.MOUSEBUTTONDOWN: mouseTilePos = getTileCoords(event.pos, Globals.gTileSize) if event.button == 3: # set end pos startCoord = selectedNinja.getTilePos() endCoord = mouseTilePos path = myPathfinder.findPath(startCoord, endCoord) if( not path ): print "no path" else: selectedNinja.setPath(path) selectedNinja.ChangeState(Globals.gStates["MoveAlongPath"]) elif event.button == 1: print "mouse coord: ", mouseTilePos # select ninja for ninja in ninjas: ninja.unselect() ninjaPos = ninja.getTilePos() if ninjaPos[0] == mouseTilePos[0] and ninjaPos[1] == mouseTilePos[1]: selectedNinja = ninja ninja.select() for ninja in ninjas: ninja.update() graphicsMgr.render(myMap, path, ninjas)
def __init__( self ): self.world = World.World( Map.Map( 512, 512 ) ) self.score = 0 self.shouldRestart = False self.autoSleep = False World.curTurn = 0 root = RoomBuilder.build( self.world._map ) self.root = root POINT_11 = Math2D.Point( 1, 1 ) Funcs.buildMap( self.world._map, root ) self.renderer = Systems.Renderer( self.world, Init.SCREEN_WIDTH, Init.SCREEN_HEIGHT ) self.renderer.setMap( self.world._map ) self.world._map.buildTcodMap() playerRoom = self.root.pickRandomRoom( lambda: random.random() < 0.5 ) pos = Math2D.IntPoint( playerRoom.rect.center ) self.actionSystem = ActionSystem( self.world, actionMap ) self.playerAction = None def playerAction( __, _, wasBlocked ): ret = self.playerAction self.playerAction = None return ret player = Entity() player.addComponent( Position( pos.x, pos.y ) ) player.addComponent( TurnTaker( ai = playerAction ) ) player.addComponent( CharacterComponent( playerCharacter ) ) player.addComponent( Renderable( chr(2) ) ) player.addComponent( SpellCaster() ) player.onRemove.append( self.playerDeath ) self.world.addEntity( player ) self.player = player self.renderer.player = player self.renderer.playerChar = player.getComponent( CharacterComponent ) def addEnemy( room ): if room.isLeaf == False: return if room == playerRoom: return prob = 1.4 while random.random() < prob: rect = room.rect while True: pos = rect.p1 + ( rect.dim * Math2D.Point( random.uniform( 0.2, 0.8 ), random.uniform( 0.2, 0.8 ) ) ) pos = Math2D.IntPoint( pos ) if not self.world._map.isBlocked( pos.x, pos.y ): break enemy = Entity() enemy.target = player enemy.onRemove.append( self.addScore ) enemy.addComponent( Position( pos.x, pos.y ) ) enemy.addComponent( TurnTaker( ai = TurnTakerAi() ) ) enemy.addComponent( Renderable( chr(1) ) ) enemy.addComponent( CharacterComponent( random.choice( enemyCharacter ) ) ) self.world.addEntity( enemy ) prob *= 0.7 #t = playerRoom #playerRoom = None #addEnemy( t ) self.root.iterateTree( addEnemy, None ) self.curTurn = 0 self.render()
def add_entity(self, x, y): new = Entity(x, y) new.id = self.id self.id += 1 self.entities.append(new)
from MainMenu import * from Town import * from Entity import * from Monster import* from PlayerTurn import* from PlayerAbilities import * from Abilities import * from Combat import* MainMenu(0) os.system('cls') Name=input("What is your Character's Name: ") Name=Name.title() # Reminder.. Player: ( Name , Hp , En , Stats , Buffs , Potions , Coins , Lvl , Exp , Lvl Points ) Player = Player (Name,[100,100],[5,5],[2,0,2],[],[0,0],0,2,[0,0],0) Monster = Entity ("Wolf",[15,15],[3,3],[2,2,0],[]) Town(Player,0) Combat(Player,Monster,1,0,0) d=input()
def live(p, dt): return Entity.simulate(p, dt)
import Entity import Stats BugBear = Entity.Organism("Some Guy", Stats.Being, (51, 51), "gfx/guy.png") List = {BugBear: 5} def Load(): BugBear.body.create("Head", "Torso", "Arm")
def __init__(self, file): self.file = file self.spriteBanks = [] self.templates = {} with open(self.file) as json_file: data = json.load(json_file) # Register the related frames if 'imageBanks' in data.keys(): for b in data["imageBanks"]: #create new bank bank = SpriteBank(b["id"], b["file"]) self.spriteBanks.append(bank) pyxel.image(b["id"]).load(0, 0, b["file"]) #add sprites for s in b["sprites"]: bank.addSprite( Sprite(Vector2f(s["pos_x"], s["pos_y"]), Vector2f(s["width"], s["height"]), Vector2f(s["pivot_x"], s["pivot_y"]), s["transparent"]), s["id"]) else: print("Warning: EntityFactory: no 'imageBanks' in " + self.file) # create entity if ('entities' in data.keys()): for name in data["entities"].keys(): templateData = data["entities"][name] template = Entity() # basic information template.size.x = templateData["size_x"] template.size.y = templateData["size_y"] if ('rigidbody' in templateData): template.addComponent('RigidBody', RigidBody()) # rendering informations if ('renderer' in templateData): palette = templateData["renderer"]["imageBank"] bank = self.spriteBanks[palette] renderer = templateData["renderer"] # prefab is rendered using an Animator if ('animations' in renderer): animations = [] #create the animations for a in renderer["animations"]: frames = [] for f in a["frames"]: frame = bank.searchByName(f) if frame != None: frames.append(frame) else: print( "Warning: EntityFactory: no sprite under the name " + str(f) + ", for loading " + name) animations.append( Animation(a["animationName"], bank, frames, a["interruptable"], 1.0 / a["speed"], a["loop"])) template.addComponent( 'Animator', Animator(palette, animations, renderer["defaultAnimation"])) # prefab is rendered using a SpriteRenderer elif ('spriteList' in renderer): spriteList = [] for s in renderer["spriteList"]: sprite = bank.searchByName(s) if sprite != None: spriteList.append(sprite) else: print( "Warning: EntityFactory: no sprite under the name " + str(s) + ", for loading " + name) template.addComponent('SpriteList', spriteList) template.addComponent('ComponentRenderer', SpriteRenderer(bank)) else: print( "Warning: EntityFactory: no component renderer for entity " + name) # collision informations if ('colliders' in templateData): colliderList = [] for c in templateData["colliders"]: collider = Collider(c["type"]) collider.position = Vector2f( c["pos_x"], c["pos_y"]) collider.size = Vector2f(c["width"], c["height"]) colliderList.append(collider) template.addComponent('ColliderList', colliderList) else: print( "Warning: EntityFactory: no colliders for entity " + name) # scripts if ('scripts' in templateData): scripts = [] for s in templateData["scripts"]: try: module = __import__(s["name"]) class_ = getattr(module, s["name"]) script = class_() scripts.append(script) except: print( "Warning: EntityFactory: script loading error for entity " + name) template.addComponent('Scripts', scripts) # register template self.templates[name] = template else: print("Warning: EntityFactory: no entities in " + self.file)
def setEntityPosition(r, type, x, y): for currentEntity in r["entity"]: if Entity.getType(currentEntity) == type: Entity.setPosition(currentEntity, x, y) return
def did_eat(self): # Boolean value representing whether or not a space is empty. This matters as you don't want the apple spawning # on the same spot as part of the snake's body spaceEmpty = True # This conditional statement checks whether or not the apple and head of the first snake occupy the same spot if self.head_1.x == self.apple.x and self.head_1.y == self.apple.y: # The integer value of what will be the previous X value prevX = self.apple.x # The integer value of what will be the previous Y value prevY = self.apple.y # The integer value of what will be the new current X value. It is randomly generated currX = myround( random.randint(0, self.w / 10 - 10 * self.director.scale), 10 * self.director.scale) * 10 + 1 * self.director.scale # This loop checks if the previous X value and the newly generated X value are the same, if so it will # generate a new one until they no longer match. This stops the apple from spawning in place while prevX == currX: currX = myround( random.randint(0, self.w / 10 - 10 * self.director.scale), 10 * self.director.scale) * 10 + 1 * self.director.scale # The integer value of what will be the new current Y value. It is randomly generated currY = myround( random.randint(0, self.h / 10 - 10 * self.director.scale), 10 * self.director.scale) * 10 + 1 * self.director.scale # This loop checks if the previous Y value and the newly generated Y value are the same, if so it will # generate a new one until they no longer match. This stops the apple from spawning in place while prevY == currY: currY = myround( random.randint(0, self.h / 10 - 10 * self.director.scale), 10 * self.director.scale) * 10 + 1 * self.director.scale # The next 11 lines essentially do what the previous lines have except it checks each segements of the tail # so that the apple doesn't spawn in one of their spots for i in self.tail_1: if currX == i.x and currY == i.y: spaceEmpty = False while not spaceEmpty and prevX != currX and prevY != currY: currX = myround( random.randint( 0, self.w / 10 - 10 * self.director.scale), 10 * self.director.scale) * 10 + 1 * self.director.scale currY = myround( random.randint( 0, self.h / 10 - 10 * self.director.scale), 10 * self.director.scale) * 10 + 1 * self.director.scale for j in self.tail_1: if currX == j.x and currY == j.y: spaceEmpty = False break spaceEmpty = True # Once all has been said and done the apple's x and y values are changed to currX and currY self.apple.x = currX self.apple.y = currY # A new segment is added to the end of the first player's snake self.tail_1.append( Entity( self.tail_1[len(self.tail_1) - 1].x * self.director.scale, self.tail_1[len(self.tail_1) - 1 * self.director.scale].y, 9 * self.director.scale, 9 * self.director.scale, self.director.p1color)) # This conditional statement checks whether or not the apple and head of the second snake occupy the same spot if self.head_2.x == self.apple.x and self.head_2.y == self.apple.y: # The integer value of what will be the previous X value prevX = self.apple.x # The integer value of what will be the previous Y value prevY = self.apple.y # The integer value of what will be the new current X value. It is randomly generated currX = myround( random.randint(0, self.w / 10 - 10 * self.director.scale), 10 * self.director.scale) * 10 + 1 * self.director.scale # This loop checks if the previous X value and the newly generated X value are the same, if so it will # generate a new one until they no longer match. This stops the apple from spawning in place while prevX == currX: currX = myround( random.randint(0, self.w / 10 - 10 * self.director.scale), 10 * self.director.scale) * 10 + 1 * self.director.scale # The integer value of what will be the new current Y value. It is randomly generated currY = myround( random.randint(0, self.h / 10 - 10 * self.director.scale), 10 * self.director.scale) * 10 + 1 * self.director.scale # This loop checks if the previous Y value and the newly generated Y value are the same, if so it will # generate a new one until they no longer match. This stops the apple from spawning in place while prevY == currY: currY = myround( random.randint(0, self.h / 10 - 10 * self.director.scale), 10 * self.director.scale) * 10 + 1 * self.director.scale # The next 11 lines essentially do what the previous lines have except it checks each segements of the tail # so that the apple doesn't spawn in one of their spots for i in self.tail_2: if currX == i.x and currY == i.y: spaceEmpty = False while not spaceEmpty and prevX != currX and prevY != currY: currX = myround( random.randint( 0, self.w / 10 - 10 * self.director.scale), 10 * self.director.scale) * 10 + 1 * self.director.scale currY = myround( random.randint( 0, self.h / 10 - 10 * self.director.scale), 10 * self.director.scale) * 10 + 1 * self.director.scale for j in self.tail_2: if currX == j.x and currY == j.y: spaceEmpty = False break spaceEmpty = True # Once all has been said and done the apple's x and y values are changed to currX and currY self.apple.x = currX self.apple.y = currY # A new segment is added to the end of the first player's snake self.tail_2.append( Entity( self.tail_2[len(self.tail_2) - 1].x * self.director.scale, self.tail_2[len(self.tail_2) - 1 * self.director.scale].y, 9 * self.director.scale, 9 * self.director.scale, self.director.p2color))
def getPlayer(r): for i in range(0, len(r["entity"])): if(Entity.getType(r["entity"][i]) == "player"): return r["entity"][i]
parser.read("level.txt") test = parser.get('level', 'map') print test map = loadMap() # load 2d array of map #print map x, y = 0, 0 # background starting point mapsprite, mapblockedsprite, backoverlaysprite, frontoverlaysprite = createMapSprites( x, y, map, table) # create sprite group for map playerTable = load_tile_table("anichar2.png", 32, 32) enemyTable = load_tile_table("enemy2.png", 32, 32) entitysprite = pygame.sprite.Group() entity = Entity(300, 300, 14, "Wood", table[14]) # make wood entity and entity group entitysprite.add(entity) entity = Entity(500, 300, 14, "Wood", table[14]) # make wood entity and entity group entitysprite.add(entity) entity = Entity(500, 500, 14, "Wood", table[14]) # make wood entity and entity group entitysprite.add(entity) enemysprite = pygame.sprite.Group() playersprite = createPlayerSprite( 500, 350, playerTable) # create sprite group for player player = playersprite.sprites()[0]
def __init__(self, director): Scene.__init__(self, director) # Boolean value that tells whether or not player one has won self.plyronewins = False # Boolean value that tells whether or not player two has won self.plyrtwowins = False # Boolean value that tells whether or not there has been a "draw" self.plyrdraw = False # A surface with the text "Draw..." printed on it using the font named "font" self.draw_txt = director.font.render("Draw...", True, (255, 255, 255)) # A surface with the text "Player One Wins" printed on it using the font named "font" self.plyronewins_txt = director.font.render("Player One Wins", True, (255, 255, 255)) # A surface with the text "Player Two Wins" printed on it using the font named "font" self.plyrtwowins_txt = director.font.render("Player Two Wins", True, (255, 255, 255)) # A surface with the text "Draw" printed on it using the font named "font" self.plyrdraw_txt = director.font.render("Draw", True, (255, 255, 255)) # This is a rectangle object with the size being the same as the size of the game window size self.screen_rect = director.screen.get_rect() # The font and size of the text that will be used to display text on the screen self.plyr = pygame.font.Font("fonts\Condition.ttf", 20 * director.scale) # Creates a surface with the text "ctrl" printed on it using the plyr font self.txt = self.plyr.render("ctrl", True, (255, 255, 255)) # These variables hold the width and height of the game window, respectively self.w, self.h = pygame.display.get_surface().get_size() # The change in x value of the first player's snake self.dx1 = 10 * director.scale # The change in y value of the first player's snake self.dy1 = 0 # The change in x value of the second player's snake self.dx2 = -10 * director.scale # The change in y value of the second player's snake self.dy2 = 0 # The Entity object representing the head of the first player's snake self.head_1 = Entity(21 * director.scale, 1 * director.scale, 9 * director.scale, 9 * director.scale, director.p1color) # The Entity object representing the head of the second player's snake self.head_2 = Entity(371 * director.scale, 1 * director.scale, 9 * director.scale, 9 * director.scale, director.p2color) # The Entity object representing the apple self.apple = Entity(11 * director.scale, 11 * director.scale, 9 * director.scale, 9 * director.scale, (255, 44, 44)) # A list holding the tail segments of the first player's snake self.tail_1 = [] # A list holding the tail segments of the second player's snake self.tail_2 = [] # This starts off the first player's snake with two tail segments for i in range(1, 3): self.tail_1.append( Entity(self.head_1.x - 10 * i * director.scale, self.head_1.y * director.scale, 9 * director.scale, 9 * director.scale, self.director.p1color)) # This starts off the second player's snake with two tail segments for i in range(1, 3): self.tail_2.append( Entity(self.head_2.x + 10 * i * director.scale, self.head_2.y * director.scale, 9 * director.scale, 9 * director.scale, self.director.p2color))
def openChest(r): player = getPlayer(r) px, py = Entity.getPosition(player) for (dx, dy) in [(-1, -1), (0, -1), (1, -1), (-1, 0), (1, 0), (-1, 1), (0, 1), (1, 1)]: cx, cy = px + dx, py + dy chest = getChestByPosition(r, cx, cy) if chest != -1: items = Chest.getItems(chest) for item in items: Chest.addItem(Player.getInventory(player), item) bonus = Chest.getBonus(chest) for b in bonus: name = Bonus.getName(b) if name == "health" and Entity.getMaxHealth(player) != Entity.getHealth(player): Entity.setHealth(player, Entity.getHealth(player) + Bonus.getAmount(b)) elif name == "strength": Entity.setStrength(player, Entity.getStrength(player) + Bonus.getAmount(b)) elif name == "resistance": Entity.setResistance(player, Entity.getResistance(player) + Bonus.getAmount(b)) r["chests"].remove(chest)
class EdiblesTwoPlayer(Scene): def __init__(self, director): Scene.__init__(self, director) # Boolean value that tells whether or not player one has won self.plyronewins = False # Boolean value that tells whether or not player two has won self.plyrtwowins = False # Boolean value that tells whether or not there has been a "draw" self.plyrdraw = False # A surface with the text "Draw..." printed on it using the font named "font" self.draw_txt = director.font.render("Draw...", True, (255, 255, 255)) # A surface with the text "Player One Wins" printed on it using the font named "font" self.plyronewins_txt = director.font.render("Player One Wins", True, (255, 255, 255)) # A surface with the text "Player Two Wins" printed on it using the font named "font" self.plyrtwowins_txt = director.font.render("Player Two Wins", True, (255, 255, 255)) # A surface with the text "Draw" printed on it using the font named "font" self.plyrdraw_txt = director.font.render("Draw", True, (255, 255, 255)) # This is a rectangle object with the size being the same as the size of the game window size self.screen_rect = director.screen.get_rect() # The font and size of the text that will be used to display text on the screen self.plyr = pygame.font.Font("fonts\Condition.ttf", 20 * director.scale) # Creates a surface with the text "ctrl" printed on it using the plyr font self.txt = self.plyr.render("ctrl", True, (255, 255, 255)) # These variables hold the width and height of the game window, respectively self.w, self.h = pygame.display.get_surface().get_size() # The change in x value of the first player's snake self.dx1 = 10 * director.scale # The change in y value of the first player's snake self.dy1 = 0 # The change in x value of the second player's snake self.dx2 = -10 * director.scale # The change in y value of the second player's snake self.dy2 = 0 # The Entity object representing the head of the first player's snake self.head_1 = Entity(21 * director.scale, 1 * director.scale, 9 * director.scale, 9 * director.scale, director.p1color) # The Entity object representing the head of the second player's snake self.head_2 = Entity(371 * director.scale, 1 * director.scale, 9 * director.scale, 9 * director.scale, director.p2color) # The Entity object representing the apple self.apple = Entity(11 * director.scale, 11 * director.scale, 9 * director.scale, 9 * director.scale, (255, 44, 44)) # A list holding the tail segments of the first player's snake self.tail_1 = [] # A list holding the tail segments of the second player's snake self.tail_2 = [] # This starts off the first player's snake with two tail segments for i in range(1, 3): self.tail_1.append( Entity(self.head_1.x - 10 * i * director.scale, self.head_1.y * director.scale, 9 * director.scale, 9 * director.scale, self.director.p1color)) # This starts off the second player's snake with two tail segments for i in range(1, 3): self.tail_2.append( Entity(self.head_2.x + 10 * i * director.scale, self.head_2.y * director.scale, 9 * director.scale, 9 * director.scale, self.director.p2color)) def on_event(self, event): # This conditional statement that if either the W key is pressed down and if the first player's snake # is not moving on the y-axis then have it start moving up on the y axis cease movement on the x axis if event.type == pygame.KEYDOWN and event.key == pygame.K_w and self.dy1 == 0: self.dy1 = -10 * self.director.scale self.dx1 = 0 # This conditional statement that if either the S key is pressed down and if the first player's snake # is not moving on the y-axis then have it start moving down on the y axis cease movement on the x axis if event.type == pygame.KEYDOWN and event.key == pygame.K_s and self.dy1 == 0: self.dy1 = 10 * self.director.scale self.dx1 = 0 # This conditional statement that if either the A key is pressed down and if the first player's snake # is not moving on the x-axis then have it start moving left on the x axis cease movement on the y axis if event.type == pygame.KEYDOWN and event.key == pygame.K_a and self.dx1 == 0: self.dx1 = -10 * self.director.scale self.dy1 = 0 # This conditional statement that if either the D key is pressed down and if the first player's snake # is not moving on the x-axis then have it start moving right on the x axis cease movement on the y axis if event.type == pygame.KEYDOWN and event.key == pygame.K_d and self.dx1 == 0: self.dx1 = 10 * self.director.scale self.dy1 = 0 # This conditional statement that if either the Up key is pressed down and if the second player's snake # is not moving on the y-axis then have it start moving up on the y axis cease movement on the x axis if event.type == pygame.KEYDOWN and event.key == pygame.K_UP and self.dy2 == 0: self.dy2 = -10 * self.director.scale self.dx2 = 0 # This conditional statement that if either the Down key is pressed down and if the second player's snake # is not moving on the y-axis then have it start moving down on the y axis cease movement on the x axis if event.type == pygame.KEYDOWN and event.key == pygame.K_DOWN and self.dy2 == 0: self.dy2 = 10 * self.director.scale self.dx2 = 0 # This conditional statement that if either the A key is pressed down and if the second player's snake # is not moving on the x-axis then have it start moving left on the x axis cease movement on the y axis if event.type == pygame.KEYDOWN and event.key == pygame.K_LEFT and self.dx2 == 0: self.dx2 = -10 * self.director.scale self.dy2 = 0 # This conditional statement that if either the D key is pressed down and if the second player's snake # is not moving on the x-axis then have it start moving right on the x axis cease movement on the y axis if event.type == pygame.KEYDOWN and event.key == pygame.K_RIGHT and self.dx2 == 0: self.dx2 = 10 * self.director.scale self.dy2 = 0 # If the R button is pressed down then the scene is changed to a new instance of the Two Player Mode if event.type == pygame.KEYDOWN and event.key == pygame.K_r: # Causes the currently playing song to stop playing pygame.mixer.music.stop() self.director.change_scene(EdiblesTwoPlayer(self.director)) # Loads the song pygame.mixer.music.load("music\snakesong.wav") # Plays the loaded song indefinitely pygame.mixer.music.play(-1) # If either of the control buttons are pressed then the scene is chagned to the Title Screen and the Two # Player Mode is reset by creating a new instance of it if event.type == pygame.KEYDOWN and (event.key == pygame.K_LCTRL or event.key == pygame.K_RCTRL): self.director.change_scene(self.director.scenes[0]) # Causes the currently playing song to stop playing pygame.mixer.music.stop() self.director.scenes[2] = EdiblesTwoPlayer(self.director) def on_update(self): # The fps (frames per second) is changed to 15 self.director.fps = 15 # This conditional statement checks to see if none of the win states have been met, and if so, execute the # following code if not self.plyronewins and not self.plyrtwowins and not self.plyrdraw: # Calling the did_eat function self.did_eat() # update position of the first tail's elements for i in range(len(self.tail_1) - 1, 0, -1): self.tail_1[i].x = self.tail_1[i - 1].x self.tail_1[i].y = self.tail_1[i - 1].y self.tail_1[0].x, self.tail_1[0].y = (self.head_1.x, self.head_1.y) # The following two lines update the x and y position of the first snake's head self.head_1.x += self.dx1 self.head_1.y += self.dy1 # The following three lines ensure that the head and tail of the snake are the proper color as the color # can change if the player picks a new color on the configuration screen self.head_1.color = self.director.p1color for i in self.tail_1: i.color = self.director.p1color # Calling of the is_collide function self.is_collide() # Checks if any of the game win / game over states and have been met and if so then the function ceases to # execute if self.plyrdraw or self.plyronewins or self.plyrtwowins: return # update position of the second tail's elements for i in range(len(self.tail_2) - 1, 0, -1): self.tail_2[i].x = self.tail_2[i - 1].x self.tail_2[i].y = self.tail_2[i - 1].y self.tail_2[0].x, self.tail_2[0].y = (self.head_2.x, self.head_2.y) # The following two lines update the x and y position of the first snake's head self.head_2.x += self.dx2 self.head_2.y += self.dy2 # The following three lines ensure that the head and tail of the snake are the proper color as the color # can change if the player picks a new color on the configuration screen self.head_2.color = self.director.p2color for i in self.tail_2: i.color = self.director.p2color # Calling of the is_collide function self.is_collide() # Checks if any of the game win / game over states and have been met and if so then the function ceases to # execute if self.plyrdraw or self.plyronewins or self.plyrtwowins: return def on_draw(self, screen): # Changes every pixel in the window to black. This is done to wipe the screen and set it up for drawing a new # frame self.director.screen.fill((0, 0, 0)) # Calls the draw_grid function self.draw_grid(screen) # Calls the apple Entity's draw function self.apple.draw(screen) # Calls the head Entity's draw function self.head_1.draw(screen) # Calls the head Entity's draw function self.head_2.draw(screen) # Calls the print_tail function self.print_tails(screen) # This conditional statement executes if player one has won if self.plyronewins: # The text "Player One Wins" is printed to the middle of the screen screen.blit( self.plyronewins_txt, self.plyronewins_txt.get_rect(center=self.screen_rect.center)) # Creates a surface with the text "ctrl" print on it using the plyr font self.txt = self.plyr.render("ctrl", True, (255, 255, 255)) # draws a round rectangle to the top left corner of the screen rrect( screen, (255, 255, 255), pygame.Rect(0 * self.director.scale, 0 * self.director.scale, 63 * self.director.scale, 30 * self.director.scale), 9 * self.director.scale, 3 * self.director.scale) # The text ctrl is printed in the top left corner of the screen screen.blit(self.txt, (25 * self.director.scale, 7 * self.director.scale)) #Draws a filled triangle to the screen with the points being at the specified coordinates gfxdraw.filled_trigon(screen, 5 * self.director.scale, 15 * self.director.scale, 20 * self.director.scale, 22 * self.director.scale, 20 * self.director.scale, 8 * self.director.scale, (255, 150, 44)) #Draws an anti-aliased triangle outline with the points being at the specified coordinates gfxdraw.aatrigon(screen, 5 * self.director.scale, 15 * self.director.scale, 20 * self.director.scale, 22 * self.director.scale, 20 * self.director.scale, 8 * self.director.scale, (255, 150, 44)) #pygame.mixer.music.stop() # This conditional statement executes if player two has won if self.plyrtwowins: # The text "Player Two Wins" is printed to the middle of the screen screen.blit( self.plyrtwowins_txt, self.plyronewins_txt.get_rect(center=self.screen_rect.center)) # Creates a surface with the text "ctrl" print on it using the plyr font self.txt = self.plyr.render("ctrl", True, (255, 255, 255)) # draws a round rectangle to the top left corner of the screen rrect( screen, (255, 255, 255), pygame.Rect(0 * self.director.scale, 0 * self.director.scale, 63 * self.director.scale, 30 * self.director.scale), 9 * self.director.scale, 3 * self.director.scale) # The text ctrl is printed in the top left corner of the screen screen.blit(self.txt, (25 * self.director.scale, 7 * self.director.scale)) #Draws a filled triangle to the screen with the points being at the specified coordinates gfxdraw.filled_trigon(screen, 5 * self.director.scale, 15 * self.director.scale, 20 * self.director.scale, 22 * self.director.scale, 20 * self.director.scale, 8 * self.director.scale, (255, 150, 44)) #Draws an anti-aliased triangle outline with the points being at the specified coordinates gfxdraw.aatrigon(screen, 5 * self.director.scale, 15 * self.director.scale, 20 * self.director.scale, 22 * self.director.scale, 20 * self.director.scale, 8 * self.director.scale, (255, 150, 44)) #pygame.mixer.music.stop() # This conditional statement executes if there has been a draw if self.plyrdraw: # Creates a surface with the text "ctrl" print on it using the plyr font self.txt = self.plyr.render("ctrl", True, (255, 255, 255)) # The text "draw" is printed to the middle of the screen screen.blit( self.plyrdraw_txt, self.plyrdraw_txt.get_rect(center=self.screen_rect.center)) # draws a round rectangle to the top left corner of the screen rrect( screen, (255, 255, 255), pygame.Rect(0 * self.director.scale, 0 * self.director.scale, 63 * self.director.scale, 30 * self.director.scale), 9 * self.director.scale, 3 * self.director.scale) # The text ctrl is printed in the top left corner of the screen screen.blit(self.txt, (25 * self.director.scale, 7 * self.director.scale)) #Draws a filled triangle to the screen with the points being at the specified coordinates gfxdraw.filled_trigon(screen, 5 * self.director.scale, 15 * self.director.scale, 20 * self.director.scale, 22 * self.director.scale, 20 * self.director.scale, 8 * self.director.scale, (255, 150, 44)) #Draws an anti-aliased triangle outline with the points being at the specified coordinates gfxdraw.aatrigon(screen, 5 * self.director.scale, 15 * self.director.scale, 20 * self.director.scale, 22 * self.director.scale, 20 * self.director.scale, 8 * self.director.scale, (255, 150, 44)) #pygame.mixer.music.stop() def print_tails(self, screen): # This draws each of the first snake's tail segments to the screen for i in range(len(self.tail_1)): pygame.draw.rect(screen, self.tail_1[i].color, self.tail_1[i].rect()) # This draws each of the second snake's tail segments to the screen for i in range(len(self.tail_2)): pygame.draw.rect(screen, self.tail_2[i].color, self.tail_2[i].rect()) def draw_grid(self, screen): #Draws the grid lines to the screen for i in range(40): # draw vertical grid lines pygame.draw.line(screen, (56, 56, 56), (i * 10 * self.director.scale, 0), (i * 10 * self.director.scale, self.h)) for i in range(40): # draw horizontal grid lines pygame.draw.line(screen, (56, 56, 56), (0, i * 10 * self.director.scale), (self.w, i * 10 * self.director.scale)) # This function decides whether or not an apple has been eaten by the snake and if so it then adds a new segment to # the snake and spawns in a new apple def did_eat(self): # Boolean value representing whether or not a space is empty. This matters as you don't want the apple spawning # on the same spot as part of the snake's body spaceEmpty = True # This conditional statement checks whether or not the apple and head of the first snake occupy the same spot if self.head_1.x == self.apple.x and self.head_1.y == self.apple.y: # The integer value of what will be the previous X value prevX = self.apple.x # The integer value of what will be the previous Y value prevY = self.apple.y # The integer value of what will be the new current X value. It is randomly generated currX = myround( random.randint(0, self.w / 10 - 10 * self.director.scale), 10 * self.director.scale) * 10 + 1 * self.director.scale # This loop checks if the previous X value and the newly generated X value are the same, if so it will # generate a new one until they no longer match. This stops the apple from spawning in place while prevX == currX: currX = myround( random.randint(0, self.w / 10 - 10 * self.director.scale), 10 * self.director.scale) * 10 + 1 * self.director.scale # The integer value of what will be the new current Y value. It is randomly generated currY = myround( random.randint(0, self.h / 10 - 10 * self.director.scale), 10 * self.director.scale) * 10 + 1 * self.director.scale # This loop checks if the previous Y value and the newly generated Y value are the same, if so it will # generate a new one until they no longer match. This stops the apple from spawning in place while prevY == currY: currY = myround( random.randint(0, self.h / 10 - 10 * self.director.scale), 10 * self.director.scale) * 10 + 1 * self.director.scale # The next 11 lines essentially do what the previous lines have except it checks each segements of the tail # so that the apple doesn't spawn in one of their spots for i in self.tail_1: if currX == i.x and currY == i.y: spaceEmpty = False while not spaceEmpty and prevX != currX and prevY != currY: currX = myround( random.randint( 0, self.w / 10 - 10 * self.director.scale), 10 * self.director.scale) * 10 + 1 * self.director.scale currY = myround( random.randint( 0, self.h / 10 - 10 * self.director.scale), 10 * self.director.scale) * 10 + 1 * self.director.scale for j in self.tail_1: if currX == j.x and currY == j.y: spaceEmpty = False break spaceEmpty = True # Once all has been said and done the apple's x and y values are changed to currX and currY self.apple.x = currX self.apple.y = currY # A new segment is added to the end of the first player's snake self.tail_1.append( Entity( self.tail_1[len(self.tail_1) - 1].x * self.director.scale, self.tail_1[len(self.tail_1) - 1 * self.director.scale].y, 9 * self.director.scale, 9 * self.director.scale, self.director.p1color)) # This conditional statement checks whether or not the apple and head of the second snake occupy the same spot if self.head_2.x == self.apple.x and self.head_2.y == self.apple.y: # The integer value of what will be the previous X value prevX = self.apple.x # The integer value of what will be the previous Y value prevY = self.apple.y # The integer value of what will be the new current X value. It is randomly generated currX = myround( random.randint(0, self.w / 10 - 10 * self.director.scale), 10 * self.director.scale) * 10 + 1 * self.director.scale # This loop checks if the previous X value and the newly generated X value are the same, if so it will # generate a new one until they no longer match. This stops the apple from spawning in place while prevX == currX: currX = myround( random.randint(0, self.w / 10 - 10 * self.director.scale), 10 * self.director.scale) * 10 + 1 * self.director.scale # The integer value of what will be the new current Y value. It is randomly generated currY = myround( random.randint(0, self.h / 10 - 10 * self.director.scale), 10 * self.director.scale) * 10 + 1 * self.director.scale # This loop checks if the previous Y value and the newly generated Y value are the same, if so it will # generate a new one until they no longer match. This stops the apple from spawning in place while prevY == currY: currY = myround( random.randint(0, self.h / 10 - 10 * self.director.scale), 10 * self.director.scale) * 10 + 1 * self.director.scale # The next 11 lines essentially do what the previous lines have except it checks each segements of the tail # so that the apple doesn't spawn in one of their spots for i in self.tail_2: if currX == i.x and currY == i.y: spaceEmpty = False while not spaceEmpty and prevX != currX and prevY != currY: currX = myround( random.randint( 0, self.w / 10 - 10 * self.director.scale), 10 * self.director.scale) * 10 + 1 * self.director.scale currY = myround( random.randint( 0, self.h / 10 - 10 * self.director.scale), 10 * self.director.scale) * 10 + 1 * self.director.scale for j in self.tail_2: if currX == j.x and currY == j.y: spaceEmpty = False break spaceEmpty = True # Once all has been said and done the apple's x and y values are changed to currX and currY self.apple.x = currX self.apple.y = currY # A new segment is added to the end of the first player's snake self.tail_2.append( Entity( self.tail_2[len(self.tail_2) - 1].x * self.director.scale, self.tail_2[len(self.tail_2) - 1 * self.director.scale].y, 9 * self.director.scale, 9 * self.director.scale, self.director.p2color)) def is_collide(self): # This conditional statement checks if the head of the two snakes occupy the same space. If so it sets the # player draw variable to true and ends the execution of the method if self.head_1.x == self.head_2.x and self.head_1.y == self.head_2.y: self.plyrdraw = True # Causes the currently playing song to stop playing pygame.mixer.music.stop() return # This loop iterates through each tail segment in the first snake's tail for i in self.tail_1: # This conditional statement checks if the current tail segment and the head of the second snake occupy the # same space. If so it sets the player one wins variable to true if self.head_2.x == i.x and self.head_2.y == i.y: self.plyronewins = True # Causes the currently playing song to stop playing pygame.mixer.music.stop() return # This conditional statement checks if the first snake's head has gone out of bounds and if so then it sets # the player two wins variable to true if self.head_1.x == i.x and self.head_1.y == i.y or self.head_1.x < 0 or self.head_1.x > self.w or self.head_1.y < 0 or self.head_1.y > self.h: self.plyrtwowins = True # Causes the currently playing song to stop playing pygame.mixer.music.stop() return # This loops iterates through each tail segment in the second snake's tail for i in self.tail_2: # This conditional statement checks if the current tail segment and the head of the first snake occupy the # same space. If so it sets the player two wins variable to true if self.head_1.x == i.x and self.head_1.y == i.y: self.plyrtwowins = True # Causes the currently playing song to stop playing pygame.mixer.music.stop() return # This conditional statement checks if the second snake's head has gone out of bounds and if so then it sets # the player one wins variable to true if self.head_2.x == i.x and self.head_2.y == i.y or self.head_2.x < 0 or self.head_2.x > self.w or self.head_2.y < 0 or self.head_2.y > self.h: self.plyronewins = True # Causes the currently playing song to stop playing pygame.mixer.music.stop() return
def restart(g): player = Dungeon.getPlayer(g["dungeon"]) Entity.setHealth(player, Entity.getMaxHealth(player)) Dungeon.generate(g["dungeon"], player)
def MakeOrb( parent, orbType, pos ): orb = Entity() orb.addComponent( Position( pos.x, pos.y ) ) orb.addComponent( SpellComponent( orbType, parent ) ) orb.addComponent( SpellRenderable( orbType, parent ) ) return orb
def GetEntityBlueprints(entityRoot): """This is separate from ChangeState() because this chunk needs to be able to be recursive. This is necessary for the Entity_List entity to be able to hold entities (which may also end up being Entity_Lists, Giants may work as a special Entity_List.) This essentially just creates Entities recursively and stores them inside of its parent Entity like it's an attribute. @param entityRoot This is an ElementTree Node object and this is where we'll be using to look for the attributes (which may be entities, and if so recursion is necessary.) @return An Entity object that contains the attributes (which may have Entities within it) that were specified within the main xml file for the game.""" entity = None iEntityDrawPriority = -1 if entityRoot.find("drawPriority") != None: iEntityDrawPriority = int(entityRoot.find("drawPriority").text) #This checks to see if there is a function that exists that will assemble this entity. if entityRoot.find("assembleFunc") != None: #This will hold all of the attributes needed to assemble the entity (using the xml files to get the data later on.) dEntityAttribs = {} #This will loop through all of the attributes for the current entity # Note that this only iterates over the immediate children. for attrib in entityRoot.find("Attributes"): #Sounds are ultimately stored in the AssetManager, but pointers to those sounds are within entities. if attrib.tag == 'Sound': #THis will start a new list of Sounds if we haven't already loaded one into this entity's attributes. if dEntityAttribs.get(attrib.tag, None) == None: dEntityAttribs[attrib.tag] = {} #Query the AssetManager for a sound that is associated with this entity, then throw that into the dictionary of attributes! dEntityAttribs[attrib.tag][ attrib.attrib["name"]] = AstManager._Get_Sound( attrib.attrib["name"], attrib.text) #Music are ultimately stored in the AssetManager, but pointers to the music is within entities. elif attrib.tag == 'Music': #THis will start a new list of Musics if we haven't already loaded one into this entity's attributes. if dEntityAttribs.get(attrib.tag, None) == None: dEntityAttribs[attrib.tag] = {} dEntityAttribs[attrib.tag][ attrib.attrib["name"]] = AstManager._Get_Music( attrib.attrib['name'], attrib.text) #Textures are ultimately stored in the AssetManager, but pointers to those textures are within entities. elif attrib.tag == 'Texture': #THis will start a new list of Textures if we haven't already loaded one into this entity's attributes. if dEntityAttribs.get(attrib.tag, None) == None: dEntityAttribs[attrib.tag] = {} #Query the AssetManager for a texture that is associated with this entity, then throw that into the dictionary of attributes! dEntityAttribs[attrib.tag][ attrib.attrib["name"]] = AstManager._Get_Texture( attrib.attrib['name'], attrib.text) #This is for the tileAtlas' elif attrib.tag == 'RenderState': #THis will start a new list of sf.RenderStates if we haven't already loaded one into this entity's attributes. if dEntityAttribs.get(attrib.tag, None) == None: dEntityAttribs[attrib.tag] = {} #Query the AssetManager for a sf.RenderState that is associated with this entity, then throw that into the dictionary of attributes! dEntityAttribs[attrib.tag][ attrib.attrib["name"]] = AstManager._Get_Render_State( attrib.attrib['name'], attrib.text) #Fonts are also in the AssetManager like textures. elif attrib.tag == 'Font': #THis will start a new list of Fonts if we haven't already loaded one into this entity's attributes. if dEntityAttribs.get(attrib.tag, None) == None: dEntityAttribs[attrib.tag] = {} #Query the AssetManager for a font that is associated with this entity, then throw that into the dictionary of attributes! dEntityAttribs[attrib.tag][ attrib.attrib["name"]] = AstManager._Get_Font( attrib.attrib['name'], attrib.text) #The Collision_Body needs a list of shapes represented by dictionaries of attribs for each shape. This # assembles that data representation so that not just entity assemblers are required for collisidable entities. elif attrib.tag == 'CollisionBody': #THis will start a new list of CollisionShapes if we haven't already loaded one into this entity's attributes. if dEntityAttribs.get(attrib.tag, None) == None: dEntityAttribs[attrib.tag] = {} #This list of shapes will define the collision body. lShapes = [] #Iterate through the collision shapes for cShape in attrib: dShapeAttribs = {} for shapeAttrib in cShape: dShapeAttribs[shapeAttrib.tag] = shapeAttrib.text lShapes.append(dShapeAttribs) #Bodies are marked by their name and are defined by a list of shapes. dEntityAttribs[attrib.tag][attrib.attrib["name"]] = lShapes #For storing entities within entities. This was originally for the EntityPQueue. elif attrib.tag == 'entity': #THis will start a new list of Entities if we haven't already loaded one into this entity's attributes. if dEntityAttribs.get(attrib.tag, None) == None: dEntityAttribs[attrib.tag] = {} #Here's the one and only recursive call. The base case occurs # when there aren't anymore nested Entities. dEntityAttribs[attrib.tag][ attrib.attrib["name"]] = GetEntityBlueprints(attrib) else: #Anything else will just be put in the dictionary as an attribute dEntityAttribs[attrib.tag] = attrib.text assembleFunc = ClassRetrieval.getClass( entityRoot.find('assembleFunc').text) #Here we're using the Assemble*() function associated with the name of this entity to assemble the entity so that #we can add it to the EntityManager. #And all Assemble*() functions will use the same arguments(using a dictionary to allow dynamic arguments.) entity = assembleFunc(entityRoot.attrib['name'], entityRoot.attrib['type'], iEntityDrawPriority, dEntityAttribs) else: #Here we will add in a default entity instance. entity = Entity.Entity(entityRoot.attrib['name'], entityRoot.attrib['type'], iEntityDrawPriority, {}) #THis adds in the components that exist in the xml file for this entity (it allows custom/variations of entities to exist.) for component in entityRoot.findall('Component'): componentClass = ClassRetrieval.getClass(component.attrib['name']) #This will add in a component into the entity we just created. #And note that it is giving the component a dictionary of the data in the xml files. entity._Add_Component( componentClass( {DataTag.tag: DataTag.text for DataTag in component})) return entity
async def actions(ctx): if(Entity.player_exists(ctx.message.author.id)): player = [player for player in Entity.players if player.player_id == ctx.message.author.id][0] for i in range(len(player.available_commands)): await bot.say(str(i+1) + " - " +player.available_commands[i])
def run(r, dt): player = getPlayer(r) for currentArrow in r["arrows"]: newX, newY = Arrow.live(currentArrow, dt) if isFree(r, newX, newY): Entity.setPosition(currentArrow, newX, newY) else: r["arrows"].remove(currentArrow) # Si une entité (Mob ou Joueur) a été touché, il faut lui enlever de la vie hurtedEntity = getEntityByPosition(r, newX, newY) if hurtedEntity != -1: health = Entity.getHealth(hurtedEntity) resistance = Entity.getResistance(hurtedEntity) newHealth = health - (Arrow.getDamage(currentArrow)/resistance) Entity.setHealth(hurtedEntity, newHealth) r["arrows"].remove(currentArrow) for currentEntity in r["entity"]: if Entity.getType(currentEntity) == "player": newX, newY = Player.live(currentEntity, dt) if Entity.getType(currentEntity) == "ghost": # Le ghost lance des flèches sur le joueur: if random.randint(0, 100) < 2: launchArrow(r, currentEntity) newX, newY = Mob.live(currentEntity, player, 3, dt) if Entity.getType(currentEntity) == "guardian": newX, newY = Mob.live(currentEntity, player, 6, dt) # Le guardian lance des flèches sur le joueur: if random.randint(0, 100) < 5: launchArrow(r, currentEntity) if Entity.getType(currentEntity) == "boss": newX, newY = Mob.live(currentEntity, player, 12, dt) # Le boss peut lancer des fleches de maniere random if random.randint(0, 100) < 20: launchArrow(r, currentEntity) # Déplacement autorisé s'il n'y pas d'obstacle ou de mob / joueur (ni de coffres) if isFree(r, newX, newY) and getEntityByPosition(r, newX, newY, currentEntity) == -1 and getChestByPosition(r, newX, newY) == -1: Entity.setPosition(currentEntity, newX, newY) # Despawn du monstre quand sa vie tombe à 0 if Entity.getHealth(currentEntity) <= 0 and Entity.getType(currentEntity) != "player": r["entity"].remove(currentEntity) # Si on a tué le Boss, alors on a gagné if Entity.getHealth(currentEntity) <= 0 and Entity.getType(currentEntity) == "boss": Entity.setMaxHealth(player, Entity.getMaxHealth(player) + 50) Entity.setHealth(player, Entity.getMaxHealth(player)) Entity.setStrength(player, Entity.getStrength(player) + 0.30) Entity.setResistance(player, Entity.getResistance(player) + 0.20) return "win" return ""
def main(self, lives_remaining, curr_score, currPlayerShip, currTime=0): '''Invokes main game state. Takes lives_remaining (lives remaining), curr_score (current score), currPlayerShip (a reference to the current player entity), and currTime (in seconds).''' ##Level Loader setup starting_events = self.loader.getEvents(0) ending_events = self.loader.getEndBehavior() player_score = curr_score player_lives = lives_remaining bg_filename = starting_events.get('background') if currPlayerShip: playerShip = currPlayerShip playerShip.rect.center = (SCREEN_WIDTH // 2, SCREEN_HEIGHT - 100) else: playerShip = starting_events.get('player') if playerShip: playerShip = playerShip[0] ##Check for end of level conditions if ending_events: endtime = ending_events.get('time') spawn_boss = ending_events.get('boss') boss_spawned = False else: endtime = -1 spawn_boss = False ##Background setup background = pygame.Surface(self.screen.get_size()) background = background.convert() bg, bg_rect = ASSET_MANAGER.getAsset( BACKGROUND_PATH.joinpath(bg_filename)) bg_size = bg.get_size() bg_w, bg_h = bg_size bg_x = 0 bg_y = 0 bg_x1 = 0 bg_y1 = -bg_h background.fill(BLACK) background.blit(bg, ORIGIN) column = pygame.Surface((COLUMN_WIDTH, SCREEN_HEIGHT)) column.fill(BLACK) inst_block = draw_instructions() #Initialize sprite groups player_sprites_invul = pygame.sprite.Group() player_sprites = pygame.sprite.GroupSingle(playerShip) player_bullet_sprites = pygame.sprite.Group() player_bomb_sprites = pygame.sprite.Group( ) #not sure if bombs should be on the lowest layer bomb_explosion_sprites = pygame.sprite.Group( ) # the bomb explosion should damage enemies on collision, so it is on the same layer as enemies enemy_sprites = pygame.sprite.Group() boss_sprites = pygame.sprite.GroupSingle() enemy_bullet_sprites = pygame.sprite.Group() items = pygame.sprite.Group() explosions = pygame.sprite.Group() chargeShot_Anim = pygame.sprite.GroupSingle() going = True self.clock.tick( ) ##need to dump this particular return value of tick() to give accurate time. time_since_start = currTime * 1000 #convert to milliseconds next_level = True invul_timer = 120 ##frames of invulnerability post-death regen_timer = 6 bomb_timer = 120 time_to_end = 9999 ## No levels this long, so effectively infinity. ##Clock time setup while going: ##check if there is a boss spawned (to figure out when to end the level post boss death) if boss_spawned and time_to_end == 9999: if len(boss_sprites) == 0: time_to_end = time_since_start // 1000 + 5 if time_since_start // 1000 == time_to_end: going = False ##Beginning of the loop checking for death and lives remaining. if len(player_sprites) == 0 and not playerShip.invul_flag: player_lives -= 1 if player_lives: self.death_loop() playerShip = Entity.Player( 'spitfire', MISC_SPRITES_PATH.joinpath('SweetShip.png'), "arrows") playerShip.invul_flag = True player_sprites_invul.add(playerShip) else: self.game_over(player_score) if self.hs_list.belongsOnList(player_score): name = self.add_to_hs( 'You\'ve set a high score! Enter your initials!') self.hs_list.add(name, player_score) #break (potentially cleaner than setting going to False) going = False next_level = False ##check if the invuln timer is complete if invul_timer == 0 and len(player_sprites_invul) != 0: playerShip.invul_flag = False player_sprites_invul.remove(playerShip) player_sprites.add(playerShip) invul_timer = 120 ##Look out for QUIT events (hitting the x in the corner of the window) or escape to quit. for event in pygame.event.get(): if event.type == QUIT: going = False next_level = False pygame.mouse.set_visible(True) ##We need the mouse here. elif event.type == KEYDOWN: if event.key == K_ESCAPE: # going = False # next_level = False pygame.mouse.set_visible( True) ##We need the mouse here. going, next_level = self.ask_to_save( playerShip.health, playerShip.shield, playerShip.weapon.name, playerShip.bombs_remaining, player_score, player_lives, time_since_start // 1000) if event.key == K_F12: self.__fs_toggle = not self.__fs_toggle if self.__fs_toggle: pygame.display.set_mode( WINDOW_OPTIONS_FULLSCREEN[0], WINDOW_OPTIONS_FULLSCREEN[1]) else: pygame.display.set_mode(WINDOW_OPTIONS_WINDOWED[0], WINDOW_OPTIONS_WINDOWED[1]) if event.key == K_PAUSE: self.pause_screen() if DEBUG: if event.key == K_F2 and len(player_sprites) == 0: playerShip = Entity.Player( 'spitfire', MISC_SPRITES_PATH.joinpath('SweetShip.png'), "arrows") player_sprites.add(playerShip) if event.key == K_F11: enemy_sprites.empty() enemy_bullet_sprites.empty() sec_running = time_since_start // 1000 #need seconds since start events = self.loader.getEvents(sec_running) enemies_to_add = [] boss_to_add = [] enemy_bullets_to_add = [] items_to_add = [] if events: enemies_to_add = events.get('enemy', []) boss_to_add = events.get('boss_sprite', []) enemy_bullets_to_add = events.get('bullets', []) items_to_add = events.get('items', []) if sec_running >= endtime and not spawn_boss: if len(enemy_sprites) == 0 and len(enemy_bullet_sprites) == 0: going = False if enemies_to_add: enemy_sprites.add(enemies_to_add) if boss_to_add: boss_spawned = True boss_sprites.add(boss_to_add) if enemy_bullets_to_add: enemy_bullet_sprites.add(enemy_bullets_to_add) if items_to_add: items.add(items_to_add) #chargeShot specific weapon firing if playerShip.weapon.name in playerShip.weapon.chargeShot_dic: if playerShip.weapon.chargeShot_charging_flag == True: keys = pygame.key.get_pressed() if not keys[pygame.K_SPACE]: playerShip.weapon.chargeShot_charging_flag = False playerShip.weapon.chargeShot_firing_flag = True if playerShip.weapon.name in playerShip.weapon.chargeShot_dic: if playerShip.weapon.chargeShot_firing_flag == True: if playerShip.weapon.chargeShot_counter >= 0: bullet = playerShip.fire() bullet.damage = playerShip.weapon.weapon_damage #print(bullet.damage) player_bullet_sprites.add(bullet) playerShip.weapon.chargeShot_counter -= 1 else: playerShip.weapon.chargeShot_firing_flag = False keys = pygame.key.get_pressed() addBullet = playerShip.control(keys, FRAMERATE) if addBullet: #special behavior for chargeShot if playerShip.weapon.name in playerShip.weapon.chargeShot_dic: #this is the chargeShot "charging" code if playerShip.weapon.chargeShot_firing_flag is False: playerShip.weapon.chargeShot_charging_flag = True if playerShip.weapon.chargeShot_counter <= playerShip.weapon.chargeShot_counter_max: playerShip.weapon.chargeShot_counter += playerShip.weapon.chargeShot_counter_rate #print(playerShip.weapon.name, playerShip.weapon.chargeShot_counter) if playerShip.weapon.chargeShot_anim_visible is False: playerShip.weapon.chargeShot_anim_visible = True new_charging = weapon.ChargingAnim( playerShip.rect.centerx, playerShip.rect.centery, playerShip) chargeShot_Anim.add(new_charging) #normal bullet behavior else: self.fire_spitfire.play() bullet = playerShip.fire() player_bullet_sprites.add(bullet) if playerShip.drop_bomb_flag is True: bomb = playerShip.drop_bomb() bomb.play_sound() playerShip.drop_bomb_flag = False player_bomb_sprites.add(bomb) playerShip.curr_bomb = bomb if playerShip.curr_bomb is not None and playerShip.curr_bomb.bomb_explode is True: new_explosion = bomb_explosion.BombExplosion( playerShip.curr_bomb.centerx, playerShip.curr_bomb.centery) new_explosion.play_sound() bomb_explosion_sprites.add(new_explosion) playerShip.curr_bomb.bomb_explode = False playerShip.curr_bomb = None ##Helper to call update() on each sprite in the group. # player_sprites.update() player_damage = playerShip.update() if player_damage: explosions.add(player_damage) player_bullet_sprites.update() player_bomb_sprites.update() for sprite in enemy_sprites: bullet = sprite.update() if bullet: enemy_bullet_sprites.add(bullet) for sprite in boss_sprites: damage, bullets = sprite.update(playerShip.rect.center) if damage: explosions.add(damage) if bullets: enemy_bullet_sprites.add(bullets) enemy_bullet_sprites.update() items.update() explosions.update() bomb_explosion_sprites.update() chargeShot_Anim.update() ##Collision/Out of Bounds detection. if player_sprites.sprite != None: collision = pygame.sprite.spritecollideany( player_sprites.sprite, enemy_bullet_sprites) if collision: self.explode.play() playerShip.take_damage(5) collision.kill() else: collision = pygame.sprite.spritecollideany( player_sprites.sprite, enemy_sprites) if collision: self.explode.play() playerShip.take_damage(1) else: collision = pygame.sprite.spritecollideany( player_sprites.sprite, boss_sprites) if collision: self.explode.play() playerShip.take_damage(1) if playerShip.health <= 0: chargeShot_Anim.empty() playerShip.kill() for sprite in items: collision = pygame.sprite.spritecollideany( sprite, player_sprites) if collision: sprite.visible = 0 player_score += sprite.value if sprite.checkWeapon(): upgrade = weapon.upgrade(sprite.weapon_name, playerShip.weapon.name) playerShip.weapon = weapon.Weapon(upgrade) if sprite.checkBomb(): playerShip.bombs_remaining += 1 if sprite.checkHealthPack(): if playerShip.health < playerShip.max_health: new_health = playerShip.health + playerShip.healthpack if new_health >= playerShip.max_health: playerShip.health = playerShip.max_health else: playerShip.health += playerShip.healthpack sprite.kill() else: collision = pygame.sprite.spritecollideany( sprite, player_sprites_invul) if collision: sprite.visible = 0 if sprite.checkWeapon(): upgrade = weapon.upgrade(sprite.weapon_name, playerShip.weapon.name) playerShip.weapon = weapon.Weapon(upgrade) sprite.kill() for sprite in enemy_sprites: collision = pygame.sprite.spritecollideany( sprite, player_bullet_sprites) if collision: sprite.take_damage( playerShip.weapon.getDamage(playerShip.weapon.name)) collision.visible = 0 collision.kill() else: collision = pygame.sprite.spritecollideany( sprite, bomb_explosion_sprites) if collision: sprite.take_damage(playerShip.weapon.getDamage('bomb')) if sprite.health <= 0: new_explosion = explosion.ExplosionSprite( sprite.rect.centerx, sprite.rect.centery) new_explosion.play_sound() explosions.add(new_explosion) player_score += sprite.value item_drop = sprite.getDrop() if item_drop is not None: items.add(item_drop) if sprite.visible == 0: sprite.kill() if boss_sprites.sprite != None: collision_dict = pygame.sprite.groupcollide( player_bullet_sprites, boss_sprites, True, False) for key in collision_dict: boss_sprites.sprite.take_damage(key.damage) collision = pygame.sprite.spritecollideany( boss_sprites.sprite, bomb_explosion_sprites) if collision: boss_sprites.sprite.take_damage(2) if boss_sprites.sprite.health <= 0: new_explosion = explosion.ExplosionSprite( sprite.rect.centerx, sprite.rect.centery) new_explosion.play_sound() explosions.add(new_explosion) player_score += boss_sprites.sprite.point_value boss_sprites.sprite.kill() #sprite cleanup for sprite in player_bullet_sprites: if sprite.visible == 0: sprite.kill() for sprite in enemy_bullet_sprites: if sprite.visible == 0: sprite.kill() for sprite in explosions: if sprite.visible == 0: sprite.kill() for sprite in player_bomb_sprites: if sprite.visible == 0: sprite.kill() for sprite in bomb_explosion_sprites: if sprite.visible == 0: sprite.kill() for sprite in items: if sprite.visible == 0: sprite.kill() for sprite in chargeShot_Anim: if sprite.visible == 0: sprite.kill() bg_y1 += 1 bg_y += 1 self.screen.blit(bg, (bg_x, bg_y)) self.screen.blit(bg, (bg_x1, bg_y1)) if bg_y > bg_h: bg_y = -bg_h if bg_y1 > bg_h: bg_y1 = -bg_h if boss_spawned and boss_sprites.sprite != None: boss_bar, boss_bar_rect = draw_boss_bar( COLUMN_WIDTH, 50, boss_sprites.sprite.health / boss_sprites.sprite.max_health, boss_sprites.sprite.shield / boss_sprites.sprite.max_shield, (COLUMN_WIDTH * 2, SCREEN_HEIGHT - 100)) if boss_spawned: self.screen.blit(boss_bar, boss_bar_rect) explosions.draw(self.screen) bomb_explosion_sprites.draw(self.screen) chargeShot_Anim.draw(self.screen) player_bullet_sprites.draw(self.screen) player_bomb_sprites.draw(self.screen) enemy_bullet_sprites.draw(self.screen) items.draw(self.screen) if playerShip.invul_flag and invul_timer // 6 % 2 == 0: ##allows visual feedback that the player is invulnerable player_sprites_invul.draw(self.screen) player_sprites.draw(self.screen) enemy_sprites.draw(self.screen) boss_sprites.draw(self.screen) c1 = self.screen.blit(column, ORIGIN) c2 = self.screen.blit(column, (SCREEN_WIDTH - COLUMN_WIDTH, 0)) text = draw_text("Score: " + str(player_score), WHITE) self.screen.blit(text, ORIGIN) self.screen.blit(inst_block, (0, text.get_rect().bottom)) if DEBUG: debug_text = draw_text( 'FPS: ' + str(round(self.clock.get_fps(), 2)), WHITE) debug_rect = self.screen.blit(debug_text, (0, SCREEN_HEIGHT - 100)) self.screen.blit(debug_text, debug_rect) mission_timer_text = draw_text( 'Mission Time: ' + str(sec_running), WHITE) mission_timer_rect = self.screen.blit(mission_timer_text, (0, SCREEN_HEIGHT - 150)) self.screen.blit(mission_timer_text, mission_timer_rect) armor_bar, armor_bar_rect = draw_vertical_bar( RED, 50, SCREEN_HEIGHT - 400, (playerShip.health / playerShip.max_health), (COLUMN_WIDTH * 4 + 10, 200)) shield_bar, shield_bar_rect = draw_vertical_bar( BLUE, 50, SCREEN_HEIGHT - 400, (playerShip.shield / playerShip.max_shield), (COLUMN_WIDTH * 4 + 70, 200)) lives_left, lives_left_rect = draw_player_lives( player_lives, (COLUMN_WIDTH * 4 + 10, 10)) bombs_left, bombs_left_rect = draw_bombs_remaining( playerShip.bombs_remaining, (COLUMN_WIDTH * 4 + 40, 100)) self.screen.blit(lives_left, lives_left_rect) self.screen.blit(bombs_left, bombs_left_rect) self.screen.blit(armor_bar, armor_bar_rect) self.screen.blit(shield_bar, shield_bar_rect) pygame.display.flip() time_since_start += self.clock.tick_busy_loop(FRAMERATE) if playerShip.invul_flag: invul_timer -= 1 regen_timer -= 1 if regen_timer == 0: playerShip.regen() regen_timer = 6 if playerShip.bomb_wait == True: bomb_timer -= 1 if bomb_timer == 0: playerShip.bomb_wait = False bomb_timer = 120 if next_level: self.level_complete() return player_lives, player_score, next_level, playerShip