Exemple #1
0
 def test_two_living_sides(self):
     joe = Player("Joe")
     darf = Mob("Darf")
     self.assertTrue(two_sides([joe, darf]))
     joe.take_damage(150)
     self.assertFalse(joe.is_alive)
     self.assertFalse(two_sides(living_fighters([joe, darf])))
Exemple #2
0
def game_loop():

    contestants = [
        Player('Rick', 100),
        Player('Morty', 10),
        Player('Summer', 25),
        Player('Beth', 50),
        Player('Jerry', 3),
        Alien('Amish Cyborg', 40, 2)
    ]

    print('The contestants are {}'.format(contestants))

    print('The battle begins...')
    while len(contestants) > 1:
        p1 = random.choice(contestants)
        p2 = random.choice(contestants)

        print('{} attacks {}'.format(p1, p2))

        if p1.attack() > p2.defense():
            print('{} is defeated'.format(p2))
            contestants.remove(p2)
        else:
            print('{} blocks'.format(p2))

    winner = contestants[0]

    print('{} wins the battle'.format(winner))
Exemple #3
0
    def __init__(self, win, net, username):
        self.menu = False
        self.grid = False
        self.win = win
        self.net = net

        #generate and save map
        # new_map = Map()
        # new_map.generate_map('random', False)

        self.bg = pygame.image.load('sprites/background.jpg').convert()

        #load first shuffled map from server
        self.current_map = 0
        Map.load(self.net.maps[self.current_map])

        #create client player object and assign colour based on ID, username from input, map from server
        self.ash = Player(
            RandomNode(Map.nodes).node, self.net.playerID, username,
            self.current_map)

        #other player objects
        p2, p3, p4, p5 = None, None, None, None
        self.players = [p2, p3, p4, p5]

        self.bikes = [Bike() for i in range(config.bikes)]
        self.mushrooms = [Mushroom() for i in range(config.mushrooms)]

        WeaponStatus.set_locations(self.bikes, self.mushrooms)

        music = pygame.mixer.music.load(config.theme)
        pygame.mixer.music.set_volume(0.5)
        pygame.mixer.music.play(-1)

        self.ash.ID = self.net.playerID
Exemple #4
0
    def test_rifle(self):
        # setup
        player = Player("joe")
        monster = Mob("darf")
        starting_monster_hp = monster.hp

        # player shoots monster with rifle
        player.perform_attack(attacks['rifle'], [monster])

        # assert the monster was hit and the weapon must cooldown
        self.assertEqual(monster.hp, starting_monster_hp - attacks['rifle']['damage'])
        self.assertNotIn('rifle', player.available_attacks)
Exemple #5
0
    def test_grenade(self):
        # setup
        player = Player("joe")
        monster1 = Mob("darf")
        starting_monster1_hp = monster1.hp
        monster2 = Mob("weebo")
        starting_monster2_hp = monster2.hp

        # player throws grenade at 2 monsters
        player.perform_attack(attacks['grenade'], [monster1, monster2])

        # assert both monsters were hit and the weapon must cooldown
        self.assertEqual(monster1.hp, starting_monster1_hp - attacks['grenade']['damage'])
        self.assertEqual(monster2.hp, starting_monster2_hp - attacks['grenade']['damage'])
        self.assertNotIn('grenade', player.available_attacks)
Exemple #6
0
 def add_character(self,map,sprite,pos,direction):
     p = Player()
     p.map = map
     p.pos = pos
     p.load(sprite)
     getattr(p,direction)()
     p.idle()
     self.add(p)
     return p
Exemple #7
0
def play():
    skeleton = Monster('Skeleton', 50, 10, 0)
    player = Player()

    skeleton.attack(player)
    player.attack(skeleton)
    player.attack(skeleton)
    player.attack(skeleton)
    player.attack(skeleton)
Exemple #8
0
def create_player():

    # create player
    decision = input("Create a new player? YES/NO").lower()
    if decision == 'yes':
        new_player = Player.Player()
        new_player.generate_character()
        # player.type_name()
        new_player.generate_name()
        new_player.generate_equipment()
        print(new_player)
        return new_player
    elif decision == 'no':
        print("No player, no game!")
        return False
    else:
        create_player()
Exemple #9
0
    #    json1_str = json1_file.read()
    #    json1_data = json.loads(json1_str)

    data_file = open("testmap.py")
    data_str = data_file.read()
    #
    game_manager = Manager()

    # list of vars filled by exec
    data = None
    start = None
    exec(data_str)

    game_manager.hack_map(data, start)

    game_manager.player = Player()

    # only use this when not hacking
    # game_manager.make_map(json1_data)

    print(
        """You wake up, badly bruised, freezing and with barely enough energy to move. 
Getting up, you inspect your surroundings...""")

    # debug
    # print(game_manager.location.name)
    last_command = None

    while True:
        # enemies only attack after a non-inspect action
        if not (last_command is None or last_command.root == "inspect"):
Exemple #10
0
### Let's Game to be started ###

################################

pg.init()
pg.display.set_caption('Hello pygame')
mainScreen = pg.display.set_mode((WIDTH, HEIGHT))
clock = pg.time.Clock()
imge = pg.image.load(os.path.join(IMG_FOLDER,
                                  'colored_packed.png')).convert_alpha()
imgKit = []
for i in range(22):
    for j in range(48):
        imgKit.append(imge.subsurface(j * 16, i * 16, 16, 16))

player1 = Player(16, 16, imgKit[25])

brickRectsList = []
bricksList = []
wallGroup, prixGroup, enemyGroup = worldCreate(levels[0])

# Цикл игры
game = True
while game:
    # Keep tempo
    clock.tick(FPS)
    # check for events
    for e in pg.event.get():
        # check for closing window
        if e.type == pg.QUIT or (e.type == pg.KEYDOWN
                                 and e.key == pg.K_ESCAPE):
Exemple #11
0
import random
from card_book import Card, Deck
from characters import Player
from actions import deal, game_on, dealer_on
from actions import bank

# GAME LOGIC STARTS HERE

Player1 = Player(input("Enter you Name:\n"))
Dealer1 = Player('Dealer')
champ = True

# player_turn = game_on(Player1)
# dealer_turn = Dealer1.current_hand[0].value + Dealer1.current_hand[1].value

game_turns = 0
while True:
    if game_turns == 0:
        Current_Bank = bank(
            int(input("How much would you like to play with? \n")))
        print(f"{Player1.name} is entering the game with ${Current_Bank}\n")

    while True:
        print(deal(Player1, Dealer1))
        bet = int(input("What is your bet for this hand?\n"))
        if bet > Current_Bank:
            print("Insufficient Amount, Please enter new amount to bet!")
            bet = int(input("What is your bet for this hand?\n"))
        player_turn = game_on(Player1, Dealer1)
        dealer_hand = Dealer1.current_hand[0].value + Dealer1.current_hand[
            1].value
Exemple #12
0
fpsClock = pygame.time.Clock()
# programIcon = pygame.image.load(icon_img)
background = pygame.transform.scale(pygame.image.load(background_img),
                                    (990, 660))
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))

pygame.display.set_caption("Zoe Town")
# pygame.display.set_icon(programIcon)
# loot_sound = pygame.mixer.Sound("crash.wav")

# score
base_font = pygame.font.Font(None, 32)
color = pygame.Color("orange")

# Initializing sprites and loot
player = Player(player_img)
gem1 = Gem(gems[0], screen)
gem2 = Gem(gems[1], screen)
villain = Villain(monster_img)

# Initializing joystick
try:
    joystick = pygame.joystick.Joystick(0)
    joystick.init()
except:
    print("no joystick")

# setting up game loop
running = True

while running:
Exemple #13
0
        for pig, skill in choice_dict.items():
            result += f"-- {pig} with a skill: {skill.name}\n"
    else:
        for pig, skill in choice_dict.items():
            result += f"-- {pig}: {skill}\n"
    return result


player_name = input("What is your name? \n>> ")
print(f"Yo {player_name}! \n")

chosen_skills = player_type_choice()

# Create player
player = Player(name=player_name,
                hp=[30, 30],
                dmg=[5, 15],
                skills=chosen_skills)

