コード例 #1
0
ファイル: Arena.py プロジェクト: Magni77/No-swords
    def fight(self, Hero, Enemy, who, a_power, d_power):
        hero_attack = Hero.hattack() * a_power
        print("Herro Attac", hero_attack)
        hero_defense = Hero.hdefense() * d_power
        print("Her Def", hero_defense)
        enemy_attack = Enemy.eattack() * a_power
        print("Enem Atta", enemy_attack)
        enemy_defense = Enemy.edefense() * d_power
        print("enemy defd", enemy_defense)
        crit = random.randint(0, 5)

        if crit == 4:
            x = 1.5
            print("CRIT")
        else:
            x = 1

        if who % 2 != 0:
            hp = enemy_defense - x * hero_attack
            Enemy.lost_health(hp)
            self.label2.text = '[size=25]' + "Hero hit for " + str(abs(hp))
        else:
            ep = hero_defense - x * enemy_attack
            Hero.lost_health(ep)
            self.label3.text = '[size=25]' + "Enemy hit for " + str(abs(ep))
コード例 #2
0
def main():
    S.win.clear()

    # GENERATE MAP AND EDGES
    curses.textpad.rectangle(S.win, 0, 0, 1 + 50 + 1, 1 + 200 + 1)
    S.win.refresh()
    #while (True):
    #   test = S.win.getch()
    #  S.win.addstr(42,42,str(test))
    # TEST FOR WAY
    genmap.genmap()
    treasure.init_exit()
    # SUMMON HERO AND MONSTERS
    hero = Hero.Hero()
    Monster.init_monsters()
    treasure.init_treasure()
    # GENERATE UI
    refresh_ui(hero)

    # GENERATE DIALOG BOX
    refresh_dialog("", False)

    # Main Game Loop
    running = True
    while (running):
        S.win.move(0, 0)
        key = S.win.getch()
        refresh_dialog("", False)

        if (key == 27):
            running = False
        Hero.hero_move(hero, S.monsters, key)
        Monster.monsters_moves(hero, S.monsters)
        refresh_ui(hero)
        S.win.move(0, 0)
コード例 #3
0
ファイル: Arena.py プロジェクト: Magni77/No-swords
    def fight(self, Hero, Enemy, who, a_power, d_power):
        hero_attack = Hero.hattack() *a_power
        print("Herro Attac", hero_attack)
        hero_defense = Hero.hdefense() * d_power
        print("Her Def",  hero_defense)
        enemy_attack = Enemy.eattack() * a_power
        print("Enem Atta" , enemy_attack)
        enemy_defense = Enemy.edefense() * d_power
        print("enemy defd", enemy_defense)
        crit = random.randint(0, 5)

        if crit == 4:
            x = 1.5
            print("CRIT")
        else:
            x = 1

        if who % 2 != 0:
            hp = enemy_defense - x*hero_attack
            Enemy.lost_health(hp)
            self.label2.text = '[size=25]' + "Hero hit for " + str(abs(hp))
        else:
            ep = hero_defense - x*enemy_attack
            Hero.lost_health(ep)
            self.label3.text = '[size=25]' + "Enemy hit for " + str(abs(ep))
コード例 #4
0
ファイル: MainGame.py プロジェクト: wuzaipei/game-feiji
    def startGame(self):
        pygame.init()
        # 初始化一个屏幕对象 pygame.display.set_mode( ) 需要的三个参数如下:
        # 第一个参数是元组:分别传入面板的宽度和高度
        # 第二个参数表示窗口的属性是否可以拖动 0表示不可以拖动
        # 第三个参数是系统的颜色默认32位

        hero = Hero(MainGame.my_hero)
        screen = pygame.display.set_mode((MainGame.WIDTH, MainGame.HEIGHT), 0,
                                         32)
        # 设置标题
        pygame.display.set_caption("飞机大战")

        # 采用死循环方式让程序不断绘制窗口

        game = MainGame()
        bullet_index = 0
        while True:
            pygame.display.update()
            # 花游戏背景
            screen.blit(MainGame.bk, (0, 0))
            screen.blit(MainGame.my_hero, (hero.x, hero.y))
            hero.move(screen)
            # 产生子弹
            bullet_index += 1

            if bullet_index % 10 == 0:
                game.__generateBullets()
            for b in game.bullets:
                b.move()

            # 产生敌方战舰
            if bullet_index % 20 == 0:
                game.__cat()
            for c in game.aircrafts:
                c.move()

            # 判断子弹是否越界若果越界则删除
            for b in game.bullets:
                if (b.isOutOfBound()):
                    game.bullets.remove(b)
                    # print("删除成功")
            # 画子弹
            for b in game.bullets:
                screen.blit(b.image, (b.x, b.y))
            #画敌方战舰
            for c in game.aircrafts:
                screen.blit(c.image, (c.x, c.y))
            # 检测碰撞
            for b in game.bullets:
                for e in game.aircrafts:
                    if b.hit(e):
                        game.aircrafts.remove(e)
                        game.bullets.remove(b)
            # 添加事件
            for e in pygame.event.get():
                if e.type == pygame.QUIT:
                    exit(0)
コード例 #5
0
 def __init__(self):
     self.level = 1
     self.hero = Hero()
     self.place = 0
     #Battle = 1 / Shop = 2 / Rest = 3
     self.room = [1,1,1,1]
     #Change this value to change the duration of the game
     self.finalLevel = 30
     createDB()
コード例 #6
0
ファイル: main.py プロジェクト: afendana1/team
def check_damage():
    '''
    проверка столкновний объектов и
    вылета за границы игрового поля
    '''
    for e in Constants.ENEMIES[:]:
        for h_b in Constants.hero_BULLETS:
            if math_functions.distance_to(h_b.x, h_b.y, e.x, e.y) < e.radius + h_b.radius:
                if h_b.type == "shock":
                    e.hp -= 100
                if h_b.type == "uzi":
                    e.hp -= 20
                if h_b.type == "snipe":
                    e.hp -= 100
                if h_b.type == "gun":
                    e.hp -= 20
                if h_b.type == "ice_sphere":
                    e.hp -= 30
                    e.slow = h_b.ice_slow
                    e.time_end_slow = h_b.time_slow_duration + Labirint.var.TIME
                if h_b.type == "fire_sphere":
                    sf = Hero.fire_floor_surfaces()
                    sf.x = h_b.x
                    sf.y = h_b.y
                    sf.time_for_destroy = Labirint.var.TIME + sf.time_exist
                    Constants.SURFACES.append(sf)
                Constants.hero_BULLETS.remove(h_b)

    for e in Constants.ENEMIES[:]:
        for sf in Constants.SURFACES:
            if max(e.x - sf.x, e.y - sf.y) < sf.radius:
                e.time_end_fire = Labirint.var.TIME + sf.tick_time
                e.fire_damage = sf.damage

    for e in Constants.ENEMIES[:]:
        if e.hp <= 0:
            d = Enemies.Dead()
            d.x = e.x
            d.y = e.y
            d.type = e.type
            d.time_for_destroy = Labirint.var.TIME + d.time_exist
            Constants.Deads.append(d)
            Constants.ENEMIES.remove(e)

    for w in Labirint.var.physics_WALLS:
        if w.can_collision == 1:
            for h_b in Constants.hero_BULLETS[:]:
                if math_functions.check_wall_collision(w.x, w.y, w.size, w.size, h_b.x, h_b.y, h_b.radius) == True:
                    if h_b.type == "fire_sphere":
                        sf = Hero.fire_floor_surfaces()
                        sf.x = h_b.x
                        sf.y = h_b.y
                        sf.time_for_destroy = Labirint.var.TIME + sf.time_exist
                        Constants.SURFACES.append(sf)
                    Constants.hero_BULLETS.remove(h_b)
                    continue
