def main(): colided_list = [] level, screen, clock, fps, rect_list = set_config() group = RenderUpdates() heroine = Hero(100, 30, group) keys = { K_LEFT: False, K_RIGHT: False, K_UP: False, K_DOWN: False, K_RETURN: False, 27: False, K_a: False } # obs 27 = 'esc' pygame.display.flip() while True: clock.tick(fps) for event in pygame.event.get([KEYUP, KEYDOWN]): value = (event.type == KEYDOWN) if event.key in keys: keys[event.key] = value idx = heroine.rect.collidelist(rect_list) if idx != -1 and rect_list[idx] not in colided_list: colided_list.append(rect_list[idx]) print rect_list[idx] if rect_list[ idx].x <= heroine.rect.x and heroine.rect.x <= rect_list[ idx].width: heroine.fsm.set_state("stand_still") heroine.cannot_move_to = None #import pdb; pdb.set_trace() else: heroine.cannot_move_to = heroine.fsm.side if idx == -1: heroine.fsm.set_state("fall") if keys[27]: # tecla ESC pygame.quit() sys.exit() elif keys[K_LEFT] and heroine.cannot_move_to != "left": heroine.fsm.set_state("move") heroine.fsm.update("left") elif keys[K_RIGHT] and heroine.cannot_move_to != "right": heroine.fsm.set_state("move") heroine.fsm.update("right") elif keys[K_UP]: heroine.fsm.set_state("jump") elif keys[K_DOWN]: heroine.fsm.set_state("get_down") elif keys[K_a]: heroine.fsm.set_state("attack") heroine.fsm.auto_update() utils.clear_screen(level, screen) pygame.display.update(group.draw(screen))
def __init__(self): self.view = View() self.map = Map() self.hero = Hero() self.view.screen(self.map.playscreen) self.view.draw_hero(self.hero.x, self.hero.y, "down") self.view.canvas.bind("<Up>", self.move_up) self.view.canvas.bind("<Down>", self.move_down) self.view.canvas.bind("<Left>", self.move_left) self.view.canvas.bind("<Right>", self.move_right) self.enemies = [Skeletons(8, 10), Skeletons(7, 5), Boss(4, 4)] self.view.draw_enemies(self.enemies)
def __init__(self): self._running = None self._surface = None self._size = self.weight, self.height = 812, 650 self._map = Map(50, (10, 10)) self._player_turn = None self._image_library = None self._action = None self._marked = None self._lost = None pos_x, pos_y = self.get_start_position() self._hero = Hero(10, 5, 10, 10, 200, pos_x, pos_y)
def __init__(self): self.view = Visual() self.map = map.game_map self.hero = Hero() self.view.screen(self.map) self.view.draw_hero(self.hero.x, self.hero.y) self.view.draw_boss(4, 0) self.view.draw_skeleton(9, 0) self.view.draw_skeleton(9, 9) self.view.draw_skeleton(4, 6) self.view.canvas.bind('<Up>', self.move_up) self.view.canvas.bind('<Down>', self.move_down) self.view.canvas.bind('<Left>', self.move_left) self.view.canvas.bind('<Right>', self.move_right)
def __init__(self): self.view = View() self.map = Map() self.characters = Characters('anyadat') self.hero = Hero() self.skeleton = Skeleton() self.boss = Boss() self.view.draw_map(self.map.gamezone1)
def test_inits(self): char = C.Character('Grognak') # YOU MADE A CHARACTER self.assertIsInstance(char,C.Character) # You made a hero hero = H.Hero('Grognak', [20, 20]) self.assertIsInstance(hero, H.Hero) # You made a monster monster = M.Monster('Goblin', 5, 5, 1) self.assertIsInstance(monster,M.Monster)
def main(): my_hero = Hero(name='Wencakisa', title='Kingslayer', health=100, mana=100, mana_regeneration_rate=2) my_enemy = Enemy(health=100, mana=100, damage=10) my_weapon = Weapon(name='Windcutter', damage=10) my_spell = Spell(name='Fireball', damage=7, mana_cost=4, cast_range=1) my_hero.equip(my_weapon) my_hero.learn(my_spell) while my_hero.is_alive() and my_enemy.is_alive(): print(my_enemy.attack(enemy=my_hero)) my_enemy.take_healing(healing_points=40) print(my_hero.attack(by='spell', enemy=my_enemy)) print(my_hero.attack(by='weapon', enemy=my_enemy))
def setup(keySet, resolution): hero = Hero({ "Name": 'Hero', "Lvl": 1, "Exp": 0, "Atk": 3, "Def": 4, "Stam": 3, "Health": 25, "ExpPoint": 50, "Skills": [], }) curMap = Map() level = Levels() makeWindow(hero, curMap, level, keySet, resolution)
class GamePlay: def __init__(self): self.view = Visual() self.map = map.game_map self.hero = Hero() self.view.screen(self.map) self.view.draw_hero(self.hero.x, self.hero.y) self.view.draw_boss(4, 0) self.view.draw_skeleton(9, 0) self.view.draw_skeleton(9, 9) self.view.draw_skeleton(4, 6) self.view.canvas.bind('<Up>', self.move_up) self.view.canvas.bind('<Down>', self.move_down) self.view.canvas.bind('<Left>', self.move_left) self.view.canvas.bind('<Right>', self.move_right) def start(self): self.view.appear() def move_up(self, event): if self.hero.y-1<=11 and self.hero.y-1>=0: if self.map[self.hero.y-1][self.hero.x] == 0: self.hero.move_hero(0,-1) self.view.draw_hero(self.hero.x, self.hero.y, 'up') def move_down(self, event): if self.hero.y+1<=11 and self.hero.y+1>=0: if self.map[self.hero.y+1][self.hero.x] == 0: self.hero.move_hero(0,1) self.view.draw_hero(self.hero.x, self.hero.y, 'down') def move_left(self, event): if self.hero.x-1<=11 and self.hero.x-1>=0: if self.map[self.hero.y][self.hero.x-1] == 0: self.hero.move_hero(-1,0) self.view.draw_hero(self.hero.x, self.hero.y, 'left') def move_right(self, event): if self.hero.x+1<=11 and self.hero.x+1>=0: if self.map[self.hero.y][self.hero.x+1] == 0: self.hero.move_hero(1,0) self.view.draw_hero(self.hero.x, self.hero.y, 'right')
class Game_play: def __init__(self): self.view = View() self.map = Map() self.hero = Hero() self.view.screen(self.map.playscreen) self.view.draw_hero(self.hero.x, self.hero.y, "down") self.view.canvas.bind("<Up>", self.move_up) self.view.canvas.bind("<Down>", self.move_down) self.view.canvas.bind("<Left>", self.move_left) self.view.canvas.bind("<Right>", self.move_right) self.enemies = [Skeletons(8, 10), Skeletons(7, 5), Boss(4, 4)] self.view.draw_enemies(self.enemies) def start(self): self.view.show() def valid_move(self, cell_x, cell_y): if cell_x in range(0, 10) and cell_y in range(0, 11): if self.map.playscreen[cell_y][cell_x] == 0: return True else: return False def move_up(self, event): if self.valid_move(self.hero.x, self.hero.y - 1): self.hero.move_hero(0, -1) self.view.draw_hero(self.hero.x, self.hero.y, "up") def move_down(self, event): if self.valid_move(self.hero.x, self.hero.y + 1): self.hero.move_hero(0, 1) self.view.draw_hero(self.hero.x, self.hero.y, "down") def move_left(self, event): if self.valid_move(self.hero.x - 1, self.hero.y): self.hero.move_hero(-1, 0) self.view.draw_hero(self.hero.x, self.hero.y, "left") def move_right(self, event): if self.valid_move(self.hero.x + 1, self.hero.y): self.hero.move_hero(1, 0) self.view.draw_hero(self.hero.x, self.hero.y, "right")
def test_hero_methods(self): # check that the set_starter_stats consistently sets the stats hero1 = H.Hero('Grognak', [1, 1]) hero1.set_starter_stats() self.assertTrue(hero1.current_hp,10) self.assertTrue(hero1.max_hp, 10) self.assertTrue(hero1.armor, 1) self.assertTrue(hero1.strength, 3) # Check that leveling works hero1.gain_xp(101) self.assertEqual(hero1.xp, 101) self.assertEqual(hero1.level, 2) # Check that set_opened_save_stats does the same hero1.set_opened_save_stats(8, 16, 3, 4, 150, 2, 1, 200, 23, 24) self.assertEqual(hero1.current_hp,8) self.assertEqual(hero1.max_hp, 16) self.assertEqual(hero1.armor, 3) self.assertEqual(hero1.strength, 4) self.assertEqual(hero1.xp, 150) self.assertEqual(hero1.level, 2) self.assertEqual(hero1.money, 1) self.assertEqual(hero1.next_level, 200) self.assertEqual(hero1.hero_pos, [23, 24]) # check for hp gains hero1.gain_hp_from_rest(True) self.assertEqual(hero1.current_hp, 12) # check that not only does this heal, but not more than it should hero1.gain_hp_from_rest(False) self.assertEqual(hero1.current_hp, 14) # make sure 'overhealing' isnt possible hero1.gain_hp_from_rest(True) self.assertEqual(hero1.current_hp, 16) monster = M.Monster('Goblin', 5, 5, 1) monster.attack_enemy(hero1) # The goblin is too weak to harm the hero. self.assertEqual(hero1.current_hp,16) # The reverse is not true however hero1.attack_enemy(monster) self.assertLess(monster.current_hp, 1)
def init_hero(): hero = Hero(gameDisplay, 175, 450) # With his mighty hammer hero.equip(Hammer()) return hero
#Initialize pygame pygame.init() #Initialize and play the song pygame.mixer.music.load(MUSIC_PATH) pygame.mixer.music.play() #Create window screen = pygame.display.set_mode(SCREEN_SIZE) #Create labyrinth board_game = Labyrinth(TILE_IMAGE_PATH, WALL_IMAGE_PATH, MODEL_PATH) board_game.initialize_labyrinth(screen) #Create characters macgyver = Hero(HERO_IMAGE_PATH, MACGYVER_COORDINATES) the_guardian = Guardian(GUARDIAN_IMAGE_PATH, GUARDIAN_COORDINATES) #Create items needle = Item(NEEDLE_IMAGE_PATH, board_game) plastic_tube = Item(PLASTIC_TUBE_IMAGE_PATH, board_game) ether = Item(ETHER_IMAGE_PATH, board_game) #The game loop while ACTIVE: #If the music stops, it starts again if pygame.mixer.music.get_busy() == False: pygame.mixer.music.play() #Display the game
def generate_hero(): level = randint(1, 500) b = Hero("Superwoman", level) return b
def main(): pygame.init() size = [SCREEN_WIDTH, SCREEN_HEIGHT] screen = pygame.display.set_mode(size) pygame.display.set_caption("Ducking Ork Hunt") sprite_list = [(0, 97, 32, 47), (32, 97, 32, 47), (64, 97, 32, 47), (96, 97, 32, 47)] hero = Hero('.//characters//green_mage.png', sprite_list) hud = pygame.image.load( os.path.join('.//HUD//SleekBars_empty.png')).convert() level_list = [] level_list.extend([Training_ground(hero)]) level_number = 0 current_level = level_list[level_number] active_elements = pygame.sprite.Group() hero.ground = current_level hero.rect.x = 100 hero.rect.bottom = SCREEN_HEIGHT - 70 - 100 active_elements.add(hero) clock = pygame.time.Clock() gameExit = False while not gameExit: for event in pygame.event.get(): if hero.inactive_time: break if event.type == pygame.QUIT: gameExit = True elif event.type == pygame.KEYDOWN: if event.key == pygame.K_a: hero.move_left() elif event.key == pygame.K_d: hero.move_right() elif event.key == pygame.K_w: hero.jump() elif event.key == pygame.K_LSHIFT: hero.cast(Fire_lion) elif event.key == pygame.K_KP6: hero.cast(Fireball, 'R') elif event.key == pygame.K_KP9: hero.cast(Fireball, 'RU') elif event.key == pygame.K_KP3: hero.cast(Fireball, 'RD') elif event.key == pygame.K_KP4: hero.cast(Fireball, 'L') elif event.key == pygame.K_KP7: hero.cast(Fireball, 'LU') elif event.key == pygame.K_KP1: hero.cast(Fireball, 'LD') elif event.key == pygame.K_KP0: hero.cast(Ice_spikes) elif event.key == pygame.K_q: hero.drink_potion('mana') elif event.key == pygame.K_e: hero.drink_potion('health') elif event.key == pygame.K_RETURN: hero.use(clock, screen) elif event.type == pygame.KEYUP: if event.key == pygame.K_a: hero.stop() elif event.key == pygame.K_d: hero.stop() if event.type == pygame.KEYUP and event.key == pygame.K_SPACE: hero.teleporta() active_elements.update() current_level.update() hero.world_shift() current_level.draw(screen) screen.blit(hud, (35, 35)) hero.hud_draw(screen) active_elements.draw(screen) clock.tick(60) pygame.display.flip() pygame.quit()
from characters import Monster, Hero, Gorgon from random import randint def roll(sides): return randint(1, sides) if __name__ == "__main__": monster = Gorgon("Medussa", "stone gaze", 100, 100) hero = Hero("Perseus", "winged sandals", 100, 100) print(str(monster) + " vs. " + str(hero)) # roll for the hero count = 0 while not hero.is_dead() and not monster.is_dead(): health = roll(12) manna = roll(12) hero.hit(monster, health, manna) if monster.is_dead(): print("Hooray the monster is dead after ", count, " rolls") health = roll(12) manna = roll(12) monster.hit(hero, health, manna) if hero.is_dead(): print("Boo hoo the hero is dead after ", count, " rolls") count += 1
def main(): level, screen, clock, fps = set_config() group = RenderUpdates() heroine = Hero(20, 140, "elisa", group) keys = { K_LEFT: False, K_RIGHT: False, K_UP: False, K_DOWN: False, K_RETURN: False, 27: False, K_a: False } # obs 27 = 'esc' pygame.display.flip() while True: clock.tick(fps) for e in pygame.event.get([KEYUP, KEYDOWN]): valor = (e.type == KEYDOWN) if e.key in keys.keys(): keys[e.key] = valor if keys[27]: # tecla ESC pygame.quit() sys.exit() if heroine.attacking: heroine.animate_attack() elif keys[K_LEFT]: heroine.move("left") elif keys[K_RIGHT]: heroine.move("right") elif keys[K_UP]: heroine.jump() elif keys[K_DOWN]: heroine.get_down() elif keys[K_a]: heroine.attack() #heroine.is_jumping(gravity) utils.clear_screen(level, screen) pygame.display.update(group.draw(screen))
characters = [ Character('cat', 50, 15, kitten), Character('dog', 70, 10, pooch), Character('chicken', 60, 20, c**k), Character('dragon', 150, 40, viper), Character('tiger', 100, 30, tigress) ] ''' heroes = [ Hero('Alexa', 400, 35, 'agility', 3, 5, 2, assasin), Hero('Max', 650, 30, 'strength', 6, 3, 1, warrior), Hero('Furion', 350, 25, 'intelligence', 2, 4, 7, prophet) ] ''' thief = Hero('Alexa', 400, 35, 'agility', 3, 5, 2, assasin) defender = Hero('Maximus', 650, 30, 'strength', 6, 3, 1, warrior) prophet = Hero('Furion', 350, 25, 'intelligence', 2, 4, 7, prophet) create_5_monsters_no_prop = (np.random.choice(characters, 5).tolist()) print(create_5_monsters_no_prop, end='\n' + '*' * 30 + '\n') monster_creater = Monster_creater(characters, properties) create_25_monsters = [monster_creater.generate_monster() for i in range(25)] print(create_25_monsters) potion = Health_potion('potion of healing', 30) thief.inventory.add_item(potion) thief.inventory.add_item(potion) thief.inventory.add_item(potion) print(thief.inventory)
class App(object): """Główna klasa gry odpowiedzialna za rozgrywkę""" def __init__(self): self._running = None self._surface = None self._size = self.weight, self.height = 812, 650 self._map = Map(50, (10, 10)) self._player_turn = None self._image_library = None self._action = None self._marked = None self._lost = None pos_x, pos_y = self.get_start_position() self._hero = Hero(10, 5, 10, 10, 200, pos_x, pos_y) def init(self): """startowa inicjalizacja potrzebnych zmiennych""" pygame.init() pygame.display.set_caption('Rogal') self._surface = pygame.display.set_mode(self._size) self._running = True self.load_images() MUSIC.load_music() MUSIC.play_music() pygame.key.set_repeat(5, 50) #(delay, interval) in milisec self._lost = False def execute(self): """głowna pętla""" self.init() self._player_turn = True while self._running: for event in pygame.event.get(): self.event(event) # wykonaj przechwycona akcje if not self._player_turn: self.player_action() self.enemy_turn() if not self._lost: self.render() else: pygame.draw.rect(self._surface, (0, 0, 0), (0, 0, 812, 650)) Auxil.write(self._surface, "GAME OVER", 34, 300, 240) pygame.display.update() def event(self, event): """ Obsługa eventów: -wciśniętych klawiszy -muzyki -wyjścia z gry """ if event.type == pygame.QUIT: self._running = False if event.type == pygame.KEYDOWN: if self._player_turn: if event.key == LOC.K_UP or event.key == LOC.K_w: if self._hero.y > 0\ and self._map[self._hero.x, self._hero.y-1][0] != '_'\ and self._map[self._hero.x, self._hero.y-1][0] != 'w'\ and self._map[self._hero.x, self._hero.y-1][2] != 'bf': self._action = 'w' self._player_turn = False if event.key == LOC.K_DOWN or event.key == LOC.K_s: if self._hero.y < self._map.size[1]-1\ and self._map[self._hero.x, self._hero.y+1][0] != '_'\ and self._map[self._hero.x, self._hero.y+1][0] != 'w'\ and self._map[self._hero.x, self._hero.y+1][2] != 'bf': self._action = 's' self._player_turn = False if event.key == LOC.K_LEFT or event.key == LOC.K_a: if self._hero.x > 0\ and self._map[self._hero.x-1, self._hero.y][0] != '_'\ and self._map[self._hero.x-1, self._hero.y][0] != 'w'\ and self._map[self._hero.x-1, self._hero.y][2] != 'bf': self._action = 'a' self._player_turn = False if event.key == LOC.K_RIGHT or event.key == LOC.K_d: if self._hero.x < self._map.size[0]-1\ and self._map[self._hero.x+1, self._hero.y][0] != '_'\ and self._map[self._hero.x+1, self._hero.y][0] != 'w'\ and self._map[self._hero.x+1, self._hero.y][2] != 'bf': self._action = 'd' self._player_turn = False #added picking up items if event.key == LOC.K_RCTRL or event.key == LOC.K_e: if self._map[self._hero.position][1] is not None: # pick up - add to backpack for item in self._map[self._hero.position][1]: self._hero.equipment.add_to_backpack(item) # delete item from the floor self._map[self._hero.position][1] = None print self._hero.equipment.backpack # debug if event.key == LOC.K_ESCAPE: #quit self._running = False if event.key == LOC.K_m: #volume up if MUSIC.volume <= 1: MUSIC.volume += 0.05 pygame.mixer.music.set_volume(MUSIC.volume) if event.key == LOC.K_n: #volume down if MUSIC.volume >= 0: MUSIC.volume -= 0.05 pygame.mixer.music.set_volume(MUSIC.volume) if event.type == pygame.USEREVENT + 1: print(MUSIC.song_num, "song ended") MUSIC.play_music() if event.type == pygame.MOUSEBUTTONDOWN: if event.button == 1: po_x, po_y = pygame.mouse.get_pos() # mouse pointer in the equipment zone if po_x >= 610 and po_y >= 100 and po_y <= 100 + 4 * 40: (square_x, square_y) = ((po_x - 610) / 40, (po_y - 100) / 40) if not self._marked == (square_x, square_y): # if not already marked self._marked = (square_x, square_y) else: # swap item with wearing bp_place = square_y * 5 + square_x if bp_place < self._hero.equipment.backpack_len(): self._hero.equipment.use_item(bp_place) self._marked = None # mouse on lvl buttons if self._hero._skill_points != 0 \ and po_x >= 780 and po_x <= 780 + 16 \ and po_y >= 275 and po_y <= 275 + 5*16: num = (po_y - 275) / 16 if num == 0: self._hero.add_hp() elif num == 1: self._hero.add_attack() elif num == 2: self._hero.add_defense() elif num == 3: self._hero.add_strength() elif num == 4: self._hero.add_dexterity() def render(self): """odpowiedzialne za wyświetlanie""" if self._hero.x < 9: x_o = 0 elif self._hero.x > self._map.size[0] - 9 - 1: x_o = self._map.size[0] - 19 else: x_o = self._hero.x - 9 if self._hero.y < 9: y_o = 0 elif self._hero.y > self._map.size[1] - 9 - 1: y_o = self._map.size[1] - 19 else: y_o = self._hero.y - 9 floor_list = [ self._image_library["texture18.png"], self._image_library["texture16.png"], self._image_library["texture15.png"] ] wall = self._image_library["texture17.png"] for y in xrange(19): for x in xrange(19): pos = self._map[(x_o + x), (y_o + y)] # ściana if pos[0] == 'w': self._surface.blit(wall, (x * 32, y * 32)) # podloga elif pos[0] != '_': i = pos[0] self._surface.blit(floor_list[i % 3], (x * 32, y * 32)) # pustka else: pygame.draw.rect(self._surface, (0, 0, 0), (x * 32, y * 32, 32, 32)) # item if pos[1] is not None: for item in pos[1]: self._surface.blit(self._image_library[item.sprite], (x * 32, y * 32)) # hero if (x_o + x, y_o + y) == self._hero.position: self._surface.blit(self._image_library["hero.png"], (x * 32, y * 32)) # enemy or fountain: if pos[2] == "rf": self._surface.blit(self._image_library["redfountain.png"], (x * 32, y * 32)) elif pos[2] == "bf": self._surface.blit(self._image_library["bluefountain.png"], (x * 32, y * 32)) elif pos[2] is not None: self._surface.blit(self._image_library[pos[2].sprite], (x * 32, y * 32)) # vision if not self.check_view(x_o + x, y_o + y): self._surface.blit(self._image_library["black.png"], (x * 32, y * 32)) # volume visual self._surface.blit(self._image_library["speaker.png"], (0, 612)) light_straps = (0, 96, 0) dark_straps = (0, 32, 0) wid = 5 for strap in xrange(20): if strap < MUSIC.volume * 20: pygame.draw.rect( self._surface, light_straps, (20 + strap * wid, 650 - strap * 2, wid - 1, strap * 2)) else: pygame.draw.rect( self._surface, dark_straps, (20 + strap * wid, 650 - strap * 2, wid - 1, strap * 2)) # nadpisuje czarnym tłem pygame.draw.rect(self._surface, (0, 0, 0), (610, 0, 200, 650)) # prawa strona Auxil.do_nice_outlines(self._surface) Auxil.write(self._surface, "EQ", 22, 700, 0) Auxil.write(self._surface, "Backpack", 22, 660, 80) Auxil.write(self._surface, "Stats:", 14, 615, 240 + 20) Auxil.write(self._surface, "HP", 14, 615, 240 + 35) # +15 pix pionowo Auxil.write(self._surface, "Attack", 14, 615, 240 + 50) Auxil.write(self._surface, "Defense", 14, 615, 240 + 65) Auxil.write(self._surface, "Strength", 14, 615, 240 + 80) Auxil.write(self._surface, "Dexterity", 14, 615, 240 + 95) Auxil.write(self._surface, "Armor", 14, 615, 240 + 110) Auxil.write(self._surface, "Exp", 14, 615, 240 + 125) #,240 + 15*i) Auxil.write(self._surface, str(floor(self._hero.hp)), 14, 690, 275) Auxil.write(self._surface, str(self._hero.attack), 14, 690, 290) Auxil.write(self._surface, str(self._hero.defense), 14, 690, 305) Auxil.write(self._surface, str(self._hero.strength), 14, 690, 320) Auxil.write(self._surface, str(self._hero.dexterity), 14, 690, 335) Auxil.write(self._surface, str(self._hero.armor.durability), 14, 690, 350) Auxil.write(self._surface, str(self._hero.exp), 14, 690, 365) Auxil.write(self._surface, "Requirements:", 14, 615, 395) Auxil.write(self._surface, "Strength", 14, 615, 410) Auxil.write(self._surface, "Dexterity", 14, 615, 425) if self._marked is not None: mark = self._marked[0] + self._marked[0] * 5 back = self._hero.equipment.backpack if mark < len(back): Auxil.write(self._surface, str(back[mark]._requirements[0]), 14, 690, 410) Auxil.write(self._surface, str(back[mark]._requirements[1]), 14, 690, 425) z = 4 eq = self._hero.equipment if eq.weapon is not None: self._surface.blit(self._image_library[eq.weapon.sprite], (612 + z, 22 + z)) if eq.suit is not None: self._surface.blit(self._image_library[eq.suit.sprite], (612 + z + 40, 22 + z)) # backpack i = 0 for item in eq.backpack: self._surface.blit(self._image_library[item.sprite], (612 + z + (i % 5) * 40, 102 + z + (i / 5) * 40)) i += 1 # buttons if self._hero.skill_points > 0: for but in xrange(5): self._surface.blit(self._image_library["button.png"], (780, 275 + but * 16)) pygame.display.update() def check_view(self, x, y): """sprawdza zasieg wzroku""" view = ceil(sqrt((self._hero.x - x)**2 + (self._hero.y - y)**2)) return view <= HORIZON def load_images(self): """wczytuje sprity""" path = r"./items/" item_list = Auxil.files("items") self._image_library = {} for item in item_list: uni_path = path.replace('/', os.sep).replace('\\', os.sep) #universal path, also works: os.path.join('','') self._image_library[item] = pygame.image.load(uni_path + item)\ .convert_alpha() def player_action(self): """ Sprawdza ostatnią akcję gracza w zależności od tego czy nachodzimy atakuje lub po prostu się przemieszcza """ if self._action == 'w': action_pos = self._map[self._hero.x, self._hero.y - 1] # brak wroga if action_pos[2] is None: self._hero.change_y(-1) # atak elif action_pos[2] == "rf": self._hero.restore_hp(95) self._hero.gain_exp(100) action_pos[2] = "bf" else: print "gracz atakuje" Auxil.write(self._surface, "gracz atakuje", 14, 615, 600) result = self._hero.do_attack(action_pos[2]) if result: self._hero.gain_exp(action_pos[2].give_exp()) loot = action_pos[2].leave_items() if loot is not None: if action_pos[1] is None: action_pos[1] = [loot] else: action_pos[1].append(loot) action_pos[2] = None if self._action == 's': action_pos = self._map[self._hero.x, self._hero.y + 1] if action_pos[2] is None: self._hero.change_y(1) elif action_pos[2] == "rf": self._hero.restore_hp(95) self._hero.gain_exp(100) action_pos[2] = "bf" else: print "gracz atakuje" Auxil.write(self._surface, "gracz atakuje", 14, 615, 600) result = self._hero.do_attack(action_pos[2]) if result: self._hero.gain_exp(action_pos[2].give_exp()) loot = action_pos[2].leave_items() if loot is not None: if action_pos[1] is None: action_pos[1] = [loot] else: action_pos[1].append(loot) action_pos[2] = None if self._action == 'a': action_pos = self._map[self._hero.x - 1, self._hero.y] if action_pos[2] is None: self._hero.change_x(-1) elif action_pos[2] == "rf": self._hero.restore_hp(95) self._hero.gain_exp(100) action_pos[2] = "bf" else: print "gracz atakuje" Auxil.write(self._surface, "gracz atakuje", 14, 615, 600) result = self._hero.do_attack(action_pos[2]) if result: self._hero.gain_exp(action_pos[2].give_exp()) loot = action_pos[2].leave_items() if loot is not None: if action_pos[1] is None: action_pos[1] = [loot] else: action_pos[1].append(loot) action_pos[2] = None if self._action == 'd': action_pos = self._map[self._hero.x + 1, self._hero.y] if action_pos[2] is None: self._hero.change_x(1) elif action_pos[2] == "rf": self._hero.restore_hp(95) self._hero.gain_exp(100) action_pos[2] = "bf" else: print "gracz atakuje" Auxil.write(self._surface, "gracz atakuje", 14, 615, 600) result = self._hero.do_attack(action_pos[2]) if result: self._hero.gain_exp(action_pos[2].give_exp()) loot = action_pos[2].leave_items() if loot is not None: if action_pos[1] is None: action_pos[1] = [loot] else: action_pos[1].append(loot) action_pos[2] = None def enemy_turn(self): """ Symulacja tury przeciwników. W praktyce poruszają się tylko ci w zasięgu naszego wzroku """ enemy_list = [] # szukamy przeciwników w zasięgu wzroku hero_x = self._hero.x hero_y = self._hero.y for i in xrange(-HORIZON, HORIZON): for j in xrange(-HORIZON, HORIZON): if not (not (hero_x + i >= 0) or not (hero_x + j >= 0) or not (hero_x + i < self._map.size[0]) or not (hero_y + j < self._map.size[1]) or not (self._map[(hero_x + i), (hero_y + j)][2] is not None) or not (self._map[(hero_x + i), (hero_y + j)][2] != "rf") or not (self._map[(hero_x + i), (hero_y + j)][2] != "bf")): enemy_list.append(self._map[(hero_x + i), (hero_y + j)][2]) # to tylko tymczasowo do debugu: if len(enemy_list) > 0: # jak pusta to po co pisac? print "w poblizu mamy: ", enemy_list # ruszamy enemy for enemy in enemy_list: x_enemy, y_enemy = enemy.position x_distance = hero_x - x_enemy y_distance = hero_y - y_enemy is_moved = False # sprawdzamy czy można zaatakować i ewentualnie atakujemy: x_distance = hero_x - enemy.x y_distance = hero_y - enemy.y if abs(x_distance) == 1 and y_distance == 0 \ or x_distance == 0 and abs(y_distance) == 1: print "potwor atakuje" Auxil.write(self._surface, "potwor atakuje", 14, 615, 240 + 130) is_moved = True self._lost = enemy.do_attack(self._hero) if not is_moved: if (x_distance > 1 or (x_distance == 1 and abs(y_distance) == 1))\ and self._map[x_enemy+1, y_enemy][2] is None\ and self._map[x_enemy+1, y_enemy][0] != 'w'\ and self._map[x_enemy+1, y_enemy][0] != '_': enemy.change_position((x_enemy + 1, y_enemy)) self._map[x_enemy, y_enemy][2] = None self._map[x_enemy + 1, y_enemy][2] = enemy is_moved = True elif (x_distance < -1 or (x_distance == -1 and abs(y_distance) == 1))\ and self._map[x_enemy-1, y_enemy][2] is None\ and self._map[x_enemy-1, y_enemy][0] != 'w'\ and self._map[x_enemy-1, y_enemy][0] != '_': enemy.change_position((x_enemy - 1, y_enemy)) self._map[x_enemy, y_enemy][2] = None self._map[x_enemy - 1, y_enemy][2] = enemy is_moved = True if not is_moved: if (y_distance > 1 or (y_distance == 1 and abs(x_distance) == 1))\ and self._map[x_enemy, y_enemy+1][2] is None\ and self._map[x_enemy, y_enemy+1][0] != 'w'\ and self._map[x_enemy, y_enemy+1][0] != '_': enemy.change_position((x_enemy, y_enemy + 1)) self._map[x_enemy, y_enemy][2] = None self._map[x_enemy, y_enemy + 1][2] = enemy is_moved = True elif (y_distance < -1 or (y_distance == -1 and abs(x_distance) == 1))\ and self._map[x_enemy, y_enemy-1][2] is None\ and self._map[x_enemy, y_enemy-1][0] != 'w'\ and self._map[x_enemy, y_enemy-1][0] != '_': enemy.change_position((x_enemy, y_enemy - 1)) self._map[x_enemy, y_enemy][2] = None self._map[x_enemy, y_enemy - 1][2] = enemy is_moved = True self._player_turn = True def get_start_position(self): """Zwraca prawidłową, losową pozycję startową dla naszego bohatera""" map_size = self._map.size x = randint(0, map_size[0] - 1) y = randint(0, map_size[1] - 1) while self._map[x, y][0] == 'w' \ or self._map[x, y][0] == '_' \ or self._map[x, y][2] is not None: x = randint(0, map_size[0] - 1) y = randint(0, map_size[1] - 1) return x, y
def main(): root = Tk() root.title("Tom's wanderer game") canvas = Canvas(root, width=600, height=600) # importing pictures hero_down = PhotoImage(file="images/hero-down.png") hero_up = PhotoImage(file="images/hero-up.png") hero_left = PhotoImage(file="images/hero-left.png") hero_right = PhotoImage(file="images/hero-right.png") #instasiating objects hero = Hero(0, 0, hero_down) game = Game(hero) # function that can be called when a key pressing happens m = Utils.matrix def on_key_press(e): def coords(char): x, y = char.get_coordinates() x, y = int(x / 60), int(y / 60) return x, y try: if e.keycode == 83 and m[coords(hero)[1] + 1][coords( hero)[0]] != 1 and coords(hero)[1] <= 9: #down hero.set_coordinatesY(60) hero.set_image(hero_down) elif e.keycode == 87 and m[coords(hero)[1] - 1][coords( hero)[0]] != 1 and coords(hero)[1] > 0: #up hero.set_coordinatesY(-60) hero.set_image(hero_up) elif e.keycode == 65 and m[coords(hero)[1]][ coords(hero)[0] - 1] != 1 and coords(hero)[0] > 0: #left hero.set_coordinatesX(-60) hero.set_image(hero_left) elif e.keycode == 68 and m[coords(hero)[1]][ coords(hero)[0] + 1] != 1 and coords(hero)[0] <= 9: #right hero.set_coordinatesX(60) hero.set_image(hero_right) except (IndexError): pass #exit if e.keycode == 27: root.destroy() #battle opponent = False for char in game.get_characters(): if e.keycode == 32 and coords(hero) == coords(char): opponent = hero.battle(char) if opponent: game.remove_character(opponent) #initialise new game object and level up characters if game.get_char_length() < 1: new_level() game.create_monsters() game.level_up_chars(hero.level) hero.x = 0 hero.y = 0 hero.set_image(hero_down) canvas.delete("all") stats() draw_canvas() # binding key press events canvas.bind("<KeyPress>", on_key_press) canvas.pack() # draw the canvas def draw_canvas(): game.draw(canvas) game.draw_character(canvas) hero.draw_character(canvas) draw_canvas() canvas.focus_set() #game stats canvas2 = Canvas(root, width=600, height=30) def stats(): canvas2.create_rectangle(0, 0, 600, 30, fill="grey") text = f"Hero (Level: {hero.level}) HP: {int(hero.HP)}/38 | DP: {hero.DP} | SP: {hero.SP}" canvas_text = canvas2.create_text(10, 10, text=text, font=('freemono bold', 11), anchor=NW) canvas2.pack() #level up function def new_level(): hero.level_up() chance = random.random() if chance <= 0.1: hero.set_HP = hero.maxHP if 0.1 < chance <= 0.4: hero.set_HP = hero.maxHP / 3 if chance >= 0.5: hero.set_HP = hero.maxHP * 0.1 root.mainloop()
def create_hero(): print('A quest has emerged and a new hero must answer the call. Who will answer the challenge and will they rise to glory or end in defeat.') return Hero(100, 5)