# Play game
while True:
    play_or_stats = input("If you want check your stats type 'stats'. \
Otherwise type 'play'\n>> ")
    if play_or_stats.lower() == "stats":
        player.get_stats()
        print(MONSTERS_DICT)
    elif play_or_stats.lower() == "play":
        event = create_random_event(player, BATTLE_DESCRIPTS, MONSTERS_DICT,
                                    OTHER_EVENTS)
        if not event:
            player.get_stats()
            exit("You won the game!")  # Futureproofing
    def setup(self):
        if G.SINGLEPLAYER:
            try:
                # TODO: create world menu
                G.SAVE_FILENAME = "world"
                start_server(internal=True)
                sock = socket.socket()
                time.sleep(2)
                sock.connect(("localhost", 1486))
            except socket.error as e:
                #Otherwise back to the main menu we go
                return False
            except Exception as e:
                import traceback
                traceback.print_exc()
                return False
        else:
            try:
                #Make sure the address they want to connect to works
                ipport = G.IP_ADDRESS.split(":")
                if len(ipport) == 1: ipport.append(1486)
                sock = socket.socket()
                sock.connect((tuple(ipport)))
            except socket.error as e:
                #Otherwise back to the main menu we go
                return False
        self.init_gl()

        self.debug_text = TextWidget(self.window, 'Loading information...',
                                     0, self.window.height - 300,
                                     500, 300,
                                     visible=True, multi_line=True, readonly=True,
                                     font_name='Arial', font_size=8,
                                     text_color=(255, 255, 255, 255),
                                     background_color=(0, 0, 0, 0))
        self.debug_text.write_escape("$$r")

        sky_rotation = -20.0  # -20.0

        # TERRAIN_CHOICE = self.biome_generator.get_biome_type(sector[0], sector[2])
        default_skybox = 'skydome.jpg'
        # if TERRAIN_CHOICE == G.NETHER:
        #     default_skybox = 'skydome_nether.jpg'
        # else:
        #     default_skybox = 'skybox.jpg'

        self.skydome = Skydome(
            'resources/' + default_skybox,
            #'resources/skydome.jpg',
            0.7,
            100.0,
            sky_rotation,
        )

        self.player_ids = {}  # Dict of all players this session, indexes are their ID's [0: first Player on server,]

        self.focus_block = Block(width=1.05, height=1.05)
        self.earth = vec(0.8, 0.8, 0.8, 1.0)
        self.white = vec(1.0, 1.0, 1.0, 1.0)
        self.polished = GLfloat(100.0)
        self.crack_batch = pyglet.graphics.Batch()

        # if G.DISABLE_SAVE and world_exists(G.game_dir, G.SAVE_FILENAME):
        #     open_world(self, G.game_dir, G.SAVE_FILENAME)

        self.world = World()
        self.packetreceiver = PacketReceiver(self.world, self, sock)
        self.world.packetreceiver = self.packetreceiver
        G.CLIENT = self.packetreceiver
        self.packetreceiver.start()

        #Get our position from the server
        self.packetreceiver.request_spawnpos()
        #Since we don't know it yet, lets disable self.update, or we'll load the wrong chunks and fall
        self.update_disabled = self.update
        self.update = lambda dt: None
        #We'll re-enable it when the server tells us where we should be

        self.player = Player(game_mode=G.GAME_MODE)
        self.item_list = ItemSelector(self, self.player, self.world)
        self.inventory_list = InventorySelector(self, self.player, self.world)
        self.item_list.on_resize(self.window.width, self.window.height)
        self.inventory_list.on_resize(self.window.width, self.window.height)
        self.text_input = TextWidget(self.window, '',
                                     0, 0,
                                     self.window.width,
                                     visible=False,
                                     font_name=G.CHAT_FONT)
        self.text_input.push_handlers(on_toggled=self.on_text_input_toggled, key_released=self.text_input_callback)
        self.chat_box = TextWidget(self.window, '',
                                   0, self.text_input.y + self.text_input.height + 50,
                                   self.window.width // 2, height=min(300, self.window.height // 3),
                                   visible=False, multi_line=True, readonly=True,
                                   font_name=G.CHAT_FONT,
                                   text_color=(255, 255, 255, 255),
                                   background_color=(0, 0, 0, 100),
                                   enable_escape=True)
        self.camera = Camera3D(target=self.player)

        if G.HUD_ENABLED:
            self.label = pyglet.text.Label(
                '', font_name='Arial', font_size=8, x=10, y=self.window.height - 10,
                anchor_x='left', anchor_y='top', color=(255, 255, 255, 255))

        self.debug_text.write_escape("$$D")

        pyglet.clock.schedule_interval_soft(self.world.process_queue,
                                            1.0 / G.MAX_FPS)
        pyglet.clock.schedule_interval_soft(self.world.hide_sectors, 10.0, self.player)
        return True
Exemple #15
0
from Magic import Spell
from Map import *
from Menu import Menu
from characters import Player
from inventory import *


def gen_spells():  # generates the spells from txt file and put them in list, to be used by player
    filepath = 'spells.txt'
    file = open(filepath, "r")
    for line in file:
        split = line.split(";")
        spellss.append(Spell(split[0], split[1], split[2], int(split[3])))


player = Player()
map = Map()  # the map for the game
mobkilled = 0
menu = Menu()  # the menu
game_on = False
spellss = []  # contains all the spells
gen_spells()
inv = Inventory()
inv.god_inventory()
# player.inventory = inv           #cheat, gives player all items in the game
# player.equiped[2] = inv.items[len(inv.items -1 )]    #  gives player the cheat item

for i in range(len(spellss)):  # for now, the player starts with all the spellss
    player.spells.append(spellss[i])

Exemple #16
0
    def get_player_data(ash, net, players, bikes, mushrooms):
        '''get player data from server and map data to local player objects'''
        attrs = net.send(ash.attributes())  #return attributes of other players

        for i in range(len(players)):
            '''ith player should map to ith attribute on server as players are
				added in order which clients connect. If client DCs and reconnects, they are
				issued the same player id'''
            a = attrs[i]

            #create new player instance if:
            #1) we haven't already created an instance
            #2) they have an ID (they are connected to server)
            if not players[i] and a['ID'] != None:
                print(f'{a["username"]} connected.')
                players[i] = Player((a['x'], a['y']), a['ID'])

            #update (in place) the ith player from server
            elif players[i]:
                players[i].x, players[i].y = a['x'], a['y']
                players[i].left, players[i].right, players[i].up, players[
                    i].down = a['L'], a['R'], a['U'], a['D']
                players[i].standing, players[i].walk_count = a['standing'], a[
                    'walk count']
                players[i].hit_slow, players[i].bike, players[i].mushroom = a[
                    'hit slow'], a['bike'], a['mushroom']
                players[i].inventory = a['inventory']
                players[i].stats = a['stats']
                players[i].killed = a['killed']
                players[i].dead = a['dead']
                players[i].ID = a['ID']
                players[i].username = a['username']
                players[i].map = a['map']

                #change local map if the host has changed the map
                if players[i].ID == 0 and players[i].map != ash.map:
                    ash.map = players[i].map
                    Map.load(net.maps[players[i].map])
                    WeaponStatus.set_locations(bikes, mushrooms)
Exemple #17
0
def _create_player(name, curr_pos):
  """Generates a Player object for the user to move around
  """
  return Player(name=name, curr_pos=curr_pos)