コード例 #7
0
    def test_normal_fight_lowers_health(self):
        w = Weapon('The Axe of Destiny', 10)
        h = Hero("Bron", "Dragonslayer", 100, 100, 1)
        h.equip(w)
        e = Enemy(100, 10)
        f = Fight(h, e, [], 3, 3)
        f.fight()

        test_passes = False
        if e.is_alive() is not True or h.is_alive() is not True:
            test_passes = True
        self.assertEqual(test_passes, True)
コード例 #8
0
 def SPAWN(self):
     '''призыв одного моба другим'''
     if Hero.var.TIME > self.time_to_spawn * Constants.FPS + self.time_last_spawn:
         e = Enemy()
         e.x = self.x + Hero.randint(50, 100) * Hero.randint(-1, 1)
         e.y = self.y + Hero.randint(50, 100) * Hero.randint(-1, 1)
         e.type = "zombie"
         e.range_to_move = Hero.hero.radius * 1.2
         e.range_to_attack = Hero.hero.radius * 1.3
         e.radius = e.radius * 0.75
         e.color = Constants.GREEN
         Constants.ENEMIES.append(e)
         self.time_last_spawn = Hero.var.TIME
コード例 #9
0
ファイル: Main.py プロジェクト: namastereid/soylent
    def __init__(self):
        """Set the window Size"""
        self.width = g_screenWidth
        self.height = g_screenHeight
        self.worldWidth = g_worldWidth
        self.worldHeight = g_worldHeight
        self.worldRect = pygame.Rect((0, 0),
                                     (self.worldWidth, self.worldHeight))
        self.toggle_full_screen = False
        self.zoom = -1500
        """Initialize PyGame"""
        video_flags = OPENGL | DOUBLEBUF

        pygame.init()
        pygame.display.set_mode((self.width, self.height), video_flags)

        self.resize((self.width, self.height))
        self.init()
        """create the hero and friends"""
        self.hero = Hero(self.worldRect.center)
        self.friendly_sprites = pygame.sprite.RenderPlain((self.hero))
        """create the enemies"""
        self.enemy_sprites = pygame.sprite.Group()
        """create timer user event"""
        seed()
        pygame.time.set_timer(pygame.USEREVENT, 1000)
コード例 #10
0
ファイル: Main.py プロジェクト: cxysl/mytest
    def __creat_sprites(self):
        #创建背景精灵,创建背景精灵组
        bg_1 = BackGround(bg_img_1,1)
        bg_2 = BackGround(bg_img_2,1)
        bg_2.rect.y = -WINDOW_HEIGHT
        self.bg_ground = pygame.sprite.Group(bg_1,bg_2)
        #创建英雄精灵,创建英雄精灵组
        self.hero = Hero()
        self.hero_group = pygame.sprite.Group(self.hero)
        #创建安全木块精灵组
        self.safetyblock = SafetyBlock()
        self.safetyblock_group = pygame.sprite.Group()
        #创建消失木块精灵组
        self.noneblock = NoneBlock()
        self.noneblock_group = pygame.sprite.Group()
        #创建跳跃木块精灵组
        self.jumpblock = JumpBlock()
        self.junpblock_group = pygame.sprite.Group()

        # 创建掉血木块精灵组
        self.loseblock = LoseBlock()
        self.loseblock_group = pygame.sprite.Group()

        self.prop_1 = Prop_1()
        self.prop_1_group = pygame.sprite.Group()

        self.prop_2 = Prop_2()
        self.prop_2_group = pygame.sprite.Group()

        self.prop_3 = Prop_3()
        self.prop_3_group = pygame.sprite.Group()
コード例 #11
0
ファイル: LevelData.py プロジェクト: wmellema/ScautingGame
def load_character(tile_map, gamescreen):
    """Create an instance of the main character and return it."""
    tile_obj = h.Hero(tile_map, gamescreen)
    tile_obj.load_texture("..//Textures//character.png")
    tile_obj.origin = r.Vector2(0, 0)
    tile_obj.hazard_touched_method = hazard_touched_method
    tile_obj.special_touched_method = special_touched_method
    return tile_obj
コード例 #12
0
 def test_when_spawning_the_hero_is_unsuccessful_then_resturn_false(self):
     h = Hero(name="Bron",
              title="Dragonslayer",
              health=100,
              mana=100,
              mana_regeneration_rate=2)
     d = Dungeon('test_maps/empty.txt', h, 2)
     self.assertFalse(d.spawn())
コード例 #13
0
ファイル: Maze.py プロジェクト: LappoAndrey/M-PT1-37-21
 def create_hero(self):
     name = input('Enter name: ')
     age = input('Enter age: ')
     race = input('Enter race: ')
     hero = Hero(name, age, race)
     print(f"You created your hero")
     print(f'Good luck {hero.name}')
     self.hero = hero
コード例 #14
0
 def test_dungeon_initialization_when_empty_map(self):
     h = Hero(name="Bron",
              title="Dragonslayer",
              health=100,
              mana=100,
              mana_regeneration_rate=2)
     d = Dungeon('test_maps/empty.txt', h, 2)
     self.assertEqual(d.tmp_map, [])
コード例 #15
0
 def test_dungeon_initialization_when_map_is_correct(self):
     h = Hero(name="Bron",
              title="Dragonslayer",
              health=100,
              mana=100,
              mana_regeneration_rate=2)
     d = Dungeon('test_maps/test.txt', h, 2)
     expected_map = [['.', '.', '#'], ['S', 'T', '.'], ['#', '.', 'G']]
     self.assertEqual(d.tmp_map, expected_map)
コード例 #16
0
def init_hero():
    """
    Инициализация главного героя.
    """
    users_choice = input(("выберите своб расу.Варианты:"
                         "Человек (H/h)(средние параметры), "
                         "Эльф (E/e)(уклон в магию),"
                         " Гном (G/g)(уклон в ближний бой): ")).lower().strip()
    if users_choice == "h":
        my_hero = Hero.Hero(Hero.human)
    elif users_choice == "e":
        my_hero = Hero.Hero(Hero.elf)
    elif users_choice == "g":
        my_hero = Hero.Hero(Hero.gnome)
    else:
        my_hero = Hero.Hero(Hero.human)

    return my_hero
コード例 #17
0
ファイル: Game.py プロジェクト: Virtuos86/thegame
def MoveHero(dx, dy):
    hero = Hero.Heroes[Hero.CurHero]
    curmap = Map.GameMap[Map.CurMap]
    if not Map.FreeTile(curmap.Cells[hero.x + dx][hero.y + dy].Tile):
        return
    x, y = hero.x, hero.y
    hero.x += dx
    hero.y += dy
    Hero.SetHeroVisible(Hero.CurHero)
    Hero.CleaningUp(x, y)
    Monsters.ShowMonsters()
    Hero.ShowHero(Hero.CurHero)
    if (abs(hero.x - curmap.LocalMapLeft) < Map.SCROLL_DELTA) or \
       (abs(hero.y - curmap.LocalMapTop) < Map.SCROLL_DELTA) or \
       (abs(hero.x - (curmap.LocalMapLeft + Const.LOCAL_MAP_WIDTH)) < Map.SCROLL_DELTA) or \
       (abs(hero.y - (curmap.LocalMapTop + Const.LOCAL_MAP_HEIGHT)) < Map.SCROLL_DELTA):
        Map.ScrollMap()
    Lowlevel.ShowHeroInfo(Hero.CurHero)
コード例 #18
0
 def test_getting_the_dimentions_of_the_current_map(self):
     h = Hero(name="Bron",
              title="Dragonslayer",
              health=100,
              mana=100,
              mana_regeneration_rate=2)
     d = Dungeon('test_maps/test.txt', h, 2)
     expected = (3, 3)
     self.assertEqual((d.X, d.Y), expected)
