def run_game(): ''' 运行游戏主程序 :return: ''' # background_image_filename = 'resources/images/level_1.png' #'/Users/lufan/Python_CODE_03/super_mario_level_01/resources/images/level_1.png' # 初始化游戏并创建一个屏幕对象 pygame.init() ai_settings = Settings() # 创建一个窗口 screen = pygame.display.set_mode( (ai_settings.screen_width, ai_settings.screen_height)) # 设置窗口标题 pygame.display.set_caption('Super Mario Bros') # 初始化声音模块 pygame.mixer.init() # 加载音乐 pygame.mixer.music.load(r"resources/music/death.wav") # pygame.mixer.music.play() # 放置Mario mario = Mario(ai_settings, screen) marios = Group() # 敌人 enemy = Enemy(ai_settings, screen) enemy_shadow = Enemy_shadow(ai_settings, screen) enemies = Group() enemies.add(enemy) enemies.add(enemy_shadow) marios.add(mario) '''在这里加上所有的setup函数,设置初始状态''' ground_group = setup_ground() pipe_group = setup_pipes() step_group = setup_steps() ground_step_pipe_group = pygame.sprite.Group(ground_group, pipe_group, step_group) while True: # 检查音乐流播放,有返回True,没有返回False # 如果没有音乐流则选择播放 #监视键盘和鼠标事件 gf.check_events(ai_settings, screen, mario) centerx = mario.update() # print(centerx) enemies.update() '''在这里加入update函数,检测碰撞情况,并将handle_state(marios,enemies)也并入到update函数中''' gf.handle_state(marios, enemies) check_mario_x_collisions(mario, ground_step_pipe_group) check_mario_y_collisions(mario, ground_step_pipe_group) if mario.rect.y > 180 and (1048 < mario.rect.x < 1080) or (1319 < mario.rect.x < 1372) \ or (2396 < mario.rect.x < 2431) : mario.rect.y += 1 # if mario.rect.centerx == 393 and mario.rect.bottom > 170: # mario.rect.centerx = 393 # # if mario.rect.centerx > 393 and mario.rect.centerx < 428 and mario.rect.bottom > 170: # mario.rect.bottom = 170 gf.update_screen(ai_settings, screen, mario, enemy, enemy_shadow, centerx)
#print_maze(lvl_1, []); def newinput(): stdout.write("\u001b[31mDisease Name: " + disease + "\u001b[37m") #+ str(player.health) + "/4\u001b[37m") #\u001b[31m #\u001b[37m stdout.flush() player.move_dir = str(readkey()) enemyList = []; # xx,yy=random_x_y(lvl_1) # e1 = Enemy(xx,yy, "Einfacher Fiend") # xx,yy=random_x_y(lvl_1) # 2 different enemies # e2 = Enemy(xx,yy, random_enemy()) # e1.findPathTo(lvl_1, player.x, player.y); # enemyList.append(e1); # enemyList.append(e2) #enemyList.append(Enemy()) enemyList.append(Enemy(2, 2,enemy_type=random_enemy())); while True: os.system("clear") print_maze(lvl_1,enemyList) newinput() player.move(lvl_1)
def add_new_enemy(canvas, enemy_list): enemy = Enemy(canvas) enemy.draw_enemy() enemy_list.append(enemy)
def main(): '''main function of the game''' if os.name == 'nt': # System check. App works only on unix system # Caused by getch function and console clearing # Can be fixed by implementing msvcrt library print("This application is meant for unix devices.") print("Closing the program.") sleep(2) forcequit() player = Player() args = { # Define map numbers 'maps': { 0: "menu", 1: "respawn.map", 2: "forest.map", 3: "dungeon.map", 4: "boss.map", 5: "end.map", }, 'map_id': 0, 'board': [], 'current_choice': 1, 'last_input': '', 'direction': None, 'change': 0, 'enemies': [1, True], 'player': player, 'last_pos': '', } clear() while True: '''main loop of the game''' clear() # mapcheck ############################################ MAP MENU ######################################################## if args['map_id'] == 0: status = display_menu(args) if status is None: exit() elif status[0] == args['maps'][0]: args['map_id'] = 0 args['current_choice'] = status[1] args['last_input'] = status[2] else: args['map_id'] = status[0] args['last_pos'] = status[1] args['board'] = status[2] ############################################ MAP SPAWN ######################################################## elif args['map_id'] == 1: if args['last_pos'] is None: args['last_pos'] = (33, 60) change = move(args) args['last_pos'] = change[0] args['board'] = change[1] # If on certain map stay on that map # Can be implemented as a standalone function print_map(args['board']) user_input = getch() if user_input == 'p': clear(24, 80) break elif user_input == 'w': args['direction'] = 0 args['change'] = -1 change = move(args) args['last_pos'] = change[0] args['board'] = change[1] if change[2] is not None: args['map_id'] = change[2] args['board'] = unfile(args['maps'][change[2]]) args['last_pos'] = None args['enemies'] = [1, True] elif user_input == 's': args['direction'] = 0 args['change'] = 1 change = move(args) args['last_pos'] = change[0] args['board'] = change[1] elif user_input == 'a': args['direction'] = 1 args['change'] = -1 change = move(args) args['last_pos'] = change[0] args['board'] = change[1] elif user_input == 'd': args['direction'] = 1 args['change'] = 1 change = move(args) args['last_pos'] = change[0] args['board'] = change[1] elif user_input == 'i': clear() inventory(player) else: exit() ############################################ MAP FOREST ######################################################## elif args['map_id'] == 2: enemies_left = 0 print(enemies_left, ' b4') if args['last_pos'] is None: args['last_pos'] = (3, 50) change = move(args) args['last_pos'] = change[0] args['board'] = change[1] if args['enemies'][1]: for i in range(10): if randint(0, 1): args['enemies'].append(Enemy(1)) args['enemies'][0] += 1 args['enemies'][args['enemies'][0]].spawn( args['board']) args['board'][args['enemies'][ args['enemies'][0]].y_coord][args['enemies'][ args['enemies'][0]].x_coord] = args['enemies'][ args['enemies'][0]].enemy_char if args['enemies'][0] < 2: args['enemies'].append(Enemy(1)) args['enemies'][0] += 1 args['enemies'][args['enemies'][0]].spawn(args['board']) args['board'][args['enemies'][args['enemies'][0]].y_coord][ args['enemies'][args['enemies'][0]].x_coord] = args[ 'enemies'][args['enemies'][0]].enemy_char args['enemies'][1] = False print_map(args['board']) user_input = getch() if user_input == 'p': clear(24, 80) break elif user_input == 'w': args['direction'] = 0 args['change'] = -1 change = move(args) args['last_pos'] = change[0] args['board'] = change[1] if change[2] is not None: args['map_id'] = args['maps'][change[2]] elif user_input == 's': args['direction'] = 0 args['change'] = 1 change = move(args) args['last_pos'] = change[0] args['board'] = change[1] if change[2] is not None: args['map_id'] = args['maps'][change[2]] elif user_input == 'a': args['direction'] = 1 args['change'] = -1 change = move(args) args['last_pos'] = change[0] args['board'] = change[1] if change[2] is not None: args['map_id'] = maps[change[2]] elif user_input == 'd': args['direction'] = 1 args['change'] = 1 change = move(args) args['last_pos'] = change[0] args['board'] = change[1] if change[2] is not None: args['map_id'] = maps[change[2]] elif user_input == 'q': if player.potions > 0: player.life += player.level * 2 player.potions -= 1 elif user_input == 'i': clear() inventory(player) else: exit() for line in args['board']: if args['enemies'][2].enemy_char in line: print(line) enemies_left += 1 print(enemies_left, ' aftr') if enemies_left == 0: print("Level clear!") sleep(1) args['map_id'] = 1 args['current_choice'] = 1 args['board'] = unfile(args['maps'][1]) args['last_pos'] = None ############################################ MAP DUNGEON ######################################################## elif args['map_id'] == 3: enemies_left = 0 clear() if args['last_pos'] is None: args['last_pos'] = (19, 109) change = move(args) args['last_pos'] = change[0] args['board'] = change[1] if args['enemies'][1]: args['enemies_left'] = 0 for i in range(15): if randint(0, 1): args['enemies'].append(Enemy(2)) args['enemies'][0] += 1 args['enemies'][args['enemies'][0]].spawn( args['board']) args['board'][args['enemies'][ args['enemies'][0]].y_coord][args['enemies'][ args['enemies'][0]].x_coord] = args['enemies'][ args['enemies'][0]].enemy_char if args['enemies'][0] < 2: args['enemies'].append(Enemy(2)) args['enemies'][0] += 1 args['enemies'][args['enemies'][0]].spawn(args['board']) args['board'][args['enemies'][args['enemies'][0]].y_coord][ args['enemies'][args['enemies'][0]].x_coord] = args[ 'enemies'][args['enemies'][0]].enemy_char args['enemies'][1] = False print_map(args['board']) user_input = getch() if user_input == 'p': clear(24, 80) break elif user_input == 'w': args['direction'] = 0 args['change'] = -1 change = move(args) args['last_pos'] = change[0] args['board'] = change[1] if change[2] is not None: args['map_id'] = args['maps'][change[2]] elif user_input == 's': args['direction'] = 0 args['change'] = 1 change = move(args) args['last_pos'] = change[0] args['board'] = change[1] if change[2] is not None: args['map_id'] = args['maps'][change[2]] elif user_input == 'a': args['direction'] = 1 args['change'] = -1 change = move(args) args['last_pos'] = change[0] args['board'] = change[1] if change[2] is not None: args['map_id'] = maps[change[2]] elif user_input == 'd': args['direction'] = 1 args['change'] = 1 change = move(args) args['last_pos'] = change[0] args['board'] = change[1] if change[2] is not None: args['map_id'] = maps[change[2]] elif user_input == 'q': if player.potions > 0: player.life += player.level * 2 player.potions -= 1 elif user_input == 'i': clear() inventory(player) else: exit() for line in args['board']: if args['enemies'][2].enemy_char in line: enemies_left += 1 if enemies_left == 0: print("Level clear!") sleep(1) args['map_id'] = 1 args['current_choice'] = 1 args['board'] = unfile(args['maps'][1]) args['last_pos'] = None if args['player'].life == 0: clear() lost() sleep(3) args['map_id'] = 0 args['current_choice'] = 1 args['last_pos'] = None
def addEnemy(self, pos): Enemy(pos, self, self.enemies, self.allsprites)
def create_enemies(canvas, enemy_list): for i in range(0, 3): enemy = Enemy(canvas) enemy.draw_enemy() enemy_list.append(enemy)
from board import * from mario import Mario from enemies import Enemy, Boss from input import input_to, Get import os import sys from brick import * from random import randint from colorama import Fore, Style b1 = Board(20, 80) mP = Mario(1) enList = [Enemy(16, 20, 1), Enemy(16, 70, 1), Enemy(16, 120, 1), Enemy(16, 170, 1), Enemy(16, 220, 1), Enemy(16, 270, 1), Enemy(16, 320, 1), Enemy(16, 400, 1)] brickList = [] breakList = [] brickMap = [] breakMap = [] forbidden_list = [i+2 for i in range(10,400,50)] forbidden_list += [i+1 for i in range(10,400,50)]
def update(): global aPressed, gameMode, bPressed, cPressed, shuttleTimer, enemyTimer, bossTimer global gameState, scoreCtr, score, highscore, shakeX, bulletCount, health, rockSizes, crystalSizes, enemyShipSizes, bossShipSizes global upPressed, downPressed, leftPressed, rightPressed, explosionList, explosionFrames global shuttle, enemyList, bulletList, dropList, bombs, bossList, spaceman, pauseGame destroyScreen = False shipHitShuttle = False # Get screen shake amount (use on all x positions of objects!) ###################################### shakeX = shake.update() if gameState != STATE_PAUSE: # Update stars ###################################### for star in starList: star.update() # Update rocks ###################################### for boulders in rockList: boulders.update(rockSizes) ###################################### # Game state ###################################### if gameState == STATE_GAME: # Update the score for player survival ###################################### scoreCtr += 1 if scoreCtr % 10 == 0: score += 1 if cPressed: gameState = STATE_PAUSE cPressed = False # Bomb button ###################################### if bPressed: bPressed = False if bombs > 0: bombs -= 1 destroyScreen = True # Move player ###################################### shipXMove = 0 shipYMove = 0 if upPressed: shipYMove = -2 if downPressed: shipYMove = 2 if leftPressed: shipXMove = -2 if rightPressed: shipXMove = 2 player.movePlayer(shipXMove, shipYMove) # Update player ship flames ###################################### for flame in flameList: flame.update(player.getPlayerPos()[0], player.getPlayerPos()[1] + 20) # Update drops ###################################### if len(dropList) > 0: tmpCtr = 0 for dropItem in dropList: # Delete drop if out of screen if dropItem.update(): del dropList[tmpCtr] break # Check if player is over drop if detectHit(player.getPlayerPos()[0] + 7, player.getPlayerPos()[1] + 7, dropItem.returnPos()[0] - 2, dropItem.returnPos()[1] - 2, 14): # Health / green if dropItem.getType() == 0: audio.playSfx(sounds.health) health = 10 # Extra bullet / orange elif dropItem.getType() == 1: audio.playSfx(sounds.extraBullet) if bulletCount == 8: bulletCount += 1 elif bulletCount < 8: bulletCount += 2 # Explosion/bonus / blue else: audio.playSfx(sounds.bonus) score += 100 if bombs < 10: bombs += 1 del dropList[tmpCtr] break tmpCtr += 1 # Delete drop object ###################################### if tmpCtr > 0: gc.collect() # Check crystal collisions ###################################### if len(crystalList) > 0: crystalCtr = 0 delCrystal = False for crystal in crystalList: crystal.update() # Has player hit crystal? if detectHit(player.getPlayerPos()[0] + 7, player.getPlayerPos()[1] + 7, crystal.returnPos()[0], crystal.returnPos()[1], crystal.getSize()): del crystalList[crystalCtr] delCrystal = True score += 50 audio.playSfx(sounds.bonus) if crystal.returnPos()[1] >= 100: del crystalList[crystalCtr] delCrystal = True # Destroy if player bombed if destroyScreen: explosionList.append(Explosion(crystal.returnPos()[0], crystal.returnPos()[1], len(explosionFrames))) del crystalList[crystalCtr] delCrystal = True crystalCtr += 1 if delCrystal: gc.collect() # Check to see if new crystals need to be spawned ###################################### if random.getrandbits(7) > 126: tmpX = random.getrandbits(7) spdX = random.getrandbits(1) spdY = random.getrandbits(2) if spdY == 0: spdY = 1 crystalId = random.getrandbits(3) # Only 6 crystals to choose from if crystalId > 5: crystalId = 0 crystalList.append(Crystal(tmpX, -20, spdX, spdY, crystalId, crystalSizes[crystalId])) # Check rock collisions ###################################### for boulders in rockList: if detectHit(player.getPlayerPos()[0] + 7, player.getPlayerPos()[1] + 7, boulders.returnPos()[0], boulders.returnPos()[1], boulders.getSize()) and not shake.isShaking(): shake.setShake() explosionList.append(Explosion(boulders.returnPos()[0], boulders.returnPos()[1], len(explosionFrames))) boulders.resetYPos(rockSizes) # Reset as if it has exploded health -= 1 audio.playSfx(sounds.explosion01) if health <= 0: gameState = STATE_GAMEOVER audio.playSfx(sounds.gameOver) # Destroy if player bombed if destroyScreen: shake.setShake() explosionList.append(Explosion(boulders.returnPos()[0], boulders.returnPos()[1], len(explosionFrames))) boulders.resetYPos(rockSizes) # Update explosion ###################################### if len(explosionList) > 0: tmpId = 0 tmpCtr = 0 for explody in explosionList: tmpId += 1 if explody.getFrame() >= len(explosionFrames): tmpCtr = tmpId break explody.update() # Delete explosion object ###################################### if tmpCtr > 0: del explosionList[tmpCtr - 1] gc.collect() # Create random shuttle ###################################### if scoreCtr % shuttleTimer == 0: if random.getrandbits(1) == 1: shuttle[2] = True # Update shuttle ###################################### if shuttle[2]: shuttle[1] += 1 if destroyScreen: explosionList.append(Explosion(shuttle[0], shuttle[1], len(explosionFrames))) audio.playSfx(sounds.explosion01) # Spawn drop dropList.append(Drop(shuttle[0], shuttle[1])) # Check if player ship hit shuttle if detectHit(player.getPlayerPos()[0] + 7, player.getPlayerPos()[1] + 7, shuttle[0], shuttle[1], 10): explosionList.append(Explosion(shuttle[0], shuttle[1], len(explosionFrames))) audio.playSfx(sounds.explosion01) # Spawn drop dropList.append(Drop(shuttle[0], shuttle[1])) shipHitShuttle = True health -= 1 if health <= 0: gameState = STATE_GAMEOVER audio.playSfx(sounds.gameOver) if shuttle[1] > 90 or destroyScreen or shipHitShuttle: shuttle[2] = False # Hide it shuttle[1] = -30 # Set y pos to top shuttle[0] = random.getrandbits(7) # Random x pos # Update spaceman ###################################### if spaceman[2]: spcX = 0 spcY = 0 # Check if player caught him if detectHit(player.getPlayerPos()[0] + 7, player.getPlayerPos()[1] + 7, spaceman[0], spaceman[1], 12): score += 50 audio.playSfx(sounds.dropItem) # Reset him spaceman = [0, 0, False] # Move him down if spaceman[0] > -12 and spaceman[0] < 122: if spaceman[1] > -12 and spaceman[1] < 100: spcX = random.getrandbits(3) spcY = random.getrandbits(3) if spcX < 3: spcX = -1 else: spcX = 1 if spcY < 3: spcY = -1 else: spcY = 1 spaceman[0] += spcX spaceman[1] += spcY # disappear him if needed if spaceman[0] < 0 or spaceman[0] > 110: if spaceman[1] < 0 or spaceman[1] > 88: spaceman = [0, 0, False] # Then update enemies ###################################### if len(enemyList) > 0: tmpId = 0 tmpCtr = 0 for en in enemyList: tmpId += 1 # Check if enemy can shoot if en.update(): # Horizontal enemy if en.getSize() == 0: if en.returnPos()[0] > 0: bulletList.append(Bullet(en.returnPos()[0] + 4, en.returnPos()[1] + 15, 0, 2, 1)) audio.playSfx(sounds.enemyShot) # All others else: if en.returnPos()[1] > 0: bulletList.append(Bullet(en.returnPos()[0] + 4, en.returnPos()[1] + 15, -1, 2, 2)) bulletList.append(Bullet(en.returnPos()[0] + 4, en.returnPos()[1] + 15, 1, 2, 2)) audio.playSfx(sounds.enemyShot) # Is enemy out of the screen yet? if en.outOfScreen(): tmpCtr = tmpId break if destroyScreen: explosionList.append(Explosion(en.returnPos()[0], en.returnPos()[1], len(explosionFrames))) # Spawn drop dropList.append(Drop(en.returnPos()[0], en.returnPos()[1])) del enemyList[tmpCtr - 1] # Delete enemy object ###################################### if tmpCtr > 0: del enemyList[tmpCtr - 1] gc.collect() # Create random enemies ###################################### if scoreCtr % enemyTimer == 0: if len(enemyList) > 3: enemyListTmp = enemyList[len(enemyList) - 1] enemyList = [enemyListTmp] else: enemyList.append(Enemy()) # Create random bosses ###################################### if len(bossList) > 0: tmpId = 0 tmpCtr = 0 for boss in bossList: tmpId += 1 bossId = boss.getId() bossX = boss.returnPos()[0] bossY = boss.returnPos()[1] # Check if enemy can shoot if boss.update(): # Horizontal enemy if boss.getId() == 0 or boss.getId() == 2: if boss.returnPos()[0] > 0: bulletList.append(Bullet(bossX + (bossShipSizes[bossId] // 2), bossY + 17, 0, 2, bossId + 1)) audio.playSfx(sounds.enemyShot) # All others else: if boss.returnPos()[1] > 0: bulletList.append(Bullet(bossX + (bossShipSizes[bossId] // 2), bossY + 17, -1, 2, bossId + 1)) bulletList.append(Bullet(bossX + (bossShipSizes[bossId] // 2), bossY + 17, 1, 2, bossId + 1)) audio.playSfx(sounds.enemyShot) # Is enemy out of the screen yet? if boss.outOfScreen(): tmpCtr = tmpId break if destroyScreen: explosionList.append(Explosion(boss.returnPos()[0], boss.returnPos()[1], len(explosionFrames))) # Spawn drop dropList.append(Drop(boss.returnPos()[0], boss.returnPos()[1])) del bossList[tmpCtr - 1] # Delete enemy object ###################################### if tmpCtr > 0: del bossList[tmpCtr - 1] gc.collect() # Create random bosses ###################################### if scoreCtr % bossTimer == 0: if len(bossList) > 1: bossListTmp = bossList[len(bossList) - 1] bossList = [bossListTmp] else: bossList.append(Boss()) # Fire button ###################################### if aPressed: aPressed = False if bulletCount > 0: bulletList.append(Bullet(player.getPlayerPos()[0] + 5, player.getPlayerPos()[1], 0, -3, 0)) bulletCount -= 1 audio.playSfx(sounds.playerShot) # Update bullet positions ###################################### if len(bulletList) > 0: tmpId = 0 tmpCtr = 0 for bul in bulletList: tmpId += 1 bullX = bul.returnPos()[0] + 3 bullY = bul.returnPos()[1] + 2 bullId = bul.getId() # Check bullet collisions ###################################### # Check against shuttle if detectHit(bullX, bullY, shuttle[0], shuttle[1], 10) and bullId == 0: explosionList.append(Explosion(shuttle[0], shuttle[1], len(explosionFrames))) # Spawn drop dropList.append(Drop(shuttle[0], shuttle[1])) # Spawn spaceman spaceman[0] = shuttle[0] spaceman[1] = shuttle[1] spaceman[2] = True # Reset shuttle shuttle[2] = False # Hide it shuttle[1] = -20 # Set y pos to top shuttle[0] = random.getrandbits(7) # Random x pos tmpCtr = tmpId # Kill this bullet audio.playSfx(sounds.explosion01) # Explosion break # Check against enemies ###################################### tmpId2 = 0 tmpCtr2 = 0 for en in enemyList: tmpId2 += 1 enX = en.returnPos()[0] enY = en.returnPos()[1] if detectHit(bullX, bullY, enX, enY, enemyShipSizes[en.getSize()]) and bullId == 0: explosionList.append(Explosion(enX, enY, len(explosionFrames))) tmpCtr = tmpId # Kill this bullet tmpCtr2 = tmpId2 # Kill this enemy audio.playSfx(sounds.explosion01) # Explosion # Spawn drop dropList.append(Drop(enX, enY)) break # Delete enemy object ###################################### if tmpCtr2 > 0: del enemyList[tmpCtr2 - 1] # Check against bosses ###################################### tmpId3 = 0 tmpCtr3 = 0 for boss in bossList: tmpId3 += 1 bossId = boss.getId() bossX = boss.returnPos()[0] bossY = boss.returnPos()[1] if detectHit(bullX, bullY, bossX, bossY, bossShipSizes[bossId]) and bullId == 0: explosionList.append(Explosion(bossX + (bossShipSizes[bossId] // 2), bossY + 10, len(explosionFrames))) tmpCtr = tmpId # Kill this bullet # Check boss hitpoints if boss.getHitPoints() > 0: boss.addHitPoint(1) else: tmpCtr3 = tmpId3 # Kill this boss audio.playSfx(sounds.explosion01) # Explosion # Spawn drop dropList.append(Drop(bossX + (bossShipSizes[bossId] // 2), bossY + 10)) break # Delete boss object ###################################### if tmpCtr3 > 0: del bossList[tmpCtr3 - 1] # Check against rocks ###################################### for boulders in rockList: boulderX = boulders.returnPos()[0] boulderY = boulders.returnPos()[1] if detectHit(bullX, bullY, boulderX, boulderY, boulders.getSize()) and bullId == 0: explosionList.append(Explosion(boulderX, boulderY, len(explosionFrames))) tmpCtr = tmpId # Kill this bullet boulders.resetYPos(rockSizes) # Reset as if it has exploded audio.playSfx(sounds.explosion01) # Explosion break # Check against player ###################################### if detectHit(bullX, bullY, player.getPlayerPos()[0], player.getPlayerPos()[1], 16) and not shake.isShaking() and bullId != 0: shake.setShake() explosionList.append(Explosion(player.getPlayerPos()[0] + 7, player.getPlayerPos()[1] + 7, len(explosionFrames))) audio.playSfx(sounds.explosion01) # Explosion health -= 1 if health <= 0: gameState = STATE_GAMEOVER audio.playSfx(sounds.gameOver) # Explosion # Check if bullet is out of screen bounds ###################################### if bul.update(): tmpCtr = tmpId break # Delete bullet object ###################################### if tmpCtr > 0: del bulletList[tmpCtr - 1] gc.collect() # Slowly speed up object timers to make game harder over time ###################################### if scoreCtr % 80 == 0: if enemyTimer > 100: enemyTimer -= 1 if bossTimer > 200: bossTimer -=1 ###################################### # PAUSE ###################################### if gameState == STATE_PAUSE: if cPressed: cPressed = False gameState = STATE_GAME ###################################### # Game over state ###################################### if gameState == STATE_GAMEOVER: # Save score if more than highscore if score > highscore: updateScore("save", score) highscore = score if cPressed: cPressed = False gameState = STATE_MENU
def __init__(self): ## sets dimension of the screen and the background pygame.init() self.w = 900 self.h = 600 self.screen = pygame.display.set_mode((self.w, self.h), pygame.FULLSCREEN) self.background = pygame.image.load("background.png") ## creates all the objects and lists needed for the game self.player = Player(self.w, self.h, self.background) self.shooter = Shooter(self.player.x, self.player.y, self.player.d) self.shield = Shield(self.player.x, self.player.y, self.player.d) self.generator = Generator(self.player.x, self.player.y, self.player.d) self.bullet = Bullet(self.shooter.x, self.shooter.y, self.shooter.image_rotation) self.enemies = [Enemy(self.w, self.h)] self.enemies_2 = [] self.counter_enemies_2_dead = 0 self.collectible = Collectible(self.w, self.h) self.ray = Ray(self.w, self.h) ## loads energy image and sets its default value self.energy_5 = pygame.image.load("energy_5.png") self.energy = 100 ## sets all default values self.points = 0 self.killed_big_enemies = 0 self.killed_small_enemies = 0 self.rays_collected = 0 self.collectibles_collected = 0 ## initializes fonts and creates the first text font = pygame.font.SysFont("comic", 64) self.font = pygame.font.SysFont("arial", 10) text = font.render("Click to play", True, (255, 255, 255)) ## loads sound self.sound = pygame.mixer.Sound("blip.wav") ## sets timer and default timer variables self.clock = pygame.time.Clock() self.timer = 0 self.seconds = 0 self.minutes = 0 ## manages beginning screen and first inputs beginning = True while beginning: self.screen.fill((0, 0, 0)) self.screen.blit(text, ((self.w / 2) - 150, (self.h / 2) - 64)) for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.display.quit() if event.type == pygame.MOUSEBUTTONUP: beginning = False self.screen.blit(self.background, (0, 0)) self.screen.blit(self.player.images[1], (self.player.x, self.player.y)) self.screen.blit(self.shooter.image, (self.shooter.x, self.shooter.y)) self.running() pygame.display.update()
def running(self): while True: ## manages time time_passed = self.clock.tick(30) time_seconds = time_passed / 1000. self.timer += 1 self.seconds += 0.03 if self.seconds >= 60: self.minutes += 1 self.seconds = 0 ## gets all the inputs and calls function related to each input for event in pygame.event.get(): if event.type == pygame.KEYUP: if event.key == pygame.K_ESCAPE: pygame.display.quit() if event.key == pygame.K_a: self.shield.index -= 1 if self.shield.index == -5: self.shield.index = -1 elif event.key == pygame.K_j: self.shield.index += 1 if self.shield.index == 4: self.shield.index = 0 elif event.key == pygame.K_l: self.generator.index += 1 if self.generator.index == 4: self.generator.index = 0 elif event.key == pygame.K_s: self.generator.index -= 1 if self.generator.index == -5: self.generator.index = -1 key = pygame.key.get_pressed() if key[pygame.K_UP]: self.player.moves_up(time_seconds) self.player.index = 0 if key[pygame.K_DOWN]: self.player.moves_down(time_seconds) self.player.index = 1 if key[pygame.K_LEFT]: self.player.moves_left(time_seconds) self.player.index = 2 if key[pygame.K_RIGHT]: self.player.moves_right(time_seconds) self.player.index = 3 ## blits the background self.screen.blit(self.background, (0, 0)) ## manages energy and prints it if self.energy >= 100: self.energy = 100 if self.energy <= 10: self.sound.play() if self.energy <= 0: self.collectible.finished = True for n in xrange(0, self.energy / 5): self.screen.blit(self.energy_5, (self.w - 35 - 10 * n, 4)) ## manages the text (points and time) text = self.font.render( (str(self.minutes) + ":" + str(self.seconds)), True, (255, 255, 255)) self.screen.blit(text, (10, 10)) text = self.font.render(("Points: " + str(self.points)), True, (255, 255, 255)) self.screen.blit(text, (440, 10)) ## manages collectibles self.collectible.blit_check(self.background, self.timer) if self.collectible.blit: self.screen.blit(self.collectible.image, (self.collectible.x, self.collectible.y)) self.collectible_rect = pygame.Rect(self.collectible.x, self.collectible.y, 20, 20) ## manages player and collision with collectible self.screen.blit(self.player.images[self.player.index], (self.player.x, self.player.y)) self.player_rect = pygame.Rect(self.player.x, self.player.y, 40, 40) if self.collectible.blit: if self.player_rect.colliderect(self.collectible_rect): i = self.collectible.index self.collectible = Collectible(self.w, self.h) self.collectible.index = i self.points += 100 self.collectibles_collected += 1 ## manages bullet, checks hits with walls self.bullet.moves(self.shooter.x, self.shooter.y) if self.bullet.rotate: self.bullet.rotates(time_seconds) self.screen.blit(self.bullet.rotated_image, self.bullet.image_draw_pos) self.bullet.check_shot() if self.bullet.shot: self.energy -= 5 if self.bullet.shot: self.screen.blit(self.bullet.rotated_image, (self.bullet.x, self.bullet.y)) self.bullet.hits_borders(self.background) if self.bullet.hits_bg: self.bullet = Bullet(self.shooter.x, self.shooter.y, self.shooter.image_rotation) self.bullet_rect = pygame.Rect(self.bullet.x, self.bullet.y, 4, 10) ## manages generator self.generator.moves(self.player.x, self.player.y, self.player.d) self.screen.blit(self.generator.images[self.generator.index], (self.generator.x, self.generator.y)) generator_rect = pygame.Rect(self.generator.x, self.generator.y, self.generator.w, self.generator.h) ## manages shooter self.shooter.moves(self.player.x, self.player.y, self.player.d) self.shooter.rotates(time_seconds) self.screen.blit(self.shooter.rotated_image, self.shooter.image_draw_pos) ## manages shield self.shield.moves(self.player.x, self.player.y, self.player.d) self.screen.blit(self.shield.images[self.shield.index], (self.shield.x, self.shield.y)) shield_rect = pygame.Rect(self.shield.x, self.shield.y, self.shield.w, self.shield.h) ## manages big enemies one by one, checks collisions with bullets, shield and tank for n in xrange(0, len(self.enemies)): enemy = self.enemies[n] enemy.moves(time_seconds) enemy.bounces(self.background) if enemy.error: self.enemies[n] = Enemy(self.w, self.h) self.screen.blit(enemy.image, (enemy.x, enemy.y)) enemy_rect = pygame.Rect(enemy.x, enemy.y, enemy.d, enemy.d) if enemy_rect.colliderect(self.bullet_rect): self.bullet = Bullet(self.shooter.x, self.shooter.y, self.shooter.image_rotation) self.enemies_2.append(Enemy_2(enemy.x, enemy.y)) self.enemies_2.append(Enemy_2(enemy.x, enemy.y)) self.enemies_2.append(Enemy_2(enemy.x, enemy.y)) enemy.alive = False self.points += 10 self.killed_big_enemies += 1 elif enemy_rect.colliderect(shield_rect): enemy.reverse() self.energy -= 5 elif enemy_rect.colliderect(self.player_rect): enemy.reverse() self.energy -= 10 if (self.timer == 30 * 5 or self.timer == 30 * 10) and len(self.enemies) <= 2: self.enemies.append(Enemy(self.w, self.h)) ## temporary list to manage the elimination of some enemies l = [] for n in xrange(0, len(self.enemies)): enemy = self.enemies[n] if enemy.alive: l.append(self.enemies[n]) self.enemies = l ## manages small enemies one by one, checks collision with bullets, shield and tank for n in xrange(0, len(self.enemies_2)): enemy_2 = self.enemies_2[n] enemy_2.moves(time_seconds) enemy_2.bounces(self.background) if enemy.error: self.enemies_2[n] = Enemy_2(self.w, self.h) self.screen.blit(enemy_2.image, (enemy_2.x, enemy_2.y)) enemy_2_rect = pygame.Rect(enemy_2.x, enemy_2.y, enemy_2.d, enemy_2.d) if enemy_2_rect.colliderect(self.player_rect): enemy_2.reverse() self.energy -= 10 elif enemy_2_rect.colliderect(shield_rect): enemy_2.reverse() self.energy -= 5 elif enemy_2_rect.colliderect(self.bullet_rect): self.bullet = Bullet(self.shooter.x, self.shooter.y, self.shooter.image_rotation) enemy_2.alive = False self.counter_enemies_2_dead += 1 self.points += 10 self.killed_small_enemies += 1 ## temporary list to manage the elimination of some enemies l = [] for n in xrange(0, len(self.enemies_2)): enemy_2 = self.enemies_2[n] if enemy_2.alive: l.append(self.enemies_2[n]) self.enemies_2 = l if self.counter_enemies_2_dead == 3: self.counter_enemies_2_dead = 0 self.enemies.append(Enemy(self.w, self.h)) ## manages rays of energy and collision with generator and tank and manages life time self.ray.moves(time_seconds) self.ray.bounces(self.background) self.screen.blit(self.ray.image, (self.ray.x, self.ray.y)) ray_rect = pygame.Rect(self.ray.x, self.ray.y, self.ray.d, self.ray.d) if ray_rect.colliderect(generator_rect): self.ray.check_caught() if self.ray.caught: self.ray = Ray(self.w, self.h) self.energy += 20 self.points += 10 self.rays_collected += 1 else: self.ray.reverse() if ray_rect.colliderect(self.player_rect): self.ray.reverse() if self.timer >= 30*15 and self.timer <= 30*15.01 or \ self.timer >= 30*30 and self.timer <= 30*30.01 or \ self.timer >= 30*45 and self.timer <= 30*45.01 or \ self.timer >= 30*60 and self.timer <= 30*60.01 or \ self.timer >= 30*75 and self.timer <= 30*75.01 or \ self.timer >= 30*90 and self.timer <= 30*90.01 or \ self.timer >= 30*105 and self.timer <= 30*105.01 or \ self.timer >= 30*120 and self.timer <= 30*120.01: self.ray = Ray(self.w, self.h) ## manages the end of the loop if self.collectible.finished == True: pygame.display.quit() self.end() pygame.display.update()
ship = Spaceship(ship_img, screen_width//2 - ship_width//2, screen_height-50, ship_width, ship_height, 5) # set up list of enemies enemies_list_1 = [] enemies_list_2 = [] enemies_list_3 = [] start_x = 50 increment = 50 speed = 2 score_1 = 10 score_2 = 20 score_3 = 30 # create lists for every lvl enemy for i in range(10): enemies_list_3.append(Enemy(enemy3, start_x, 50, enemy_width, enemy_height, speed, score_3)) enemies_list_2.append(Enemy(enemy2, start_x, 90, enemy_width, enemy_height, speed, score_2)) enemies_list_2.append(Enemy(enemy2, start_x, 130, enemy_width, enemy_height, speed, score_2)) enemies_list_1.append(Enemy(enemy1, start_x, 170, enemy_width, enemy_height, speed, score_1)) enemies_list_1.append(Enemy(enemy1, start_x, 210, enemy_width, enemy_height, speed, score_1)) start_x += increment # create list of shields to draw on screen shield_list = [] shield_x = 60 shield_y = screen_height - 150 shield_increment = screen_width // 4 for i in range(4):
from base_entity import Entity, Dragon from heroes import PlayerCharacter, Warrior from enemies import Enemy, Troll, Mage from equipment import LightArmor, HeavyArmor, Cap player = PlayerCharacter("Mighty Joe", 100, 50, 10, 10, 10, 10, 10) enemy = Enemy("Gooloff", 50, 20, 9, 9, 9, 9, 9) player.physical_attack([enemy]) print(enemy._current_hp) mini_troll = Troll("Jerk", 47, 0, 8, 8, 8, 8, 8) mini_troll.shriek() print(" Name = {} Strength = {}, Max HP = {}".format(mini_troll._name, mini_troll._strength, mini_troll._max_hp)) mage1 = Mage("Evelyn", 80, 45, 6, 6, 12, 11, 6) mage1.focus() mage1.boost(mini_troll) conan = Warrior("Conan", 100, 50, 10, 10, 10, 10, 10) print("{}'s Current Strength = {}, Defense = {}, Mind = {}".format( conan._name, conan._strength, conan._defense, conan._mind)) (conan.ability()) #Testing Armor and Cap Functions knights_armor = HeavyArmor() knights_armor.up_defense(conan) knights_armor.up_strength(conan) guards_armor = LightArmor()
def main(): """ Main Program """ pygame.init() #Défini les dimensions size = [constants.SCREEN_WIDTH, constants.SCREEN_HEIGHT] #[nom_du_fichier.VARIABLE] screen = pygame.display.set_mode(size) #Titre de la fenetre pygame.display.set_caption("The pudi pudi quest") # Créer le joueur en important le fichier (voir importations) player = Player() enemies = Enemy() # Police font = pygame.font.SysFont("calibri", 48) # Créer les niveaux (listes) level_list = [] level_list.append(levels.Level_01(player)) # Met en player le niveau actuel current_level_no = 0 current_level = level_list[current_level_no] active_sprite_list = pygame.sprite.Group() player.level = current_level player.rect.x = 492 player.rect.y = 1342 active_sprite_list.add(player) enemies.rect.x = 300 enemies.rect.y = 600 active_sprite_list.add(enemies) #Relais permettant le maintien de la boucle tant que la variable est False gameExit = False # Temps du raffraichissement de l'écran (voir FPS) clock = pygame.time.Clock() score_text = font.render("Score: ", True, constants.WHITE) screen.blit(score_text, (5, 5)) #Musique d'ambiance pygame.mixer.music.load("data/sound/ambiance.mp3") pygame.mixer.music.play(-1) # -------- Programme : MAIN LOOP ----------- #Main while not gameExit: for event in pygame.event.get( ): # Quand l'utilisation fait quelque chose if event.type == pygame.QUIT: # Si il clique sur 'Fermer' gameExit = True # La variable relais prends la valeur True et permet la sortie #Quand l'utilisateur appuie sur une touche if event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: # Touche echap gameExit = True if event.key == pygame.K_LEFT: player.go_left() if event.key == pygame.K_RIGHT: player.go_right() if event.key == pygame.K_UP: player.jump() #Quand l'utilisateur relâche la touche if event.type == pygame.KEYUP: if event.key == pygame.K_LEFT: player.stop() if event.key == pygame.K_RIGHT: player.stop() # Update le joueur active_sprite_list.update() # Affiche tous les items du niveau current_level.update() # Mvt caméra si le joueur va à droite (ici nul) if player.rect.x >= 0: #car on veut aucun décallage (sinon on met 500) diff = player.rect.x - 350 # on peut mettre (constants.SCREEN_WIDTH/2) player.rect.x = 350 # milieu de l'écran current_level.shift_world(-diff) # Mvt caméra si le joueur va à gauche (ici nul) if player.rect.x <= 0: diff = 350 - player.rect.x #(constants.SCREEN_WIDTH/2) player.rect.x = 350 #mileu de l'écran current_level.shift_world(diff) if player.rect.y <= 200: diff = player.rect.y - 350 player.rect.y = 350 currentb_level.shift_world_y(-diff) if player.rect.y >= 200: diff = 350 - player.rect.y #(constants.SCREEN_WIDTH/2) player.rect.y = 350 #mileu de l'écran current_level.shift_world_y(diff) # ALL CODE TO DRAW SHOULD GO BELOW THIS COMMENT current_level.draw(screen) active_sprite_list.draw(screen) # ALL CODE TO DRAW SHOULD GO ABOVE THIS COMMENT # FPS : limités à 60 FPS = constants.FPS clock.tick(FPS) # Update pygame de tout se qu'on a écrit pygame.display.flip() # Sortie du programme pygame.quit()
[0,0,1,0,0,1,0,0,1,0,0,1,0,0] ] # General graphics livesImg = graphics.g_player.lives numbers = [graphics.g_numbers.n0, graphics.g_numbers.n1, graphics.g_numbers.n2, graphics.g_numbers.n3, graphics.g_numbers.n4, graphics.g_numbers.n5, graphics.g_numbers.n6, graphics.g_numbers.n7, graphics.g_numbers.n8, graphics.g_numbers.n9] impImages = [graphics.g_imps.imp0_0, graphics.g_imps.imp1_0, graphics.g_imps.imp2_0, graphics.g_imps.imp3_0, graphics.g_imps.imp4_0, graphics.g_imps.imp5_0] levelImages = [[graphics.g_tiles.tile01, graphics.g_teleporters.tele01], [graphics.g_tiles.tile02, graphics.g_teleporters.tele02], [graphics.g_tiles.tile03, graphics.g_teleporters.tele03], [graphics.g_tiles.tile04, graphics.g_teleporters.tele04], [graphics.g_tiles.tile05, graphics.g_teleporters.tele05], [graphics.g_tiles.tile06, graphics.g_teleporters.tele06]] bullet = graphics.g_enemies.bullet # Init classes instructions = Interface() bg = Background(0, 0) player = Player(0, 2, -12, 106) audio = Audio(g_sound) lvlEnemies = Enemy(0, -20, -20, 0, 0) bonusItem.append(Drops(-20, -20, 0)) aLevel = Levels([levelMaps[random.getrandbits(4)], levelMaps[random.getrandbits(4)], levelMaps[random.getrandbits(4)], levelMaps[random.getrandbits(4)], levelMaps[random.getrandbits(4)]]) levelImps = Imps(-20, -20, impImages[0], 0) flashText = Text(1, 1, "", True, -5) tmpImpId = random.getrandbits(2) impId = tmpImpId + random.getrandbits(2) if impId > 5: impId = 5 ############################################# def update(): global gameState, levelComplete, movePlayerX, impsOnScreen, impId, rndLevel, bonusItem, playerLives, bonusItemDropRate, score, aLevel, tmpImpId global cheatsOn, flashPlayer, flashText, freezeTimer, freezeTimerMax, freezeEnemies, bulletVisible, bulletX, bulletY, bulletDir, bulletSpeed, warpPlayed # Randomize imps during splash
pygame.draw.rect(screen, red, (mouse_rect.x, mouse_rect.y, tank_icon.get_width(), tank_icon.get_height(),)) else: pygame.draw.rect(screen, green, (mouse_rect.x, mouse_rect.y, tank_icon.get_width(), tank_icon.get_height(),)) screen.blit(tank_icon_nobg, (mouse_rect.x, mouse_rect.y)) if picked_tack: if red_bg: screen.blit(tack_icon_red, (mouse_rect.x, mouse_rect.y)) else: screen.blit(tack_icon, (mouse_rect.x, mouse_rect.y)) shoot_count = 0 speed = 1 # increased for speed motion. hostiles = [Enemy(i * 3, 170, 7, 1) for i in range(7)] buildings = [] snipers = [] picked_tank = False picked_tack = False picked_sniper = False mouse_counter = 0 red_bg = False # red background if can't place defenses, else green while True: clock.tick(60 * speed) for event in pygame.event.get(): if event.type == pygame.QUIT: # if X button is pressed on the app pygame.quit() sys.exit()
def move_down(player, enemies): '''function in charge of movig character up an down''' enemies_left = enemies[0] for element in enemies: try: if element.x_coord == last[1] and element.y_coord == (last[0] + change): enemy = element except AttributeError: pass try: if board[last[0] + change][last[1]] == ' ': # movement only on floor that is " " board[last[0] + change][last[1]] = character board[last[0]][last[1]] = " " return True elif board[last[0] + change][last[1]] == '0': #here goes the things that sage wants to say if player.if_sage == False: player.if_sage = sage() else: shop(player) return False elif board[last[0] + change][last[1]] == Colors.portal + '$' + Colors.end: board[last[0]][last[1]] = " " output = 2 return (True, output) elif board[last[0] + change][last[1]] == Colors.portal + '*' + Colors.end: if player.level >= 2: board[last[0]][last[1]] = ' ' output = 3 return (True, output) else: return False elif board[last[0] + change][last[1]] == Colors.portal + '^' + Colors.end: from enemies import Enemy enemy = Enemy(3) fight(player, enemy) from win import wingame as win #win() elif '<' in board[last[0] + change][last[1]]: fight(player, enemy) if enemy.life == 0: board[enemy.y_coord][ enemy.x_coord] = Colors.money + 'o' + Colors.end args['enemies'][0] -= 1 player.enemies_killed += 1 return False elif 'o' in board[last[0] + change][last[1]]: player.gold += enemy.level * randint(1, 10) board[last[0] + change][last[1]] = character board[last[0]][last[1]] = ' ' return True elif board[last[0] + change][last[1]] == '=': if doors(): board[last[0] + change][last[1]] = ' ' return False else: idle() return False except IndexError: idle() return False
def setUp(self): self.enemy = Enemy(health=100, mana=100, damage=20)
def main(): """ Main Program """ #pygame.init() #main_menu() # Set the height and width of the screen size = [constants.SCREEN_WIDTH, constants.SCREEN_HEIGHT] screen = pygame.display.set_mode(size) pygame.display.set_caption("Danga") ### Main score song we pause for debug song = pygame.mixer.Sound("sounds/danga.wav") song.play(-1) score = 0 # Create the player player = Player() player_shot = None # Create the enemy enemy = Enemy() enemies = pygame.sprite.Group() npcs = pygame.sprite.Group() #Prepare for enemy_shots enemy_shots = pygame.sprite.Group() npc = Npc() # Create all the levels level_list = [] level_list.append(levels.Level_01(player)) level_list.append(levels.Level_02(player)) # Set the current level current_level_no = 0 current_level = level_list[current_level_no] active_sprite_list = pygame.sprite.Group() player.level = current_level enemy.level = current_level npc.level = current_level player.rect.x = 340 player.rect.y = constants.SCREEN_HEIGHT - player.rect.height active_sprite_list.add(player) enemy.rect.x = constants.SCREEN_WIDTH - enemy.rect.width enemy.rect.y = 0 #constants.SCREEN_HEIGHT - enemy.rect.height active_sprite_list.add(enemy) enemies.add(enemy) npc.rect.x = constants.SCREEN_WIDTH - enemy.rect.width npc.rect.y = 0 #constants.SCREEN_HEIGHT - enemy.rect.height #aggiungiano un NPC ? #active_sprite_list.add(npc) #npcs.add(npc) #Loop until the user clicks the close button. done = False # Used to manage how fast the screen updates clock = pygame.time.Clock() # -------- Main Program Loop ----------- while not done: for event in pygame.event.get(): # User did something if event.type == pygame.QUIT: # If user clicked close done = True # Flag that we are done so we exit this loop if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: player.go_left() if event.key == pygame.K_RIGHT: player.go_right() if event.key == pygame.K_UP: player.jump() if event.key == pygame.K_SPACE: player.yell() if event.key == pygame.K_LCTRL: #shots.append(Shot(player.rect.center, player.direction)) player_shot = Shot(player.rect.center, player.direction) active_sprite_list.add(player_shot) #if event.key == pygame.K_RCTRL: #shots.append(EnemyShot(enemy.rect.center)) #active_sprite_list.add(EnemyShot(enemy.rect.center, player)) if event.type == pygame.KEYUP: if event.key == pygame.K_LEFT and player.change_x < 0: player.stop() if event.key == pygame.K_RIGHT and player.change_x > 0: player.stop() ### ENEMY SHOTS time_now = pygame.time.get_ticks() #print (str(time_now - enemy.last_shot)) if time_now - enemy.last_shot > 1500: current_shot = EnemyShot(enemy.rect.center, player) enemy_shots.add(current_shot) active_sprite_list.add(current_shot) enemy.last_shot = time_now #draw_text('COLLIDE!', font40, constants.WHITE, int( constants.SCREEN_WIDTH / 2 - 100), int( constants.SCREEN_HEIGHT / 2 + 50)) ### MAIN COLLISION (Player Shot) if player_shot: if pygame.sprite.collide_rect(player_shot, enemy): #print("COLLIDE") explosion = Explosion(enemy.rect.centerx, enemy.rect.centery, 4) active_sprite_list.add(explosion) score += 10 ### MAIN COLLISION (Enemy Shot) if pygame.sprite.collide_rect(current_shot, player): #print("COLLIDE") explosion = DeathExplosion(player.rect.centerx, player.rect.centery, 4) active_sprite_list.add(explosion) player.shield = player.shield -3 ### SHIELD, DEATH, LIVES AND GAME OVER if player.shield <= 0: player_die_sound.play() death_explosion = DeathExplosion(player.rect.centerx, player.rect.centery, 4) active_sprite_list.add(death_explosion) # running = False ## GAME OVER 3:D player.hide() player.lives -= 1 player.shield = 100 ## if player died and the explosion has finished, end game if player.lives == 0 and not death_explosion.alive(): done = True #draw_text(screen, "GAME OVER", 30, constants.SCREEN_WIDTH/2, constants.SCREEN_HEIGHT/2) ### SPRITE UPDATES # Update the player. active_sprite_list.update() # Update items in the level current_level.update() ### PLAYER SCREEN LIMITS # print ('x:'+str(player.rect.x)) # print ('y:'+str(player.rect.y)) # If the player gets near the right side, shift the world left (-x) if player.rect.x >= 500: diff = player.rect.x - 500 player.rect.x = 500 current_level.shift_world(-diff) # If the player gets near the left side, shift the world right (+x) if player.rect.x <= 120: diff = 120 - player.rect.x player.rect.x = 120 current_level.shift_world(diff) # If the player gets to the end of the level, go to the next level current_position = player.rect.x + current_level.world_shift if current_position < current_level.level_limit: player.rect.x = 120 if current_level_no < len(level_list)-1: current_level_no += 1 current_level = level_list[current_level_no] player.level = current_level ### DRAWS # ALL CODE TO DRAW SHOULD GO BELOW THIS COMMENT current_level.draw(screen) active_sprite_list.draw(screen) draw_text(screen, str(score), 18, constants.SCREEN_WIDTH / 2, 10) ## 10px down from the screen #draw_shield_bar(screen, 5, 5, 100) draw_shield_bar(screen, 5, 5, player.shield) # Draw lives draw_lives(screen, constants.SCREEN_WIDTH - 100, 5, player.lives, player_mini_img) # ALL CODE TO DRAW SHOULD GO ABOVE THIS COMMENT # Limit to 60 frames per second clock.tick(60) # Go ahead and update the screen with what we've drawn. pygame.display.flip() game_over() main_menu()
from room import Room from player import Player from items import Item import time from enemies import Enemy from battle_sequence import Battle items = {'dagger' : Item("Basic Dagger", "Just a basic dagger. Can be used to cause minimal damage. 10-15 dmg dealt.")} room = Room("Practice Room", """This room is a practice room, its contents being a mobile wooden dummy and the player. its purpose is to test out the battle_sequence function.""") enemy = Enemy("Wooden Dummy") player = Player("Player Dummy", room, inventory=[items['dagger']]) # print(enemy.name) # print(enemy.health) # print(player.name) # print(player.health) # player.print_inventory() test_battle = Battle(player, enemy) test_battle.main_battle_loop()