class GameController(Controller):
    def __init__(self, window):
        super(GameController, self).__init__(window)
        self.sector, self.highlighted_block, self.crack, self.last_key = (None,) * 4
        self.bg_red, self.bg_green, self.bg_blue = (0.0,) * 3
        self.mouse_pressed, self.sorted = (False,) * 2
        self.block_damage = 0
        self.time_of_day = 6.0

        self.back_to_main_menu = threading.Event()


    def update(self, dt):
        if self.back_to_main_menu.isSet():
            self.switch_controller_class(MainMenuController)
            return
        self.update_sector(dt)
        self.update_player(dt)
        self.update_mouse(dt)
        self.update_time(dt)
        self.camera.update(dt)

    def update_sector(self, dt):
        sector = sectorize(self.player.position)
        if sector != self.sector:
            self.world.change_sectors(sector)
            # When the world is loaded, show every visible sector.
            if self.sector is None:
                self.world.process_entire_queue()
            self.sector = sector

    def update_player(self, dt):
        m = 8
        df = min(dt, 0.2)
        for _ in range(m):
            self.player.update(df / m, self)
        for ply in self.player_ids.values():
            for _ in range(m):
                ply.update(df / m, self)
        momentum = self.player.get_motion_vector(15 if self.player.flying else 5*self.player.current_density)
        if momentum != self.player.momentum_previous:
            self.player.momentum_previous = momentum
            self.packetreceiver.send_movement(momentum, self.player.position)


    def update_mouse(self, dt):
        if self.mouse_pressed:
            vector = self.player.get_sight_vector()
            block, previous = self.world.hit_test(self.player.position, vector,
                                                  self.player.attack_range)
            self.set_highlighted_block(block)

            if self.highlighted_block:
                hit_block = self.world[self.highlighted_block]
                if hit_block.hardness >= 0:
                    self.update_block_damage(dt, hit_block)
                    self.update_block_remove(dt, hit_block)

    def update_block_damage(self, dt, hit_block):
        multiplier = 1
        current_item = self.item_list.get_current_block()
        if current_item is not None:
            if isinstance(current_item, Tool):  # tool
                if current_item.tool_type == hit_block.digging_tool:
                    multiplier = current_item.multiplier

        self.block_damage += self.player.attack_power * dt * multiplier

    def update_block_remove(self, dt, hit_block):
        if self.block_damage >= hit_block.hardness:
            self.world.remove_block(self.player,
                                    self.highlighted_block)
            self.set_highlighted_block(None)
            if getattr(self.item_list.get_current_block_item(), 'durability', -1) != -1:
                self.item_list.get_current_block_item().durability -= 1
                if self.item_list.get_current_block_item().durability <= 0:
                    self.item_list.remove_current_block()
                    self.item_list.update_items()
            if hit_block.drop_id is None:
                return
            if type(hit_block.drop_id) == list:
                for index, item in enumerate(hit_block.drop_id):
                    if not self.player.add_item(item, quantity=hit_block.drop_quantity[index]):
                        return
            elif not self.player.add_item(hit_block.drop_id, quantity=hit_block.drop_quantity):
                    return
            self.item_list.update_items()
            self.inventory_list.update_items()

    def init_gl(self):
        glEnable(GL_ALPHA_TEST)
        glAlphaFunc(GL_GREATER, 0.1)
        glEnable(GL_COLOR_MATERIAL)
        glEnable(GL_BLEND)

        glEnable(GL_LINE_SMOOTH)
        glHint(GL_LINE_SMOOTH_HINT, GL_NICEST)
        glEnable(GL_POLYGON_SMOOTH)
        glHint(GL_POLYGON_SMOOTH_HINT, GL_NICEST)

        # glClampColorARB(GL_CLAMP_VERTEX_COLOR_ARB, GL_FALSE)
        # glClampColorARB(GL_CLAMP_FRAGMENT_COLOR_ARB, GL_FALSE)
        # glClampColorARB(GL_CLAMP_READ_COLOR_ARB, GL_FALSE)

        # glClearColor(0, 0, 0, 0)
        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)

    def setup(self):
        if G.SINGLEPLAYER:
            try:
                # TODO: create world menu
                G.SAVE_FILENAME = "world"
                start_server(internal=True)
                sock = socket.socket()
                time.sleep(2)
                sock.connect(("localhost", 1486))
            except socket.error as e:
                #Otherwise back to the main menu we go
                return False
            except Exception as e:
                import traceback
                traceback.print_exc()
                return False
        else:
            try:
                #Make sure the address they want to connect to works
                ipport = G.IP_ADDRESS.split(":")
                if len(ipport) == 1: ipport.append(1486)
                sock = socket.socket()
                sock.connect((tuple(ipport)))
            except socket.error as e:
                #Otherwise back to the main menu we go
                return False
        self.init_gl()

        self.debug_text = TextWidget(self.window, 'Loading information...',
                                     0, self.window.height - 300,
                                     500, 300,
                                     visible=True, multi_line=True, readonly=True,
                                     font_name='Arial', font_size=8,
                                     text_color=(255, 255, 255, 255),
                                     background_color=(0, 0, 0, 0))
        self.debug_text.write_escape("$$r")

        sky_rotation = -20.0  # -20.0

        # TERRAIN_CHOICE = self.biome_generator.get_biome_type(sector[0], sector[2])
        default_skybox = 'skydome.jpg'
        # if TERRAIN_CHOICE == G.NETHER:
        #     default_skybox = 'skydome_nether.jpg'
        # else:
        #     default_skybox = 'skybox.jpg'

        self.skydome = Skydome(
            'resources/' + default_skybox,
            #'resources/skydome.jpg',
            0.7,
            100.0,
            sky_rotation,
        )

        self.player_ids = {}  # Dict of all players this session, indexes are their ID's [0: first Player on server,]

        self.focus_block = Block(width=1.05, height=1.05)
        self.earth = vec(0.8, 0.8, 0.8, 1.0)
        self.white = vec(1.0, 1.0, 1.0, 1.0)
        self.polished = GLfloat(100.0)
        self.crack_batch = pyglet.graphics.Batch()

        # if G.DISABLE_SAVE and world_exists(G.game_dir, G.SAVE_FILENAME):
        #     open_world(self, G.game_dir, G.SAVE_FILENAME)

        self.world = World()
        self.packetreceiver = PacketReceiver(self.world, self, sock)
        self.world.packetreceiver = self.packetreceiver
        G.CLIENT = self.packetreceiver
        self.packetreceiver.start()

        #Get our position from the server
        self.packetreceiver.request_spawnpos()
        #Since we don't know it yet, lets disable self.update, or we'll load the wrong chunks and fall
        self.update_disabled = self.update
        self.update = lambda dt: None
        #We'll re-enable it when the server tells us where we should be

        self.player = Player(game_mode=G.GAME_MODE)
        self.item_list = ItemSelector(self, self.player, self.world)
        self.inventory_list = InventorySelector(self, self.player, self.world)
        self.item_list.on_resize(self.window.width, self.window.height)
        self.inventory_list.on_resize(self.window.width, self.window.height)
        self.text_input = TextWidget(self.window, '',
                                     0, 0,
                                     self.window.width,
                                     visible=False,
                                     font_name=G.CHAT_FONT)
        self.text_input.push_handlers(on_toggled=self.on_text_input_toggled, key_released=self.text_input_callback)
        self.chat_box = TextWidget(self.window, '',
                                   0, self.text_input.y + self.text_input.height + 50,
                                   self.window.width // 2, height=min(300, self.window.height // 3),
                                   visible=False, multi_line=True, readonly=True,
                                   font_name=G.CHAT_FONT,
                                   text_color=(255, 255, 255, 255),
                                   background_color=(0, 0, 0, 100),
                                   enable_escape=True)
        self.camera = Camera3D(target=self.player)

        if G.HUD_ENABLED:
            self.label = pyglet.text.Label(
                '', font_name='Arial', font_size=8, x=10, y=self.window.height - 10,
                anchor_x='left', anchor_y='top', color=(255, 255, 255, 255))

        self.debug_text.write_escape("$$D")

        pyglet.clock.schedule_interval_soft(self.world.process_queue,
                                            1.0 / G.MAX_FPS)
        pyglet.clock.schedule_interval_soft(self.world.hide_sectors, 10.0, self.player)
        return True

    def update_time(self, dt: float):
        self.time_of_day += dt * 24.0 / G.TIME_RATE
        if self.time_of_day > 24.0:
           self.time_of_day = 0.0

        # Calculate sky colour according to time of day.
        sin_t = sin(pi * (((self.time_of_day / 12.0) + 1) % 2 - 1))
        self.bg_red = 0.1 * (1.0 - sin_t)
        self.bg_green = 0.9 * sin_t
        self.bg_blue = min(sin_t + 0.4, 0.8)

        self.skydome.update_time_of_day(self.time_of_day)

    def set_highlighted_block(self, block):
        if self.highlighted_block == block:
            return
        self.highlighted_block = block
        self.block_damage = 0
        if self.crack:
            self.crack.delete()
        self.crack = None

    def on_mouse_press(self, x, y, button, modifiers):
        if self.window.exclusive:
            vector = self.player.get_sight_vector()
            block, previous = self.world.hit_test(self.player.position, vector, self.player.attack_range)
            if button == pyglet.window.mouse.LEFT:
                self.on_mouse_press_left(block, x, y, button, modifiers)
            else:
                self.on_mouse_press_right(block, previous, x, y, button, modifiers)
        else:
            self.window.set_exclusive_mouse(True)

    def on_mouse_press_left(self, block, x, y, button, modifiers):
        if block:
            self.mouse_pressed = True
            self.set_highlighted_block(None)

    def on_mouse_press_right(self, block, previous, x, y, button, modifiers):
        if previous:
            hit_block = self.world[block]
            if hit_block.id == craft_block.id:
                self.inventory_list.switch_mode(1)
                self.inventory_list.toggle(False)
            elif hit_block.id == furnace_block.id:
                self.inventory_list.switch_mode(2)
                self.inventory_list.set_furnace(hit_block)
                self.inventory_list.toggle(False)
            elif hit_block.density >= 1:
               self.place_block(previous)
        elif self.item_list.get_current_block() and getattr(self.item_list.get_current_block(), 'regenerated_health', 0) != 0 and self.player.health < self.player.max_health:
            self.eat_food()

    def place_block(self, previous):
        current_block = self.item_list.get_current_block()
        if current_block is not None:
            if current_block.id.is_item():
                if current_block.on_right_click(self.world, self.player):
                    self.item_list.get_current_block_item().change_amount(-1)
                    self.item_list.update_health()
                    self.item_list.update_items()
            else:
                localx, localy, localz = map(operator.sub,previous,normalize(self.player.position))
                if localx != 0 or localz != 0 or (localy != 0 and localy != -1):
                    self.world.add_block(previous, current_block)
                    self.item_list.remove_current_block()

    def eat_food(self):
        self.player.change_health(self.item_list.get_current_block().regenerated_health)
        self.item_list.get_current_block_item().change_amount(-1)
        self.item_list.update_health()
        self.item_list.update_items()

    def on_mouse_release(self, x, y, button, modifiers):
        if self.window.exclusive:
            self.set_highlighted_block(None)
            self.mouse_pressed = False

    def on_mouse_motion(self, x, y, dx, dy):
        if self.window.exclusive:
            m = 0.15
            x, y = self.player.rotation
            x, y = x + dx * m, y + dy * m
            y = max(-90, min(90, y))
            self.player.rotation = (x, y)
            self.camera.rotate(x, y)

    def on_mouse_drag(self, x, y, dx, dy, button, modifiers):
        if button == pyglet.window.mouse.LEFT:
            self.on_mouse_motion(x, y, dx, dy)

    def on_key_press(self, symbol, modifiers):
        if symbol == G.TOGGLE_HUD_KEY:
            G.HUD_ENABLED = not G.HUD_ENABLED
        if symbol == G.TOGGLE_DEBUG_TEXT_KEY:
            self.debug_text.visible = not self.debug_text.visible
            self.debug_text.delete()
        elif symbol == G.INVENTORY_SORT_KEY:
            if self.last_key == symbol and not self.sorted:
                self.player.quick_slots.sort()
                self.player.inventory.sort()
                self.sorted = True
            else:
                self.player.quick_slots.change_sort_mode()
                self.player.inventory.change_sort_mode()
                self.item_list.update_items()
                self.inventory_list.update_items()
        elif symbol == G.INVENTORY_KEY:
            self.set_highlighted_block(None)
            self.mouse_pressed = False
            self.inventory_list.toggle()
        elif symbol == G.SOUND_UP_KEY:
            G.EFFECT_VOLUME = min(G.EFFECT_VOLUME + .1, 1)
        elif symbol == G.SOUND_DOWN_KEY:
            G.EFFECT_VOLUME = max(G.EFFECT_VOLUME - .1, 0)
        elif symbol == G.SCREENCAP_KEY:  # dedicated screencap key
            now = datetime.datetime.now()
            dt = datetime.datetime(now.year, now.month, now.day, now.hour, now.minute, now.second)
            st = dt.strftime('%Y-%m-%d_%H.%M.%S')
            filename = str(st) + '.png'
            if not os.path.exists('screencaptures'):
                os.makedirs('screencaptures')
            path = 'screencaptures/' + filename
            pyglet.image.get_buffer_manager().get_color_buffer().save(path)
        elif symbol == G.SHOWMAP_KEY:
            self.show_map()
        elif symbol == G.QUIT_KEY:
            self.back_to_main_menu.set()
            savingsystem.save_quit_world(G.SERVER)
            self.window.set_exclusive_mouse(False)
        self.last_key = symbol

    def on_key_release(self, symbol, modifiers):
        if symbol == G.TALK_KEY:
            self.toggle_text_input()
            return pyglet.event.EVENT_HANDLED

    def on_resize(self, width, height):
        if G.HUD_ENABLED:
            self.label.y = height - 10
        self.text_input.resize(x=0, y=0, width=self.window.width)
        self.chat_box.resize(x=0, y=self.text_input.y + self.text_input.height + 50,
                             width=self.window.width // 2, height=min(300, self.window.height // 3))
        self.debug_text.resize(0, self.window.height - 300,
                                   500, 300)

    def set_3d(self):
        width, height = self.window.get_size()
        glEnable(GL_DEPTH_TEST)
        glViewport(0, 0, width, height)
        glMatrixMode(GL_PROJECTION)
        glLoadIdentity()
        gluPerspective(G.FOV, width / float(height),
                       G.NEAR_CLIP_DISTANCE,
                       G.FAR_CLIP_DISTANCE)
        glMatrixMode(GL_MODELVIEW)
        glLoadIdentity()
        glPushMatrix()
        self.camera.look()
        self.skydome.draw()
        glPopMatrix()
        self.camera.transform()

    def clear(self):
        glClearColor(self.bg_red, self.bg_green, self.bg_blue, 1.0)
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

    def on_draw(self):
        self.clear()
        #self.window.clear()
        self.set_3d()
        self.world.batch.draw()
        self.world.transparency_batch.draw()
        glEnable(GL_BLEND)
        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
        self.crack_batch.draw()
        glDisable(GL_BLEND)
        self.draw_focused_block()
        for ply in self.player_ids.values():
            ply.model.draw()
        self.set_2d()
        if G.HUD_ENABLED:
            self.item_list.draw()
            self.inventory_list.draw()
        self.update_label()
        self.debug_text.draw()
        self.text_input.draw()
        glEnable(GL_BLEND)
        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
        self.chat_box.draw()
        glDisable(GL_BLEND)

    def show_cracks(self, hit_block, vertex_data):
        if self.block_damage:  # also show the cracks
            crack_level = int(CRACK_LEVELS * self.block_damage
                              // hit_block.hardness)  # range: [0, CRACK_LEVELS]
            if crack_level >= CRACK_LEVELS:
                return
            texture_data = crack_textures.texture_data[crack_level]
            count = len(texture_data) // 2
            if self.crack:
                self.crack.delete()
            self.crack = self.crack_batch.add(count, GL_QUADS, crack_textures.group,
                                              ('v3f/static', vertex_data),
                                              ('t2f/static', texture_data))

    def draw_focused_block(self):
        glDisable(GL_LIGHTING)
        vector = self.player.get_sight_vector()
        position = self.world.hit_test(self.player.position, vector, self.player.attack_range)[0]
        if position:
            hit_block = self.world[position]
            if hit_block.density >= 1:
                self.focus_block.width = hit_block.width * 1.05
                self.focus_block.height = hit_block.height * 1.05
                vertex_data = self.focus_block.get_vertices(*position)

                if hit_block.hardness > 0.0:
                    self.show_cracks(hit_block, vertex_data)

                glEnable(GL_BLEND)
                glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
                glColor4f(0.0, 0.0, 0.0, 0.4)
                glLineWidth(2.0)
                glDisable(GL_TEXTURE_2D)
                glDepthMask(False)

                glPolygonMode(GL_FRONT_AND_BACK, GL_LINE)
                pyglet.graphics.draw(24, GL_QUADS, ('v3f/static', vertex_data))
                glPolygonMode(GL_FRONT_AND_BACK, GL_FILL)

                glDepthMask(True)
                glEnable(GL_TEXTURE_2D)
                glDisable(GL_BLEND)

    def update_label(self):
        x, y, z = self.player.position
        self.debug_text.clear()
        self.debug_text.write_line(' '.join((G.APP_NAME, str(G.APP_VERSION))))
        self.debug_text.write_line('FPS:%02d Blocks Shown: %d / %d sector_packets:%d' \
                                   % (pyglet.clock.get_fps(),len(self.world._shown),len(self.world),
                                      len(self.world.sector_packets)))
        self.debug_text.write_line('x: %.2f, chunk: %d' %(x, x // G.SECTOR_SIZE))
        self.debug_text.write_line('y: %.2f, chunk: %d' %(y, y // G.SECTOR_SIZE))
        self.debug_text.write_line('z: %.2f, chunk: %d' %(z, z // G.SECTOR_SIZE))
        dirs = ['East', 'South', 'West', 'North']
        vec, direction, angle = self.player.get_sight_direction()
        dx, dy, dz = vec
        self.debug_text.write_line('Direction: (%.2f, %.2f, %.2f) %d(%s) %.2f' % (dx, dy, dz, direction, dirs[direction], angle))

    def write_line(self, text, **kwargs):
        self.chat_box.write_line(text, **kwargs)

    def text_input_callback(self, symbol, modifier):
        if symbol == G.VALIDATE_KEY:
            txt = self.text_input.text.replace('\n', '')
            self.text_input.clear()
            if txt:
                self.world.packetreceiver.send_chat(txt)
            return pyglet.event.EVENT_HANDLED

    def hide_chat_box(self, dt):
        self.chat_box.toggle(False)

    def on_text_input_toggled(self):
        pyglet.clock.unschedule(self.hide_chat_box)  # Disable the fade timer
        self.chat_box.toggle(state=self.text_input.visible)  # Pass through the state incase chat_box was already visible
        if self.chat_box.visible:
            self.chat_box.focused = True # Allow scrolling
            self.window.push_handlers(self.chat_box)
        else:
            self.chat_box.focused = False
            self.window.remove_handlers(self.chat_box)

    def toggle_text_input(self):
        self.text_input.toggle()
        if self.text_input.visible:
            self.player.velocity = 0
            self.player.strafe = [0, 0]
            self.window.push_handlers(self.text_input)
            self.text_input.focus()
        else:
            self.window.remove_handlers(self.text_input)

    def push_handlers(self):
        if self.setup():
            self.window.push_handlers(self.camera)
            self.window.push_handlers(self.player)
            self.window.push_handlers(self)
            self.window.push_handlers(self.item_list)
            self.window.push_handlers(self.inventory_list)
        else:
            self.switch_controller_class(MainMenuController)

    def pop_handlers(self):
        while self.window._event_stack:
            self.window.pop_handlers()

    def on_close(self):
        G.save_config()
        self.world.packetreceiver.stop()  # Disconnect from the server so the process can close

    def show_map(self):
         # taken from Nebual's biome_explorer, this is ment to be a full screen map that uses mini tiles to make a full 2d map.
        with open(os.path.join(G.game_dir, "world", "seed"), "r") as f:
            SEED = f.read()
        b = BiomeGenerator(SEED)
        x, y, z = self.player.position
        curx =  x
        cury = y
        xsize = 79
        ysize = 28
        pbatch = pyglet.graphics.Batch()
        pgroup = pyglet.graphics.OrderedGroup(1)
        DESERT, PLAINS, MOUNTAINS, SNOW, FOREST = list(range(5))
        letters = ["D","P","M","S","F"]

        #  temp background pic...
        image = load_image('resources', 'textures', 'main_menu_background.png')

        #map_frame = image_sprite(image, pbatch, 0, y=G.WINDOW_WIDTH, height=G.WINDOW_HEIGHT)
        #sprite = pyglet.sprite.Sprite(image)
        #sprite.image(image)
        #sprite.visible = True
       # map_frame.draw()
       # map_frame.visible = True
        for y in range(int(cury),int(cury+ysize)):
         for x in range(int(curx),int(curx+xsize)):
             #string += letters[b.get_biome_type(x,y)]
            tmap = letters[b.get_biome_type(x,y)]
            tile_map = load_image('resources', 'textures', tmap +'.png')
            tile_map.anchor_x = x * 8
            tile_map.anchor_y = y * 8
            sprite = pyglet.sprite.Sprite(tile_map, x=x * 8, y=y * 8, batch=pbatch)
            game_map = image_sprite(tile_map, pbatch, pgroup, x * 8, y * 8, 8, 8)
            game_map = pyglet.sprite.Sprite(image,x=G.WINDOW_WIDTH, y=G.WINDOW_HEIGHT,batch=pbatch, group=pgroup)
            game_map = pyglet.sprite.Sprite(tile_map,x=x*8, y=y*8,batch=pbatch, group=pgroup)

            tile_map.blit(x *8, y * 8)

            #tile_map.draw()
            #map.append(tmap)
            game_map.draw()
            pbatch.draw()
Exemple #19
0
# initialize pygame
pygame.init()

# initialize game window
screen = pygame.display.set_mode(size=(PAGE_WIDTH, PAGE_HEIGHT))
# set caption of game window
pygame.display.set_caption('Space Invaders')
# load icon for game
icon = pygame.image.load('./images/ufo.png')
# set icon for the game
pygame.display.set_icon(icon)

# player -
p1 = Player(x=PLAYER_X,
            y=PLAYER_Y,
            screen=screen,
            image_path="./images/space-invaders.png")

# list of enemies -
enemies = list()
# make 2 rows
for j in range(2):
    # of 10 enemies each
    for i in range(10):
        enemy = Enemy(x=((PAGE_WIDTH - 2 * PAGE_BORDER) // 11) * (i + 1),
                      y=ENEMY_Y + j * ENEMY_START_HEIGHT,
                      screen=screen,
                      image_path="./images/spaceship.png",
                      respawn_status=False)
        enemies.append(enemy)
 def dequeue_packet(self):
     with self.lock:
         packetid, packet = self.world.sector_packets.popleft()
     if packetid == 1:  # Entire Sector
         blocks, sectors = self.world, self.world.sectors
         secpos = struct.unpack("iii", packet[:12])
         sector = sectors[secpos]
         cx, cy, cz = sector_to_blockpos(secpos)
         fpos = 12
         exposed_pos = fpos + 1024
         for x in range(cx, cx+8):
             for y in range(cy, cy+8):
                 for z in range(cz, cz+8):
                     read = packet[fpos:fpos+2]
                     fpos += 2
                     unpacked = structuchar2.unpack(read)
                     if read != null2 and unpacked in BLOCKS_DIR:
                         position = x,y,z
                         try:
                             blocks[position] = BLOCKS_DIR[unpacked]
                             if blocks[position].sub_id_as_metadata:
                                 blocks[position] = type(BLOCKS_DIR[unpacked])()
                                 blocks[position].set_metadata(0)
                         except KeyError:
                             main_blk = BLOCKS_DIR[(unpacked[0], 0)]
                             if main_blk.sub_id_as_metadata: # sub id is metadata
                                 blocks[position] = type(main_blk)()
                                 blocks[position].set_metadata(unpacked[-1])
                         sector.append(position)
                         if packet[exposed_pos:exposed_pos+1] == b"1":
                             blocks.show_block(position)
                     exposed_pos += 1
         if secpos in self.world.sector_queue:
             del self.world.sector_queue[secpos] #Delete any hide sector orders
     elif packetid == 2:  # Blank Sector
         self.world.sectors[struct.unpack("iii", packet)] = []
     elif packetid == 3:  # Add Block
         self.world._add_block(struct.unpack("iii", packet[:12]),
             BLOCKS_DIR[struct.unpack("BB", packet[12:])])
     elif packetid == 4:  # Remove Block
         self.world._remove_block(struct.unpack("iii", packet))
     elif packetid == 5:  # Chat Print
         self.controller.write_line(packet[:-4].decode('utf-8'), color=struct.unpack("BBBB", packet[-4:]))
         if not self.controller.text_input.visible:
             self.controller.chat_box.visible = True
             pyglet.clock.unschedule(self.controller.hide_chat_box)
             pyglet.clock.schedule_once(self.controller.hide_chat_box, G.CHAT_FADE_TIME)
     elif packetid == 6:  # Inventory
         player = self.controller.player
         caret = 0
         for inventory in (player.quick_slots.slots, player.inventory.slots, player.armor.slots):
             for i in range(len(inventory)):
                 id_main, id_sub, amount = struct.unpack("HBB", packet[caret:caret+4])
                 caret += 4
                 if id_main == 0: continue
                 durability = -1
                 if id_main >= G.ITEM_ID_MIN and (id_main, id_sub) not in G.ITEMS_DIR:
                     #The subid must be durability
                     durability = id_sub * G.ITEMS_DIR[(id_main, 0)].durability // 255
                     id_sub = 0
                 inventory[i] = ItemStack(type=BlockID(id_main, id_sub), amount=amount, durability=durability)
         self.controller.item_list.update_items()
         self.controller.inventory_list.update_items()
     elif packetid == 7:  # New player connected
         plyid, name = struct.unpack("H", packet[:2])[0], packet[2:].decode('utf-8')
         if plyid not in self.controller.player_ids:
             self.controller.player_ids[plyid] = Player(username=name, local_player=False)
         elif name == '\0':
             del self.controller.player_ids[plyid]
     elif packetid == 8:  # Player Movement
         ply = self.controller.player_ids[struct.unpack("H", packet[:2])[0]]
         ply.momentum = struct.unpack("fff", packet[2:14])
         ply.position = struct.unpack("ddd", packet[14:])
     elif packetid == 9:  # Player Jump
         self.controller.player_ids[struct.unpack("H", packet)[0]].dy = 0.016
     elif packetid == 10: # Update Tile Entity
         try:
             self.world[struct.unpack("iii", packet[:12])].update_tile_entity(packet[12:])
         except Exception as e:
             warn(str(e))
     elif packetid == 255:  # Spawn Position
         self.controller.player.position = struct.unpack("iii", packet[:12])
         packet = packet[12:]
         packet, seed = extract_string_packet(packet)
         self.world.biome_generator = BiomeGenerator(seed)
         #Now that we know where the player should be, we can enable .update again
         self.controller.update = self.controller.update_disabled
     else:
         warn("Received unknown packetid %s, there's probably a version mismatch between client and server!" % packetid)
Exemple #21
0
def main():
    pygame.init()
    pygame.running = True
    running = True
    routes = None

    # window for drawing on
    window_width = config.window_width
    window_height = config.window_height
    grid_spacing = config.grid_spacing
    win = pygame.display.set_mode(
        (window_width, window_height))  #width and height of window

    pygame.display.set_caption("Pokémon Crisis")

    bg = pygame.image.load('sprites/background.jpg').convert()
    oak = pygame.image.load('sprites/oak.png')

    new_map = Map()
    #use all objects, set specific number of grass tree and water objects
    new_map.generate_map(grass=20, trees=20, water=2)

    clock = pygame.time.Clock()

    ash = Player(choice(tuple(new_map.nodes)))

    font = pygame.font.SysFont('verdana', 10, False, True)

    path = Pathfinding(new_map.nodes, new_map.movement_cost_area)

    def redraw_gamewindow():
        win.blit(bg, (0, 0))  #put picutre on screen (background)
        pygame.draw.rect(win, (200, 200, 200),
                         (0, 0, window_width, window_height))

        # # draw grid
        # for x in range(0,window_width,grid_spacing): #col
        # 	for y in range(0,window_height,grid_spacing): #row
        # 		pygame.draw.rect(win, (125,125,125), (x,y,grid_spacing,grid_spacing),1)

        Map.draw(win)
        if routes:
            # draw bfs route
            for x, y in routes['BFS']:
                pygame.draw.rect(win, (0, 0, 255),
                                 (x, y, grid_spacing, grid_spacing))
            #draw dfs route
            for x, y in routes['DFS']:
                pygame.draw.rect(win, (0, 0, 100),
                                 (x, y, grid_spacing, grid_spacing))
            # draw dijkstra route
            for x, y in routes['GBFS']:
                pygame.draw.rect(win, (255, 0, 0),
                                 (x, y, grid_spacing, grid_spacing))
            #draw DA route
            for x, y in routes['DA']:
                pygame.draw.rect(win, (0, 255, 0),
                                 (x, y, grid_spacing, grid_spacing))
            # draw A* route
            for x, y in routes['A*']:
                pygame.draw.rect(win, (100, 100, 100),
                                 (x, y, grid_spacing, grid_spacing))

            # re-position oak if oob
            oak_x = target_x
            oak_y = target_y
            if oak_x > window_width - oak.get_width(): oak_x -= grid_spacing
            elif oak_y > window_height - oak.get_height():
                oak_y -= grid_spacing
            win.blit(oak, (oak_x, oak_y))

        ash.draw(win)

        pygame.display.update()

    #main event loop
    while running:
        clock.tick(9)  #9 FPS

        for event in pygame.event.get(
        ):  #get mouse positions, keyboard clicks etc
            if event.type == pygame.QUIT:  #we pressed the exit button
                running = False
            if event.type == pygame.MOUSEBUTTONDOWN:
                target_x, target_y = event.pos[0], event.pos[1]
                routes = path.compute_all_paths(ash.x, ash.y, target_x,
                                                target_y)

        #move amongst available nodes
        #(no movement out of bounds and in object coordinates)
        #movement cost in grass / water
        ash.move(new_map.objs_area, new_map.movement_cost_area)
        redraw_gamewindow()

    pygame.quit()
Exemple #22
0
class Game:
    def __init__(self, screen):
        self.screen = screen
        self.objects = []
        self.game_messages = []
        self.game_state = Game_States.none
        self.map = []
        self.characters = []
        self.text_background = pygame.Surface((config.screen_width, 180))
        self.scene_surface = pygame.Surface((config.screen_width, config.screen_height))
        self.message_count = 0

        self.grid_index_X = int(config.screen_width / config.scale) - 1
        self.grid_index_Y = int(config.screen_height / config.scale)

        self.main_map = pygame.Surface((config.screen_width, config.screen_height))

        self.game_map = [[Map_Tile(True, False) for y in range(0, config.screen_height)] for x in
                         range(0, config.screen_width)]

        for x in range(5, 12):
            for y in range(5, 7):
                self.game_map[x][y].movement = False
                self.game_map[x][y].movement = False

        self.player = Player(self.screen, self.game_map)  # initialise player

        # initialise first tester npc
        self.tester_npc = CharacterController("NPC1", 7, 8, self.screen, config.NPC01IDLE, self.game_map,
                                              config.NPC01LEFT, config.NPC01RIGHT, config.NPC01BACK,
                                              config.NPC01FRONT, config.NPC01IDLE)
        self.message1 = self.tester_npc.text_to_speak(self.screen, "Hi there! How are you doing?",
                                                      config.game_messages,
                                                      (1 * config.scale, 9 * config.scale),
                                                      config.black)
        self.message2 = self.tester_npc.text_to_speak(self.screen, "I like you very much!", config.game_messages,
                                                      (1 * config.scale, 9 * config.scale),
                                                      config.black)

        self.my_creatures = [creature.charmander]

        # initialise the route creatures

        self.route1 = [creature.bulbasaur, creature.squirtle, creature.charmander]

        # TODO: find out a better way to do this

        # sets the tree objects
        # self.tester_npc2 = CharacterController("NPC2", 3, 3, self.screen, config.NPC02, self.game_map)

        self.treesXb = [Obstacles(config.tree01, x, 11, self.player.group)
                        for x in range(self.grid_index_X)]
        self.treesXt = [Obstacles(config.tree01, x, 0, self.player.group)
                        for x in range(self.grid_index_X)]

        self.treesYl = [Obstacles(config.tree01, 0, y, self.player.group)
                        for y in range(self.grid_index_Y)]
        self.treesYr = [Obstacles(config.tree01, self.grid_index_X, y, self.player.group)
                        for y in range(self.grid_index_Y)]

        self.tall_grass = [[Non_Obstacle_Tiles(config.tallgrass01, x, y, self.player)
                            for x in range(9, self.grid_index_X)] for y in range(1, 4)]

        self.trees = [self.treesXb, self.treesXt, self.treesYl, self.treesYr]

        # adds the tree border to the game

        for x in range(self.grid_index_X):
            self.game_map[x][self.grid_index_Y - 1].blocked = True
            self.game_map[x][0].blocked = True
        for y in range(self.grid_index_Y):
            self.game_map[0][y].blocked = True
            self.game_map[self.grid_index_X][y].blocked = True

        # scene mechanics
        self.scene = Scene(self.scene_surface)
        self.scene.set_background(config.battle_background, self.scene_surface)

    def set_up(self):
        print("setting up")
        self.game_state = Game_States.running

        # self.objects.append(self.tester_npc)
        # self.objects.append(self.tester_npc2)

        self.characters.append(self.tester_npc)
        # self.characters.append(self.tester_npc2)

        # TODO: find out a better way to do this

        for tree_list in self.trees:
            for tree in tree_list:
                self.objects.append(tree)

        self.objects.append(self.player)  # adds player to object list

        for tallgrass in self.tall_grass:
            for i in tallgrass:
                self.objects.append(i)

        self.render_map(self.game_map)
        self.screen.blit(self.main_map, (0, 0))

        pygame.display.flip()  # update screen

    def update(self, clock):

        self.game_messages = [self.message1, self.message2]

        fps_count = Text_Controller(self.screen, "FPS: " + str(int(clock.get_fps())),
                                    config.fps_Counter, (5, 5), config.black)

        self.screen.blit(self.main_map, (0, 0))
        self.render_blocked_tiles(self.game_map)
        self.manage_events()
        self.manage_ais()

        for obj in self.objects:  # draws all objects into the screen
            obj.image.convert()
            obj.draw(self.screen)
            fps_count.draw_text()

        self.player.rect.topleft = self.player.rect.x, self.player.rect.y  # updates player's rect
        self.tester_npc.rect.topleft = self.tester_npc.rect.x, self.tester_npc.rect.y

        for grass in self.tall_grass:
            for i in grass:
                i.check_collide(self)

        for character in self.characters:
            self.player.check_collision(character.group)
            character.check_collision(self.player, self)  # the one that identifies it

        pygame.display.flip()

    def manage_ais(self):
        self.tester_npc.ai_left_right()
        self.tester_npc.play_animation()
        # self.tester_npc2.ai_up_down()

    def manage_events(self):
        rdm_pos = self.random_grass()

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                self.game_state = Game_States.quit

            elif event.type == pygame.KEYDOWN:

                if event.key == pygame.K_ESCAPE:
                    self.game_state = Game_States.quit

                elif event.key == pygame.K_a:  # left
                    self.player.update_position(0, -1)
                    self.player.left = True
                    self.player.right = False
                    self.player.front = False
                    self.player.back = False

                elif event.key == pygame.K_d:  # right
                    self.player.update_position(0, 1)
                    self.player.left = False
                    self.player.right = True
                    self.player.front = False
                    self.player.back = False

                elif event.key == pygame.K_w:  # up
                    self.player.update_position(-1, 0)
                    self.player.front = False
                    self.player.back = True
                    self.player.left = False
                    self.player.right = False

                elif event.key == pygame.K_s:  # down
                    self.player.update_position(1, 0)
                    self.player.front = True
                    self.player.back = False
                    self.player.left = False
                    self.player.right = False

                elif self.player.position == rdm_pos:
                    print(rdm_pos)
                    print("yes")

                else:
                    self.player.left = False
                    self.player.right = False
                    self.player.back = False
                    self.player.front = False
                    self.player.walk_count = 0

                if event.key == pygame.K_p:  # pause
                    self.pause_game()

                if event.key == pygame.K_o:
                    pass

    def render_map(self, drawn_map):

        for x in range(0, config.screen_width):
            for y in range(0, config.screen_height):

                if drawn_map[x][y].movement:
                    self.main_map.blit(config.grass01, (x * config.scale, y * config.scale))

    def render_blocked_tiles(self, drawn_map):
        for x in range(0, config.screen_width):
            for y in range(0, config.screen_height):

                if not drawn_map[x][y].movement:
                    self.screen.blit(config.water01, (x * config.scale, y * config.scale))

    def pause_game(self):
        self.game_state = Game_States.pause
        self.screen.blit(self.scene_surface, (0, 0))
        pygame.display.flip()

        for event in pygame.event.get():  # pause sequence
            if event.type == pygame.QUIT:
                quit()
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_r:
                    self.game_state = Game_States.running

                elif event.key == pygame.K_ESCAPE:
                    quit()

    def play_scene(self):
        self.game_state = Game_States.play_scene
        self.screen.blit(self.scene_surface, (0, 0))
        print("displaying scene")

        pygame.display.flip()

    def play_message(self):
        count = 0
        done = False

        self.text_background.blit(config.text_background, (0, 0))
        self.screen.blit(self.text_background, (0, 300))
        self.game_messages[0].draw_text()
        pygame.display.flip()

        while not done:
            for event in pygame.event.get():
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_ESCAPE:
                        quit()

                    elif event.key == pygame.K_SPACE:
                        count += 1
                        print(len(self.game_messages))

                        if count == len(self.game_messages):
                            self.game_state = Game_States.running
                            done = True

                        elif count < len(self.game_messages):
                            self.screen.blit(self.text_background, (0, 300))
                            self.game_messages[count].draw_text()

                            pygame.display.flip()

    def random_grass(self):
        random_list = []
        for tallgrass in self.tall_grass:
            for i in tallgrass:
                position = i.get_position()

                random_list.append((position))
        return random_list[random.randint(0, len(random_list) - 1)]

    @staticmethod
    def button_mechanics(button, mouse):
        for event in pygame.event.get():
            if event.type == pygame.MOUSEBUTTONDOWN:
                if button.rect.x < mouse[0] < (
                        button.rect.x + button.rect[2]):
                    if button.rect.y < mouse[1] < (
                            button.rect.y + button.rect[3]):
                        # add what happens after fight button is clicked here
                        print("click")
                        ended = True

            elif event.type == pygame.MOUSEMOTION:
                if button.rect.x < mouse[0] < (
                        button.rect.x + button.rect[2]):
                    if button.rect.y < mouse[1] < (
                            button.rect.y + button.rect[3]):
                        # print("hover")
                        button.image = config.fight_button_H
                        button.draw()

                    else:
                        button.image = config.fight_button
                        button.draw()

    def game_mechanics(self):
        self.scene_surface.blit(config.battle_background, (0, 0))
        self.play_scene()
Exemple #23
0
        self.name = "Where are we now"
        # Position of Where are we now tile
        super().__init__(x, y)


class Hooligan(MapTile):
    """Lake location containing easy difficutly fish"""
    def __init__(self, x, y):
        self.name = "Hooligan"
        # Position of Hooligan tile
        super().__init__(x, y)


class Residential(MapTile):
    """Lake containing trader to obtain items"""
    def __init__(self, x, y):
        self.name = "Residential"
        # Position of Residential tile
        super().__init__(x, y)


# The map
world_map = [[None, None, Ethereal(2, 0), None, None],
             [None, None, None, None, None],
             [Juliot(0, 2), None, None, None,
              Kytersize(4, 2)], [None, None, None, None, None],
             [None, Where(1, 4), None,
              Hooligan(3, 4), None],
             [None, None, Residential(2, 5), None, None],
             [None, None, None, Player(3, 6), None]]
Exemple #24
0
    def __init__(self, screen):
        self.screen = screen
        self.objects = []
        self.game_messages = []
        self.game_state = Game_States.none
        self.map = []
        self.characters = []
        self.text_background = pygame.Surface((config.screen_width, 180))
        self.scene_surface = pygame.Surface((config.screen_width, config.screen_height))
        self.message_count = 0

        self.grid_index_X = int(config.screen_width / config.scale) - 1
        self.grid_index_Y = int(config.screen_height / config.scale)

        self.main_map = pygame.Surface((config.screen_width, config.screen_height))

        self.game_map = [[Map_Tile(True, False) for y in range(0, config.screen_height)] for x in
                         range(0, config.screen_width)]

        for x in range(5, 12):
            for y in range(5, 7):
                self.game_map[x][y].movement = False
                self.game_map[x][y].movement = False

        self.player = Player(self.screen, self.game_map)  # initialise player

        # initialise first tester npc
        self.tester_npc = CharacterController("NPC1", 7, 8, self.screen, config.NPC01IDLE, self.game_map,
                                              config.NPC01LEFT, config.NPC01RIGHT, config.NPC01BACK,
                                              config.NPC01FRONT, config.NPC01IDLE)
        self.message1 = self.tester_npc.text_to_speak(self.screen, "Hi there! How are you doing?",
                                                      config.game_messages,
                                                      (1 * config.scale, 9 * config.scale),
                                                      config.black)
        self.message2 = self.tester_npc.text_to_speak(self.screen, "I like you very much!", config.game_messages,
                                                      (1 * config.scale, 9 * config.scale),
                                                      config.black)

        self.my_creatures = [creature.charmander]

        # initialise the route creatures

        self.route1 = [creature.bulbasaur, creature.squirtle, creature.charmander]

        # TODO: find out a better way to do this

        # sets the tree objects
        # self.tester_npc2 = CharacterController("NPC2", 3, 3, self.screen, config.NPC02, self.game_map)

        self.treesXb = [Obstacles(config.tree01, x, 11, self.player.group)
                        for x in range(self.grid_index_X)]
        self.treesXt = [Obstacles(config.tree01, x, 0, self.player.group)
                        for x in range(self.grid_index_X)]

        self.treesYl = [Obstacles(config.tree01, 0, y, self.player.group)
                        for y in range(self.grid_index_Y)]
        self.treesYr = [Obstacles(config.tree01, self.grid_index_X, y, self.player.group)
                        for y in range(self.grid_index_Y)]

        self.tall_grass = [[Non_Obstacle_Tiles(config.tallgrass01, x, y, self.player)
                            for x in range(9, self.grid_index_X)] for y in range(1, 4)]

        self.trees = [self.treesXb, self.treesXt, self.treesYl, self.treesYr]

        # adds the tree border to the game

        for x in range(self.grid_index_X):
            self.game_map[x][self.grid_index_Y - 1].blocked = True
            self.game_map[x][0].blocked = True
        for y in range(self.grid_index_Y):
            self.game_map[0][y].blocked = True
            self.game_map[self.grid_index_X][y].blocked = True

        # scene mechanics
        self.scene = Scene(self.scene_surface)
        self.scene.set_background(config.battle_background, self.scene_surface)
Exemple #25
0
class StartGame:
    '''main game class'''
    def __init__(self, win, net, username):
        self.menu = False
        self.grid = False
        self.win = win
        self.net = net

        #generate and save map
        # new_map = Map()
        # new_map.generate_map('random', False)

        self.bg = pygame.image.load('sprites/background.jpg').convert()

        #load first shuffled map from server
        self.current_map = 0
        Map.load(self.net.maps[self.current_map])

        #create client player object and assign colour based on ID, username from input, map from server
        self.ash = Player(
            RandomNode(Map.nodes).node, self.net.playerID, username,
            self.current_map)

        #other player objects
        p2, p3, p4, p5 = None, None, None, None
        self.players = [p2, p3, p4, p5]

        self.bikes = [Bike() for i in range(config.bikes)]
        self.mushrooms = [Mushroom() for i in range(config.mushrooms)]

        WeaponStatus.set_locations(self.bikes, self.mushrooms)

        music = pygame.mixer.music.load(config.theme)
        pygame.mixer.music.set_volume(0.5)
        pygame.mixer.music.play(-1)

        self.ash.ID = self.net.playerID

    def redraw_gamewindow(self):
        '''draw objects onto the screen: background, grid, players, weapons'''
        self.win.blit(self.bg, (0, 0))  #put picutre on screen (background)

        # draw grid
        if self.grid:
            for x in range(0, config.window_width, config.grid_spacing):  #col
                for y in range(0, config.window_height,
                               config.grid_spacing):  #row
                    pygame.draw.rect(
                        self.win, (125, 125, 125),
                        (x, y, config.grid_spacing, config.grid_spacing), 1)

        Map.draw(self.win)
        for bike in self.bikes:
            bike.draw(self.win)
        for mushroom in self.mushrooms:
            mushroom.draw(self.win)
        self.ash.draw(self.win)

        #draw all players
        for p in self.players:
            if p and p.ID != None:
                p.draw(self.win)

                #note that we are 20px behind (last position doesnt show... this is temp fix)
                for bullet in p.inventory:
                    bullet_sprite = pygame.image.load(
                        'sprites/objects/pokeball.png').convert_alpha()
                    x, y, _dir, start_x, start_y = bullet
                    if _dir == 'L':
                        x += 20
                    elif _dir == 'R':
                        x -= 20
                    elif _dir == 'U':
                        y += 20
                    elif _dir == 'D':
                        y -= 20
                    self.win.blit(bullet_sprite, (x, y))

                self.ash.check_trample(p)

        #pressed z
        if self.menu:
            Menu(self.win, [self.ash.stats, self.ash.username],
                 [[p.stats, p.username] for p in self.players if p])

        for bullet in self.ash.inventory:
            self.ash.draw_bullet(self.win, bullet)
            for p in self.players:
                if p and p.ID != None:
                    self.ash.check_kill(bullet, p)

        pygame.display.update()

    def change_map(self):
        '''host (ID=0) may change map i.e. go to next shuffled map from server or back to 0'''
        if self.ash.map < len(self.net.maps) - 1:
            self.ash.map += 1
        else:
            self.ash.map = 0
        Map.load(self.net.maps[self.ash.map])
        WeaponStatus.set_locations(self.bikes, self.mushrooms)

    def check_keyboard_input(self, event):
        '''check for Z,X,C'''
        if event.type == pygame.KEYUP:
            if event.key == pygame.K_SPACE:
                self.ash.space_up = True
            if event.key == pygame.K_z:  #z for menu
                self.menu = True if not self.menu else False
            if event.key == pygame.K_x:  #a for grid
                self.grid = True if not self.grid else False
            if event.key == pygame.K_c and self.ash.ID == 0:  #host can press c to change map
                self.change_map()

    def fetch_data(self):
        '''get data from server, player positions, stats, kill status etc'''
        Multiplayer.get_player_data(self.ash, self.net, self.players,
                                    self.bikes, self.mushrooms)
        Multiplayer.check_death_status(self.ash, self.players)

    def check_collisions_and_pickups(self):
        WeaponStatus(self.ash)
        self.ash.move(Map.objs_area, Map.movement_cost_area, self.bikes,
                      self.mushrooms)
Exemple #26
0
from characters import Player
from obstacles import Stone
import os
import pygame

###Resources###
resources = "resources"
background_path = os.path.join(resources, "background.jpg")

###Backgrounds###
background = pygame.image.load(background_path)

###Characters###
#alucard_path = os.path.join(resources, "images.png")
#img = pygame.image.load(alucard_path)
img = pygame.Surface((32, 48))
img.fill((255, 0, 0))
alucard = Player(image=img, pos=(20, 200), walk=10, jump_height=10)

###Obstacles###
stones = []
for i in range(10):
    s = Stone()
    stones.append(s)
Exemple #27
0
# CS 30
# Period 4
# Date : 12/9/2019
# Krutik Rana
# Program description : Players inventory and command to heal player
from characters import Player

# Creates and instance of player to be used
player = Player(None, None)


def inventory():
    """Commands to access the characters inventory"""
    # While loop to continously play
    while True:
        # Print statement detailing how to go to the last menu
        print('\ntype q to go back to previous menu')
        # Aquiring user input for what they want to access of the inventory
        user = input('action: ')
        # Making the user input all lower case to match if and elif statements
        user = user.lower()
        # Checks to see if the user typed weapon
        if user == 'backpack':
            # Prints the current inventory of the player
            player.print_inventory()
        # Checks to see if user typed heal
        elif user == 'heal':
            # Bring up the heal menu
            player.heal()
        # Checks to see if user typed q
        elif user == 'q':
Exemple #28
0
class Game:
    """ Class used to play the game. """

    # We start Pygame
    pygame.init()
    pygame.font.init()
    # We prepare the font of our caption to indicate how many items we picked
    # up
    myfont = pygame.font.SysFont(None, 40)

    # We display the window
    square_window = pygame.display.set_mode(WINDOW_DIMENSIONS)

    # We make the labyrinth
    labyrinth = Labyrinth(FLOOR_IMAGE, WALL_IMAGE, LEVEL_FILE)
    labyrinth.initialize_labyrinth(square_window)

    # We initialize McGyver and the gatekeeper
    mac = Player(PLAYER_PIC, labyrinth.PLAYER_COORDINATES)
    gatekeeper = Boss(BOSS_PIC, labyrinth.BOSS_COORDINATES)

    # We initialize the three components of the serynge
    needle = Items(NEEDLE_PIC, labyrinth)
    tube = Items(TUBE_PIC, labyrinth)
    ether = Items(ETHER_PIC, labyrinth)

    # Displays Items
    def display_items(self, item):
        self.square_window.blit(item.image, item.coordinates)

    # Display characters
    def display_character(self, character):
        self.square_window.blit(character.head, character.coordinates)

    def main(self):
        """ Function that runs the game """
        is_running = True
        # Loop of the game
        while is_running:

            # Displays the game
            self.labyrinth.display_labyrinth(self.square_window)
            self.display_character(self.mac)
            self.display_character(self.gatekeeper)
            for item in Items.LIST_OF_ITEMS:
                self.display_items(item)
            pygame.display.flip()

            # What happens when we meet the gatekeeper
            if self.mac.coordinates in self.labyrinth.FIGHT_POSITION:
                if self.mac.count == 3:
                    self.mac.neutralize(
                        self.labyrinth,
                        self.gatekeeper,
                        self.labyrinth.EXIT_POSITION)
                else:
                    self.gatekeeper.lose(self.mac, CARCASS)
                    self.square_window.blit(
                        self.mac.head, self.mac.coordinates)
                    is_running = False

            # Reaching the exit position
            if self.mac.coordinates == self.labyrinth.EXIT_POSITION:
                self.mac.victorious = True
                is_running = False

            # Events detection
            for event in pygame.event.get():
                if event.type == QUIT:
                    is_running = False
                if event.type == KEYDOWN:
                    x, y = self.mac.move(event)

                    # Square where we can walk, or with a serynge component, or
                    # wall so we can't use it
                    if (x, y) in [
                            item.coordinates for item in Items.LIST_OF_ITEMS]:
                        self.mac.count += 1
                        Items.LIST_OF_ITEMS = [
                            item for item in Items.LIST_OF_ITEMS if item.coordinates != (
                                x, y)]
                        moving = True
                        print(self.mac.count)
                    else:
                        moving = False

                    if self.labyrinth.reachable((x / 40, y / 40)):
                        moving = True

                    #  Moving means replace the position of Mac by en empty square
                    # Moving also means replacing an empty square by the
                    # position of Mac
                    if moving:
                        self.labyrinth.void.append(self.mac.coordinates)
                        self.mac.coordinates = (x, y)

            txt = self.myfont.render(
                str(self.mac.count) + "items picked up!", False, (255, 255, 255))
            self.square_window.blit(txt, (0, 0))
            pygame.display.flip()

        # Outcome of the game
        if self.mac.victorious:
            path = VICTORY
        else:
            path = FAILURE

        # Showing the outcome notification
        notification = pygame.image.load(path).convert()
        self.square_window.blit(notification, (100, 300))
        pygame.display.flip()

        #  Waiting 1 seconds before closing the window
        sleep(1)
    def main(self):
        """ Main Program """
        pygame.init()

        # Create the player
        player = Player(SpriteSheet('catman.png'))
        # Create all the levels
        level_list = []
        level_list.append(levels.Level_01(player))
        level_list.append(levels.Level_02(player))

        # Set the current level & player position
        current_level_no = 0
        current_level = level_list[current_level_no]

        active_sprite_list = pygame.sprite.Group()
        player.level = current_level
        player.rect.x = 340
        player.rect.y = constants.SCREEN_HEIGHT - player.rect.height - 500
        active_sprite_list.add(player)

        # Loop until the user clicks the close button.
        done = False

        # Used to manage how fast the screen updates
        clock = pygame.time.Clock()
        start_ticks = pygame.time.get_ticks()  #starter tick

        # -------- Main Program Loop -----------
        while not done:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    done = True
                elif event.type == None:
                    player.idle()
                elif event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_a or event.key == pygame.K_LEFT:
                        player.go_left()
                    elif event.key == pygame.K_d or event.key == pygame.K_RIGHT:
                        player.go_right()
                    elif event.key == pygame.K_w or event.key == pygame.K_UP:
                        player.jump()
                    elif event.key == pygame.K_SPACE:
                        if len(player.bullet_list) < 4:
                            # Fire a bullet if the user clicks the mouse button
                            bullet = Bullet(player)
                            # Set the bullet so it is where the player is
                            bullet.rect.x = player.rect.x + 10
                            bullet.rect.y = player.rect.y + 10
                            # Add the bullet to the lists
                            player.bullet_list.add(bullet)

                # set what happens when player lets the key up
                elif event.type == pygame.KEYUP:
                    if event.key == pygame.K_a or event.key == pygame.K_LEFT and player.change_x < 0:
                        player.stop()
                    elif event.key == pygame.K_d or event.key == pygame.K_RIGHT and player.change_x > 0:
                        player.stop()

            # Update the player.
            active_sprite_list.update()
            player.bullet_list.update()
            # Update items in the level
            current_level.update()

            ydiff = 0
            diff = 0
            # if the player gets near the top, shift the world up (ydiff)
            if player.rect.top <= 20:
                ydiff = player.rect.top - 20
                player.rect.top = 20
                current_level.shift_world_y(ydiff)

            # if the player gets near the bottom, shift the world down (ydiff)
            if player.rect.bottom >= 550:
                ydiff = player.rect.bottom - 550
                player.rect.bottom = 550
                current_level.shift_world_y(ydiff)

            # If the player gets near the right side, shift the world left (-x)
            if player.rect.right >= 500:
                diff = player.rect.right - 500
                player.rect.right = 500
                current_level.shift_world(-diff)

            # If the player gets near the left side, shift the world right (+x)
            if player.rect.left <= 120:
                diff = 120 - player.rect.left
                player.rect.left = 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 = 150
                if current_level_no < len(level_list) - 1:
                    current_level_no += 1
                    current_level = level_list[current_level_no]
                    player.level = current_level
                    player.stop()

            # IF the player falls, game done
            if player.rect.y + player.level.world_shift_y + 75 > constants.SCREEN_HEIGHT:
                done = True

            seconds = (pygame.time.get_ticks() -
                       start_ticks) / 1000  #calculate how many seconds
            # ALL CODE TO DRAW SHOULD GO BELOW THIS COMMENT
            current_level.draw(screen)
            active_sprite_list.draw(screen)
            player.bullet_list.draw(screen)
            font = pygame.font.SysFont(None, 25)
            showscore = font.render(f"Score: {player.score}", True,
                                    constants.BLACK)
            showclock = font.render(f"Time: {round(seconds,2)}", True,
                                    constants.BLACK)
            screen.blit(showscore, (10, 10))
            screen.blit(showclock, (constants.SCREEN_WIDTH / 2, 10))
            for crony in player.level.enemy_list:
                crony.draw(screen)
            for platform in player.level.platform_list:
                try:
                    platform.draw(screen)
                except:
                    pass
            # 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.update()
            print(player.rect.x - player.level.world_shift, player.rect.y)
        # Be IDLE friendly. If you forget this line, the program will 'hang'
        # on exit.
        pygame.quit()