コード例 #19
0
	def initHeroList(self):
		HeroesJson = fileIn.readHeroJson()
		heroesjson = HeroesJson["heroes"]
	
		for hero in heroesjson:
			#from json
			self.HeroesList.append(Hero.Hero(hero['shotname'],hero['id'],hero['safe'],hero['mid'],hero['off'],hero['sup'],hero["abilities"]))

		self.heroMaxNum = len(self.HeroesList)
コード例 #20
0
 def test_moving_the_hero_to_an_obstacle_then_return_false(self):
     h = Hero(name="Bron",
              title="Dragonslayer",
              health=100,
              mana=100,
              mana_regeneration_rate=2)
     d = Dungeon('test_maps/test.txt', h, 2)
     d.spawn()
     self.assertFalse(d.move_hero('down'))
コード例 #21
0
 def __create_sprites_group(self):
     bg1 = bg.Background()
     bg2 = bg.Background(True)
     self.bg_group = pygame.sprite.Group(bg1, bg2)
     self.hero = Hero.Hero(self.SCREEN_RECT)
     self.enemies = pygame.sprite.Group()
     self.pawn_enemies = pygame.sprite.Group()
     self.office_enemies = pygame.sprite.Group()
     self.mid_boss_enemies = pygame.sprite.Group()
コード例 #22
0
ファイル: MapManager.py プロジェクト: quopple/Game
    def loadResource(self):
        '''
        加载地图资源
        '''
        self.room = Room(mapPath, self.gameNP)
        self.hero = Hero(LVecBase3f(0, 0, 0), parent=self.gameNP)
        self.room.setHero(self.hero)
        self.initHeroInfo = Hero.ToDict(self.hero)
        # 加载中场视频、结束视频
        video, card = loadVideo('middle.mp4')
        self.videoDict['middle'] = {'video': video, 'card': card}
        video, card = loadVideo('end.mp4')
        self.videoDict['end'] = {'video': video, 'card': card}

        base.LEAPMOTION = True
        if _LEAPMOTION:
            base.leapMotion = LeapListener()
        else:
            base.LEAPMOTION = False
コード例 #23
0
 def test_moving_the_hero_down_when_there_are_no_obstacles_then_return_true(
         self):
     h = Hero(name="Bron",
              title="Dragonslayer",
              health=100,
              mana=100,
              mana_regeneration_rate=2)
     d = Dungeon('test_maps/no_obstacles.txt', h, 2)
     d.spawn()
     self.assertTrue(d.move_hero('down'))
コード例 #24
0
 def test_moving_the_hero_out_of_boundaries_of_the_map_then_return_false_and_print_message(
         self):
     h = Hero(name="Bron",
              title="Dragonslayer",
              health=100,
              mana=100,
              mana_regeneration_rate=2)
     d = Dungeon('test_maps/test.txt', h, 2)
     d.spawn()
     self.assertFalse(d.move_hero('left'))
コード例 #25
0
 def test_when_spawning_the_hero_then_change_S_to_H(self):
     h = Hero(name="Bron",
              title="Dragonslayer",
              health=100,
              mana=100,
              mana_regeneration_rate=2)
     d = Dungeon('test_maps/test.txt', h, 2)
     d.spawn()
     letter_on_the_map = d.tmp_map[d.hero_position_X][d.hero_position_Y]
     self.assertEqual('H', letter_on_the_map)
コード例 #26
0
ファイル: Main.py プロジェクト: danyducky/pythonrpg
    def menu():
        import pygame
        import Menu
        import Hero
        pygame.init()
        status = False
        status1 = False
        clock = pygame.time.Clock()
        while True:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    sys.exit()
                elif event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_ESCAPE:
                        sys.exit()
            mouse = pygame.mouse.get_pos()
            if pygame.mouse.get_pressed(
            )[0] and 340 < mouse[0] < 435 and 75 < mouse[1] < 115:
                Main(
                    background,
                    Hero.Player('ducky'),
                    start_x,
                    start_y,
                    mobs=[],
                )
            elif pygame.mouse.get_pressed(
            )[0] and 5 < mouse[0] < 75 and 76 < mouse[1] < 105:
                sys.exit()
            if pygame.mouse.get_pressed()[0] and 5 < mouse[
                    0] < 100 and 125 < mouse[1] < 160 and status == False:
                pygame.time.wait(100)
                status = True
            elif pygame.mouse.get_pressed()[0] and 5 < mouse[
                    0] < 100 and 125 < mouse[1] < 160 and status1 == True:
                pygame.time.wait(100)
                status = False

            Menu.menu.background()
            Menu.menu.text('Morikov', 30, (15, 10), (255, 255, 255))
            Menu.menu.text('Vinokurov', 30, (15, 40), (255, 255, 255))
            Menu.menu.text('PLAY', 50, (350, 70), (0, 30, 0))
            Menu.menu.text('EXIT', 40, (15, 70), (255, 30, 0))
            Menu.menu.text('Hotkeys', 40, (15, 120), (255, 255, 255))

            if status == True:
                Menu.menu.text('W, A, S, D - КНОПКИ ПЕРЕДВИЖЕНИЯ', 15,
                               (15, 200), (255, 255, 255))
                Menu.menu.text(
                    '1,2,3,4 -КНОПКИ ОТВЕЧАЮЩИЕ ЗА СВОСОБНОСТИ ,КОТОРЫЕ АКТИВНЫ ПРИ ОПРЕДЕЛЕННЫХ УСЛОВИЯХ',
                    15, (15, 230), (255, 255, 255))
                Menu.menu.text('SHIFT- КНОПКА ОТВЕЧАЮЩАЯ ЗА БЛИНК ПЕРСОНАЖА',
                               15, (15, 260), (255, 255, 255))
                status1 = True

            pygame.display.update()
コード例 #27
0
 def test_getting_the_end_point_of_the_map_then_return_its_coordinates(
         self):
     h = Hero(name="Bron",
              title="Dragonslayer",
              health=100,
              mana=100,
              mana_regeneration_rate=2)
     d = Dungeon('test_maps/test.txt', h, 2)
     result = d.endpoint
     expected = (2, 2)
     self.assertEqual(result, expected)
コード例 #28
0
 def test_getting_the_spawning_coordinates_of_the_hero_on_the_S_location_on_map(
         self):
     h = Hero(name="Bron",
              title="Dragonslayer",
              health=100,
              mana=100,
              mana_regeneration_rate=2)
     d = Dungeon('test_maps/test.txt', h, 2)
     d.spawn()
     result = [d.hero_position_X, d.hero_position_Y]
     expected = [1, 0]
     self.assertEqual(result, expected)
コード例 #29
0
def ShowMap():
    """Рисует карту."""
    curmap = GameMap[CurMap]
    Lowlevel.PrepareMap()
    for x in xrange(curmap.LocalMapLeft,
                    curmap.LocalMapLeft + Const.LOCAL_MAP_WIDTH + 1):
        for y in xrange(curmap.LocalMapTop,
                        curmap.LocalMapTop + Const.LOCAL_MAP_HEIGHT + 1):
            Lowlevel.ShowCell(curmap.Cells[x][y], x, y)
    # Хак.
    Monsters.ShowMonsters()
    Hero.ShowHero(Hero.CurHero)
    Lowlevel.main()
コード例 #30
0
 def test_moving_the_hero_down_when_there_are_no_obstacles_then_compare_the_updated_coordinates(
         self):
     h = Hero(name="Bron",
              title="Dragonslayer",
              health=100,
              mana=100,
              mana_regeneration_rate=2)
     d = Dungeon('test_maps/no_obstacles.txt', h, 2)
     d.spawn()
     old_coordinates_after_update = (d.hero_position_X + 1,
                                     d.hero_position_Y)
     d.move_hero('down')
     new_coordinates = (d.hero_position_X, d.hero_position_Y)
     self.assertEqual(old_coordinates_after_update, new_coordinates)
コード例 #31
0
def Move(direction):
    global MAPS
    global PLAYER
    global ENEMIES
    bf = ENEMIES['brendan fallon']
    x = PLAYER.location[0]
    y = PLAYER.location[1]
    z = PLAYER.location[2]
    CurrentPlace = MAPS[x][y][z]
    Place = 0
    if direction not in CurrentPlace.walls:
        if direction == 'f':
            y += 1
        elif direction == 'b':
            y -= 1
        elif direction == 'r':
            x += 1
        elif direction == 'l':
            x -= 1
        elif direction == 'u':
            z += 1
        elif direction == 'd':
            z -= 1
        Place = MAPS[x][y][z]
    if Place:
        PLAYER.location[0] = x
        PLAYER.location[1] = y
        PLAYER.location[2] = z
        if bf.location != (None, None, None):
            MAPS[bf.location[0]][bf.location[1]][bf.location[2]].removeEnemy(
                bf)
        if random() <= 0.003:
            MAPS[x][y][z].placeEnemy(bf)
            Hero.Hero()
        if Place.travelled:
            print "========================================================================"
            print Place.lore + "\n\n" + Place.info + Place.search()
            Place.travelled = 0
        else:
            print "========================================================================"
            print Place.info + Place.search()
            return Place
    else:
        PLAYER.location[0] = CurrentPlace.coords[0]
        PLAYER.location[1] = CurrentPlace.coords[1]
        PLAYER.location[2] = CurrentPlace.coords[2]
        print "\nYou can't go that way!\n"
        return CurrentPlace
コード例 #32
0
ファイル: main.py プロジェクト: potcharajoe/BlockEscape
    def __init__(self):
        super(MonsterRunGame, self).__init__('MonsterRun', MonsterRunGame.BLACK)
        self.hero = Hero(radius=8,pos=(self.window_size[0]/2,self.window_size[1]/2),color=MonsterRunGame.RED)
        self.topwall=Wall(pos=(0,-1),width=self.window_size[0],height=1,color=MonsterRunGame.WHITE)
        self.bottomwall=Wall(pos=(0,self.window_size[1]-1),width=self.window_size[0],height=1,color=MonsterRunGame.WHITE)
        self.rightwall=Wall(pos=(self.window_size[0],0),width=1,height=self.window_size[1],color=MonsterRunGame.WHITE)
        self.leftwall=Wall(pos=(-1,0),width=1,height=self.window_size[1],color=MonsterRunGame.WHITE)
        self.enemies=[]
        self.item=Item(pos=(random.randint(10,1014),random.randint(10,710)),color=MonsterRunGame.WHITE)
        self.score = 0
        self.score_debounce =0
        self.score_error = 7
        self.gameover = False
        self.plusscore = False

        for i in range(7):            
            enemy = Enemy(color=pygame.Color(random.randrange(150,255,40),random.randrange(0,150,40),random.randrange(150,255,40)),pos=(random.randrange(20,800,80),random.randrange(20,500,80)),speed=(100,50),rectwidth=random.randrange(30,120),rectheight=random.randrange(30,120))
            self.enemies.append(enemy)
コード例 #33
0
ファイル: Game.py プロジェクト: vmohheng/NPRZC
BG = pygame.sprite.Group()
herogroup = pygame.sprite.Group()
bulletgroup = pygame.sprite.Group()

#TEST INITIATION FOR WEAPON
#backcoll = [] #Background collision pixels

weapon = BasicWeapon()
weapon.screenSize = screenSize
weapon.bulletgroup = bulletgroup
weapon.allgroup = allSprites
weapon.bgcoll = BG
#weapon.bgcoll = backcoll

#Instantiate sprites
hero = Hero((screenSize[0]/2, screenSize[1]/2), screenSize, screenPos)
allSprites.add(hero)
herogroup.add(hero)
hero.Backgroundcoll = BG


nr = 2
mr = 2
stepsize = 650

for n in range(0, nr):
    for m in range(0, mr):
        ns = Background((n*stepsize, m*stepsize), screenSize, screenPos, 'Images\\davince2.png', 'Images\\colltest3.bmp', BG)
        k = int((n*mr+m)/(nr*mr)*100)
        print('Loading: ' + str(k) +'%')
        allSprites.add(ns)
コード例 #34
0
ファイル: main.py プロジェクト: potcharajoe/BlockEscape
class MonsterRunGame(gamelib.SimpleGame):
    BLACK = pygame.Color('black')
    WHITE = pygame.Color('white')
    GREEN = pygame.Color('green')
    RED = pygame.Color('red')
    
    def __init__(self):
        super(MonsterRunGame, self).__init__('MonsterRun', MonsterRunGame.BLACK)
        self.hero = Hero(radius=8,pos=(self.window_size[0]/2,self.window_size[1]/2),color=MonsterRunGame.RED)
        self.topwall=Wall(pos=(0,-1),width=self.window_size[0],height=1,color=MonsterRunGame.WHITE)
        self.bottomwall=Wall(pos=(0,self.window_size[1]-1),width=self.window_size[0],height=1,color=MonsterRunGame.WHITE)
        self.rightwall=Wall(pos=(self.window_size[0],0),width=1,height=self.window_size[1],color=MonsterRunGame.WHITE)
        self.leftwall=Wall(pos=(-1,0),width=1,height=self.window_size[1],color=MonsterRunGame.WHITE)
        self.enemies=[]
        self.item=Item(pos=(random.randint(10,1014),random.randint(10,710)),color=MonsterRunGame.WHITE)
        self.score = 0
        self.score_debounce =0
        self.score_error = 7
        self.gameover = False
        self.plusscore = False

        for i in range(7):            
            enemy = Enemy(color=pygame.Color(random.randrange(150,255,40),random.randrange(0,150,40),random.randrange(150,255,40)),pos=(random.randrange(20,800,80),random.randrange(20,500,80)),speed=(100,50),rectwidth=random.randrange(30,120),rectheight=random.randrange(30,120))
            self.enemies.append(enemy)

    def init(self):
        super(MonsterRunGame, self).init()
        self.render_score()

    def update(self):

        if(self.is_key_pressed(K_RETURN)):
            self.hero.resetpos(self.surface)
            self.gameover=False
            self.score=0
            self.render_score()

            for enemy in self.enemies:
                enemy.resetspeed()
                enemy.addspeed=0
       
        if(self.hero.checkplayer(self.surface)==None or self.is_key_pressed(K_RETURN)) :        
            
            if(not(self.gameover) or (pygame.time.get_ticks())/1000<5):

                for enemy in self.enemies:
                    enemy.update()
                    enemy.move(1./self.fps)

                    if(enemy.getRectenemy().colliderect(self.topwall.getRectwall()) and enemy.y<5 ):
                        enemy.y = 1
                        enemy.moveinverseone()
                        enemy.change_color()
                    elif (enemy.getRectenemy().colliderect(self.bottomwall.getRectwall()) and (enemy.y>715-enemy.rectheight)):
                        enemy.y = 719-enemy.rectheight
                        enemy.moveinverseone()
                        enemy.change_color()
                    elif (enemy.getRectenemy().colliderect(self.leftwall.getRectwall()) and (enemy.x<5)):
                        enemy.x = 1
                        enemy.moveinversetwo()
                        enemy.change_color()
                    elif (enemy.getRectenemy().colliderect(self.rightwall.getRectwall()) and (enemy.x>1019-enemy.rectwidth)):
                        enemy.x = 1023-enemy.rectwidth
                        enemy.moveinversetwo()
                        enemy.change_color()

                    if(enemy.getRectenemy().colliderect(self.hero.getRecthero())):
                        self.gameover = True

                    if(self.hero.getRecthero().colliderect(self.item.getRectitem())):

                        self.item.randomspawn(self.surface)
                        self.score_debounce +=1
                        self.render_score()


                    if((pygame.time.get_ticks())/1000%5 == 0):
                        enemy.addspeed+=0.05

                    if self.is_key_pressed(K_UP):
                        self.hero.move_up()
                    if self.is_key_pressed(K_DOWN):
                        self.hero.move_down()
                    if self.is_key_pressed(K_LEFT):
                        self.hero.move_left()
                    if self.is_key_pressed(K_RIGHT):
                        self.hero.move_right()

                    print self.score_debounce

                    if(self.score_debounce == 1):
                        self.score +=1
                    
                    if self.score_debounce%self.score_error == 0:
                        self.score_debounce = 0    

        self.item.update()
        self.hero.update()

        
    def render_score(self):

        self.score_image = self.font.render("Score = %d" % self.score, 0, MonsterRunGame.WHITE)

    def render(self, surface):

        for enemy in self.enemies:
            enemy.render(surface)
        self.hero.render(surface)
        self.topwall.render(surface)
        self.bottomwall.render(surface)
        self.leftwall.render(surface)
        self.rightwall.render(surface)
        self.item.render(surface)
        surface.blit(self.score_image, (10,10))
コード例 #35
0
ファイル: Game.py プロジェクト: vmohheng/NPRZC
BG = pygame.sprite.Group() #The background
herogroup = pygame.sprite.Group() #Just for the hero
enemygroup = pygame.sprite.Group() #Just for enemies
bulletgroup = pygame.sprite.Group() #All the projectiles
weapongroup = pygame.sprite.Group() #All the weapons on the ground
weapondisplaygroup = pygame.sprite.Group() #The weapons BEING HELD

#Declare globals
GameSprite.BG = BG
GameSprite.allSprites = allSprites
GameSprite.screenSize = screenSize
GameSprite.bullets = bulletgroup
GameSprite.weapons = weapondisplaygroup

#Initiate hero
hero = Hero((screenSize[0]/2, screenSize[1]/2), screenPos)
hero.enemies = enemygroup
hero.takeWeapon(TestWeapon(hero, 0, 5))
hero.switchWeapon()


#Test enemy
enemy = Enemy((5, 5), screenPos)
enemy.enemies = herogroup
enemy.weapon = Pistol(enemy, 0, 1)
enemy2 = Enemy((130, 5), screenPos)
enemy2.enemies = herogroup
enemy2.weapon = Pistol(enemy2, 0, 1)
allSprites.add(enemy)
enemygroup.add(enemy)
allSprites.add(enemy2)
コード例 #36
0
__author__ = 'Polle'
import csv
import random as ran
import  time
import Highscore
import Hero
import Score

import Timer

score = Score.Score()
name = input("wat is you naam?! ")
score.startGame()
Timer.startTimer(score)
print("Hint 1:")
hero_list = Hero.loadHeroes()
ran.seed(time.gmtime())
random_hero = hero_list[ran.randint(0, len(hero_list) - 1)]
#print(random_hero)
print(random_hero.hint())
while score.GAMESTATE == "STARTED":
    userInput = input("Guess: ")
    if userInput == "hint":
        print(random_hero.hint())
        score.aftrek(3)
    elif userInput == random_hero.getName():
        score.winGame(score, name)
    else:
        score.aftrek(1)
print("The Hero was: ")
print(random_hero)
コード例 #37
0
ファイル: main.py プロジェクト: Stals/PythonRPG
gameType = getChoice("Choose game type:", list(gameTypes.keys())
selectedGame = getChoice("Choose game:", list(gameTypes[gameType].keys())
exec(open(selectedGame).read()) # Нужно перепистаь так как я хочу передавать кол-во денег у игрока и получать сколько он выйграл или проиграл (Но мини игры не обязательно азартные игры, и потому для некоторых ничего не нужно будет , а может что-то еще кроме денег. - Но пока ничего другого кроме денег не нужно лучше просто передавать деньги)
#? Может нужно писать через Pakage так же __init__ файл есть? чтобы можно было как-то так сделать что при добавлении туда файла с миниигрой он появлялся в игре.
# Я просто не хочу чтобы было 100500 инклюдов для каждой игры, а был каким-то образом инклюд всех файлов которые в minigames.
# Может нужно добавить папку minigames в Environment и тогда так же как и стандартные функции эти функции будут вызываться?
"""м
#TODO! Перенести все идеи которые разбросаны по коду в ideas.txt
#TODO!! Сделать отмени в бою!
#TODO! Добавить canUse методы в другие классы (weapon,armor - может можно просто в ITEM)
#TODO! внутри spell.__str__() выводится имя спелла и Описани того что он делает( зависит от спелла )
#TODO Сделать питомца - Pet наследуется от Entity
#Question делать боевку так чтобы если у тебя dex в 2 раза больше - ты ходиш в 2 раза чаще?
#TODO писать Physical damage если это не магический урон

player = Hero()
dragonMonster = Monster("Dragon",Stats(9,10,4,4,6,1),Damage(2,6),4,Elements(),10)
puppyMonster = Monster("Puppy",Stats(1,2,1,2,1,1),Damage(1,1),1,Elements(),5)

# TODO Если player.class = "Warrior" сделать
# player = Warrior(player)
#

magicBow = Weapon("Magic Bow",Stats(Agi=3,Dex=2),Damage(1,5))
fireSword = Weapon("Fire Sword",Stats(Str=3,Con=2),Damage(1,5))

player.inventory.addItem(magicBow)
player.inventory.addItem(fireSword)
player.equip(utils.getChoice("Choose weapon to equip:", player.inventory.items()))

コード例 #38
0
ファイル: game.py プロジェクト: lajohn4747/GreekGame
def main():

	# Setup stuff such as getting the surface and starting the engine
	pygame.init()
	DISPLAYSURF = pygame.display.set_mode((600, 600))
	pygame.display.set_caption('Hero of Greece') # Title
	DISPLAYSURF.fill(WHITE)
	people2 = {}
	allSprites  = {}

	#Loading up NPC's images
	hydraPic = [pygame.image.load('hydra.png'), pygame.image.load('hydra.png'), pygame.image.load('hydra.png')]
	npcL = [pygame.image.load('npc_left.png'), pygame.image.load('npc_left_L.png'), pygame.image.load('npc_left_R.png')]
	npcR = [pygame.image.load('npc_right.png'), pygame.image.load('npc_right_L.png'), pygame.image.load('npc_right_R.png')]
	npcU = [pygame.image.load('npc_up.png'), pygame.image.load('npc_up_L.png'), pygame.image.load('npc_up_R.png')]
	npcD = [pygame.image.load('npc_down.png'), pygame.image.load('npc_down_L.png'), pygame.image.load('npc_down_R.png')]

	npc2L = [pygame.image.load('npc2_left.png'), pygame.image.load('npc2_left_L.png'), pygame.image.load('npc2_left_R.png')]
	npc2R = [pygame.image.load('npc2_right.png'), pygame.image.load('npc2_right_L.png'), pygame.image.load('npc2_right_R.png')]
	npc2U = [pygame.image.load('npc2_up.png'), pygame.image.load('npc2_up_L.png'), pygame.image.load('npc2_up_R.png')]
	npc2D = [pygame.image.load('npc2_down.png'), pygame.image.load('npc2_down_L.png'), pygame.image.load('npc2_down_R.png')]

	farmerL = [pygame.image.load('helot_farmer_left.png'), pygame.image.load('helot_farmer_left_L.png'), pygame.image.load('helot_farmer_left_R.png')]
	farmerR = [pygame.image.load('helot_farmer_right.png'), pygame.image.load('helot_farmer_right_L.png'), pygame.image.load('npc_right_R.png')]
	farmerU = [pygame.image.load('helot_farmer_up.png'), pygame.image.load('helot_farmer_up_L.png'), pygame.image.load('helot_farmer_up_R.png')]
	farmerD = [pygame.image.load('helot_farmer.png'), pygame.image.load('helot_farmer_down_L.png'), pygame.image.load('helot_farmer_down_R.png')]

	soldierL = [pygame.image.load('Soldier_left.png'), pygame.image.load('Soldier_left_L.png'), pygame.image.load('Soldier_left_R.png')]
	soldierR = [pygame.image.load('Soldier_right.png'), pygame.image.load('Soldier_right_L.png'), pygame.image.load('Soldier_right_R.png')]
	soldierU = [pygame.image.load('Soldier_up.png'), pygame.image.load('Soldier_up_L.png'), pygame.image.load('Soldier_up_R.png')]
	soldierD = [pygame.image.load('Soldier_down.png'), pygame.image.load('Soldier_down_L.png'), pygame.image.load('Soldier_down_R.png')]

	enemyL = [pygame.image.load('enemy_left.png'), pygame.image.load('enemy_left_L.png'), pygame.image.load('enemy_left_R.png')]
	enemyR = [pygame.image.load('enemy_right.png'), pygame.image.load('enemy_right_L.png'), pygame.image.load('enemy_right_R.png')]
	enemyD = [pygame.image.load('enemy_up.png'), pygame.image.load('enemy_up_L.png'), pygame.image.load('enemy_up_R.png')]
	enemyU = [pygame.image.load('enemy_down.png'), pygame.image.load('enemy_down_L.png'), pygame.image.load('enemy_down_R.png')]

	#scene one - eight buildings
	building1 = Building(210,50, (0,0))
	building2 = Building(150, 100, (0,50))
	building3 = Building(100, 140,(0,150))
	building4 = Building(155, 50, (0,545))
	building5 = Building(155,50,(445,545))
	building6 = Building(150,190,(445,0))
	building7 = Building(50, 50, (547,260))
	building8 = Building(50, 50, (400,90))
	building9 = Building(50,40, (400,0))

    #scene 9 buildings
	building91 = Building(405,360,(0,100))
	building92 = Building(100, 360, (495,100))

	#scene 10 buildings
	buildingS1 = Building(100, 130, (0,70))
	buildingS2 = Building(100,200,(150,0))
	buildingS3 = Building(205,80,(350,0))
	buildingS4 = Building(250,230,(0,255))
	buildingS5 = Building(105,120,(360,130))
	buildingS6 = Building(105,40,(360,315))
	buildingS7 = Building(85,80,(480,470))
	buildingS8 = Building(65,105,(530,250))

	#scene 2 buildings
	buildingA1 = Building(255, 100, (0,0))
	buildingA2 = Building(255, 75, (0,130))
	buildingA3 = Building(210, 45, (0,205))
	buildingA4 = Building(200, 75, (0,295))
	buildingA5 = Building(55, 130, (0,465))
	buildingA6 = Building(100, 130, (100,465))
	buildingA7 = Building(100, 45, (345,550))
	buildingA8 = Building(90, 100, (505,450))
	buildingA9 = Building(250, 55, (345,0))
	buildingA10 = Building(50, 300, (545,80))
	buildingA11 = Building(150, 130, (350,100))
	buildingA12 = Building(110, 140, (390,230))
	
    #people
	first = Hero(50, 50, (300,300))
	first.setSurface(DISPLAYSURF)
	second = Person((0,400), soldierL, soldierR, soldierU, soldierD)
	soldier1 = Person((0,400), soldierL, soldierR, soldierU, soldierD)
	soldier2 = Person((0,470), soldierL, soldierR, soldierU, soldierD)


	'''
	Important NPC's
	'''
	# The starting NPC's
	scaredW1 = Person((280,0), npcL, npcR, npcU, npcD)
	scaredM1 = Person((320,0), npc2L, npc2R, npc2U, npc2D)
	allSprites["scaredW1"] = scaredW1
	allSprites["scaredM1"] = scaredM1
	scene1People = {}
	scene1People["scaredW1"] = scaredW1
	scene1People["scaredM1"] = scaredM1
	scene1People["building1"] = building1
	scene1People["building2"] = building2
	scene1People["building3"] = building3
	scene1People["building4"] = building4
	scene1People["building5"] = building5
	scene1People["building6"] = building6
	scene1People["building7"] = building7
	scene1People["building8"] = building8
	scene1People["building9"] = building9

	Guard1 = Person((310,0), soldierL, soldierR, soldierU, soldierD)
	Guard2 = Person((260,0), soldierL, soldierR, soldierU, soldierD)
	Guard1.addDialogue(Dialogue("You cannot pass until you have the people's favor. We need a true champion to fight the beast."))
	Guard1.addDialogue(Dialogue("You cannot pass until you have the people's favor. We need a true champion to fight the beast."))
	Guard1.addDialogue(Dialogue("You cannot pass until you have the people's favor. We need a true champion to fight the beast."))
	Guard2.addDialogue(Dialogue("You cannot pass until you have the people's favor. We need a true champion to fight the beast."))
	Guard2.addDialogue(Dialogue("You cannot pass until you have the people's favor. We need a true champion to fight the beast."))
	Guard2.addDialogue(Dialogue("You cannot pass until you have the people's favor. We need a true champion to fight the beast."))
	allSprites["Guard1"] = Guard1
	allSprites["Guard2"] = Guard2
	'''
	Useless NPC's just giving information about the city, they have five different responses based on you likability
	'''
	# Spartan People
	spartanW1 = Person((0, 245), npcL, npcR, npcU, npcD)
	spartanW1.addDialogue(Dialogue("Spartans are a people of honor, maybe you should understand that before entering this city"))
	spartanW1.addDialogue(Dialogue("You are a scum without honor, how dare you show your face here"))
	spartanW1.addDialogue(Dialogue("Hello fine warrior, I cannot believe that you are not a native spartan"))
	allSprites["spartanW1"] = spartanW1

	spartanM1 = Person((200, 500), npc2L, npc2R, npc2U, npc2D)
	spartanM1.addDialogue(Dialogue("Hmmm if only were you a more suitable fighter, Sparta would honor you as a hero."))
	spartanM1.addDialogue(Dialogue("You consider yourself a hero? More a coward than anything."))
	spartanM1.addDialogue(Dialogue("I speak for the rest of Sparta and I say that you are truly a hero!"))
	allSprites["spartanM1"] = spartanM1

	scene10People = {}
	scene10People['spartanW1'] = spartanW1
	scene10People['spartanM1'] = spartanM1
	scene10People['buildingS1'] = buildingS1
	scene10People['buildingS2'] = buildingS2
	scene10People['buildingS3'] = buildingS3
	scene10People['buildingS4'] = buildingS4
	scene10People['buildingS5'] = buildingS5
	scene10People['buildingS6'] = buildingS6
	scene10People['buildingS7'] = buildingS7
	scene10People['buildingS8'] = buildingS8

    #stuff for scene 9
	poorFarmer = Person((150, 150), farmerL, farmerR, farmerU, farmerD)
	poorFarmer.addDialogue(Dialogue("Thank you, maybe you are the Greece needs in order to destroy the Hydra"))
	allSprites['poorFarmer'] = poorFarmer
	scene9People = {}
	scene9People['building91'] = building91
	scene9People['building92'] = building92
	scene9People['poorFarmer'] = poorFarmer
	
	#stuff for scene 2
	scene2People = {}
	scene2People['buildingA1'] = buildingA1
	scene2People['buildingA2'] = buildingA2
	scene2People['buildingA3'] = buildingA3
	scene2People['buildingA4'] = buildingA4
	scene2People['buildingA5'] = buildingA5
	scene2People['buildingA6'] = buildingA6
	scene2People['buildingA7'] = buildingA7
	scene2People['buildingA8'] = buildingA8
	scene2People['buildingA9'] = buildingA9
	scene2People['buildingA10'] = buildingA10
	scene2People['buildingA11'] = buildingA11
	scene2People['buildingA12'] = buildingA12

	# Athens People
	athensW1 = Person((250, 250), npcL, npcR, npcU, npcD)
	athensW1.addDialogue(Dialogue("The blessed Athena believes justice should be settled by the people"))
	athensW1.addDialogue(Dialogue("You are a lawless monster, how dare you tarnish this city with your presence"))
	athensW1.addDialogue(Dialogue("You are truly the suymbol of justics, Athena blesses you"))
	allSprites["athensW1"] = athensW1

	athensM1 = Person((300, 400), npc2L, npc2R, npc2U, npc2D)
	athensM1.addDialogue(Dialogue("Killing people may satisfy one's vengeance but it does not cleanse the soul"))
	athensM1.addDialogue(Dialogue("Your anger consumes you. You must learn to control yourself before you fight the darkness"))
	athensM1.addDialogue(Dialogue("Your reputation precedes you, I believe you are the true hero of Athens. Do not lose sight of justice"))
	allSprites["athensM1"] = athensM1

	scene2People = {}
	scene2People["athensW1"] = athensW1
	scene2People["athensM1"] = athensM1
	#buildings for scene 2
	scene2People['buildingA1'] = buildingA1
	scene2People['buildingA2'] = buildingA2
	scene2People['buildingA3'] = buildingA3
	scene2People['buildingA4'] = buildingA4
	scene2People['buildingA5'] = buildingA5
	scene2People['buildingA6'] = buildingA6
	scene2People['buildingA7'] = buildingA7
	scene2People['buildingA8'] = buildingA8
	scene2People['buildingA9'] = buildingA9
	scene2People['buildingA10'] = buildingA10
	scene2People['buildingA11'] = buildingA11
	scene2People['buildingA12'] = buildingA12

	# Delphi People
	delphiW1 = Person((175, 445), npcL, npcR, npcU, npcD)
	delphiW1.addDialogue(Dialogue("There is a monster out there in the north, I wonder who can stop him"))
	delphiW1.addDialogue(Dialogue("I know you may be strong but I think you aren't fit to be a hero. Delphi will never vote for you"))
	delphiW1.addDialogue(Dialogue("Hurry save us hero"))
	allSprites["dephiW1"] = delphiW1

	oldManQuest = Person((480, 115), npc2L, npc2R, npc2U, npc2D)
	oldManQuest.addDialogue(Dialogue("I am a great philosopher and I have great deciples but one of them has went rogue and killed my son. Athenian law wants to stop him but I want to make sure he pays"))
	oldManQuest.addDialogue(Question("Will you exact my vengeance", ["Yes", "No"], ["LooseApprentence", "NoApprentence"]), True)
	allSprites["oldManQuest"] = oldManQuest

	delphiM1 = Person((215, 135), farmerL, farmerR, farmerU, farmerD)
	delphiM1.addDialogue(Dialogue("Many have left due to the attacks of the monsters, the cities are trying to determine who they should send. \
		Perhaps it would be ideal if all cities liked a single person but they are so divided"))
	delphiM1.addDialogue(Dialogue("I don't know what to say about Sparta and Athens but I know for sure that Delphi will never choose you as their hero with all your blasphehemy."))
	delphiM1.addDialogue(Dialogue("I hope you were able to get Sparta and Athens to choose you, because the city of Delphi adores you and your holy blade"))
	allSprites["dephiM1"] = delphiM1

	scene11People = {}
	scene11People["delphiW1"] = delphiW1
	scene11People["delphiM1"] = delphiM1
	scene11People["Guard1"] = Guard1
	scene11People["Guard2"] = Guard2
	scene11People["oldManQuest"] = oldManQuest
	#scene 11 buildings
	buildingD1 = Building(205, 85, (0,0))
	buildingD2 = Building(100, 95, (355,0))
	buildingD3 = Building(85, 95, (510,0))
	buildingD4 = Building(240, 75, (0,160))
	buildingD5 = Building(130, 105, (0,235))
	buildingD6 = Building(80, 75, (170,290))
	buildingD7 = Building(85, 200, (360,155))
	buildingD8 = Building(80, 200, (515,150))
	buildingD9 = Building(130, 125, (0,470))
	buildingD10 = Building(80, 125, (170,470))
	buildingD11 = Building(100, 125, (355,470))
	buildingD12 = Building(85, 105, (510,490))
	scene11People["buildingD1"] = buildingD1
	scene11People["buildingD2"] = buildingD2
	scene11People["buildingD3"] = buildingD3
	scene11People["buildingD4"] = buildingD4
	scene11People["buildingD5"] = buildingD5
	scene11People["buildingD6"] = buildingD6
	scene11People["buildingD7"] = buildingD7
	scene11People["buildingD8"] = buildingD8
	scene11People["buildingD9"] = buildingD9
	scene11People["buildingD10"] = buildingD10
	scene11People["buildingD11"] = buildingD11
	scene11People["buildingD12"] = buildingD12

	#Scene 7 enemies
	enemy1 = Enemy((200,300),6, people2, enemyL, enemyR, enemyD, enemyU)
	enemy2 = Enemy((400,300),6, people2, enemyL, enemyR, enemyD, enemyU)
	soldier1Enemy = Enemy((0,0), 20, scene9People, soldierL, soldierR, soldierU, soldierD, 3)
	soldier2Enemy = Enemy((0,0), 20, scene9People, soldierL, soldierR, soldierU, soldierD)
	soldier3Enemy = Enemy((0,360), 10, {}, soldierL, soldierR, soldierU, soldierD,4)
	soldier4Enemy = Enemy((0,410), 16, {}, soldierL, soldierR, soldierU, soldierD,3)
	apprentence = Enemy((300, 300), 8, {},  npcL, npcR, npcU, npcD, 10)

	hydra = Enemy((300, 100), 40, {}, hydraPic, hydraPic, hydraPic, hydraPic, 12)
	boss = [hydra]

	allSprites['apprentence'] = apprentence
	allSprites['soldier1Enemy'] = soldier1Enemy
	allSprites['soldier2Enemy'] = soldier2Enemy
	allSprites['soldier3Enemy'] = soldier3Enemy
	allSprites['soldier4Enemy'] = soldier4Enemy
	enemies7 = [enemy1, enemy2]

        #scene 8 enemy
	enemy3 = Enemy((100,400),6, people2, enemyL, enemyR, enemyD, enemyU)
	enemy8 = Enemy((300,200),6, people2, enemyL, enemyR, enemyD, enemyU)
	enemies8 = [enemy3,enemy8]

	#scene 3 enemy
	enemy4 = Enemy((500,400),6, people2, enemyL, enemyR, enemyD, enemyU)
	enemy7 = Enemy((300,200),6, people2, enemyL, enemyR, enemyD, enemyU)
	enemies3 = [enemy4,enemy7]

	#scene 5 enemies
	enemy5 = Enemy((200,325),6, people2, enemyL, enemyR, enemyD, enemyU)
	enemy6 = Enemy((100,400),6, people2, enemyL, enemyR, enemyD, enemyU)
	enemies5 = [enemy5, enemy6]

	# Add buildings for all the cities
	building = Building(80,80,(0,520))

	second.addDialogue(Dialogue("Will you help me?"))
	second.addDialogue(Question("Will you help?", ["Help", "Do not Help"], ["guyThanks", "guyHates"]), True)
	allSprites["guy"] = second
	allSprites["Hero"] = first
	allSprites["soldier1"] = soldier1
	allSprites["soldier2"] = soldier2


	people2["building1"] = building1
	people2["building2"] = building2
	people2["building3"] = building3
	people2["building4"] = building4
	people2["building5"] = building5
	people2["building6"] = building6
	people2["building7"] = building7
	people2["building8"] = building8
	people2["building9"] = building9


	#hero sprite is 25 pixels wide, 40 tall											
	scene1 = Scene(DISPLAYSURF, scene1People, first, background = pygame.image.load('midpoint.png').convert(), transition_points = {1:[250,350,0,0], 2:[0,0,365,465], 4:[575,600,365,465]}, entranceTrigger = "startScene")
	scene2 = Scene(DISPLAYSURF, scene2People, first, background = pygame.image.load('fran_athens_city.png').convert(), transition_points = {2:[0,0,365,465], 3:[250,350,560,600], 4:[575,600,365,465]})
	scene3 = Scene(DISPLAYSURF, {}, first, enemies3, background = pygame.image.load('rightbottomL.png').convert(), transition_points = {2:[0,0,365,465], 3:[250,350,560,600]})
	scene4 = Scene(DISPLAYSURF, {}, first, background = pygame.image.load('leftLroad.png').convert(), transition_points = {1:[250,350,0,0], 2:[0,0,365,465]}, entranceTrigger = "beginning")
	scene5 = Scene(DISPLAYSURF, people2, first, enemies5, background = pygame.image.load('rightLroad.png').convert(), transition_points = {1:[250,350,0,0], 4:[575,600,365,465]})
	#scene6 doesn't exist anymore, but left it there so we don't have to rename everything
	scene6 = Scene(DISPLAYSURF, people2, first)
	scene7 = Scene(DISPLAYSURF, people2, first, enemies7, background = pygame.image.load('leftLroad.png').convert(), transition_points = {1:[250,350,0,0], 2:[0,0,365,465]})
	scene8 = Scene(DISPLAYSURF, people2, first, enemies8, background = pygame.image.load('rightLroad.png').convert(), transition_points = {1:[250,350,0,0], 4:[575,600,365,465]})
	scene9 = Scene(DISPLAYSURF, scene9People, first, background = pygame.image.load('fran_sparta_helotfarm.png').convert(), transition_points = {3:[250,350,560,600], 4:[575,600,487,584]}, entranceTrigger = "poorFarmer")
	scene10= Scene(DISPLAYSURF, scene10People, first, background = pygame.image.load('fran_sparta_city.png').convert(), transition_points = {2:[0,0,487,584], 3:[250,350,560,600], 4:[575,600,365,465]})
	scene11= Scene(DISPLAYSURF, scene11People, first, background = pygame.image.load('fran_delphi_city.png').convert(), transition_points = {1:[250,350,0,0], 3:[250,350,560,600]})
	scene12= Scene(DISPLAYSURF, people2, first, boss, background = pygame.image.load('finalmonster_room_withopening.png').convert(), transition_points = {3:[250,350,560,600]})

	scenes_list = [scene1, scene2, scene3, scene4, scene5, scene6, scene7, scene8, scene9, scene10, scene11, scene12]

	theGame = Game(scenes_list, allSprites, DISPLAYSURF, first)

	current_scene = scenes_list[0]
	current_scene_num = 1
	current_hero_coords = (300,400)

	while True:
		#print(current_scene_num)
		state_of_current_scene, last_hero_coords = current_scene.run(current_hero_coords)
		if state_of_current_scene == "Dead":
			break
		if state_of_current_scene > 0:
			new_scene_num, current_hero_coords = getNextScene(current_scene_num, state_of_current_scene, last_hero_coords)
			current_scene_num = new_scene_num
			current_scene = scenes_list[new_scene_num-1]
	DISPLAYSURF.fill(WHITE)
	DISPLAYSURF.blit(pygame.font.Font(None, 22).render("You Lose", True, BLACK), (300, 300))
	pygame.display.update()
	pygame.time.wait(2000)
コード例 #39
0
def ranHero():
    hero_list = Hero.loadHeroes()
    HER0 = hero_list[ran.randint(0, len(hero_list) - 1)]
    return HER0
コード例 #40
0
ファイル: game.py プロジェクト: DChaushev/the-last-stand
def start_game():

    zombie_count = 10
    player = Hero()
    zombies = []
    for i in range(zombie_count):
        zombie = Zombie()
        zombies.append(zombie)

    """This is a timer, I use for measuring 1 second. Every second the player is alive,
        he gets 1 point. For every zombie he kills - 5 points"""
    scoreIncrementTimer = 0
    lastFrameTicks = pygame.time.get_ticks()

    while 1:

        DISPLAYSURF.fill(TERRAINCOLOR)
        DISPLAYSURF.blit(player.surface, (player.x, player.y))

        gamefont = pygame.font.Font(None, 30)
        scoretext = gamefont.render('Score: ' + str(player.score), 2, [0, 0, 0])

        DISPLAYSURF.blit(scoretext, (900, 20))

        if player.animation_position_dead == player.animation_dead_max:
            gameOver(player)

        if player.is_alive:

            if not zombies:
                zombie_count += 5
                for i in range(zombie_count):
                    zombie = Zombie()
                    zombies.append(zombie)

            """We get rid of the dead zombies right after their dead animation is over.
                Over all still 'living' zombies, there is a health bar, which decrements with each hit."""

            zombies = [z for z in zombies if z.animation_dead_position < z.animation_dead_max]
            for z in zombies:
                DISPLAYSURF.blit(z.surface, (z.x, z.y))
                box = pygame.Rect(z.x, z.y, (z.health*z.surface.get_width())/10, -5)
                pygame.draw.rect(DISPLAYSURF, (255, 0, 0), box, 0)

            thisFrameTicks = pygame.time.get_ticks()
            ticksSinceLastFrame = thisFrameTicks - lastFrameTicks
            lastFrameTicks = thisFrameTicks

            scoreIncrementTimer = scoreIncrementTimer + ticksSinceLastFrame
            if scoreIncrementTimer > 1000:
                player.score += 1
                scoreIncrementTimer = 0

        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
            elif event.type == KEYDOWN:
                if event.key in (K_UP, K_w):
                    player.move_down = False
                    player.move_up = True
                elif event.key in (K_DOWN, K_s):
                    player.move_up = False
                    player.move_down = True
                elif event.key in (K_LEFT, K_a):
                    player.move_right = False
                    player.move_left = True
                elif event.key in (K_RIGHT, K_d):
                    player.move_left = False
                    player.move_right = True
                elif event.key == K_SPACE:
                    player.shooting = True
                    player.fire(zombies)
                elif event.key == K_ESCAPE:
                    return
            elif event.type == KEYUP:
                if event.key in (K_UP, K_w):
                    player.move_up = False
                elif event.key in (K_DOWN, K_s):
                    player.move_down = False
                elif event.key in (K_RIGHT, K_d):
                    player.move_right = False
                elif event.key in (K_LEFT, K_a):
                    player.move_left = False
                elif event.key == K_SPACE:
                    player.shooting = False

        player.update()

        for z in zombies:
            dead = z.update(player.x, player.y, player.surface.get_width(), player.surface.get_height())

            if dead:
                player.is_alive = False

        pygame.display.update()
        FPSCLOCK.tick(FPS)