Exemple #1
0
 def __init__(self):
     self.loc = None #Where we think we are
     world.load("the_world")
     self.condition = Condition()
     self.netThread = NetThread(self.condition)
     self.aiThread = AIThread(self.condition)
     self.terminate = False
Exemple #2
0
    def update(this, delta_time):
        # Movement code
        if not ("mov_del" in this.attributes["effects"]):
            diffX = this.X - world.player.X # How much it needs to move left to hit player
            diffY = this.Y - world.player.Y # How much it needs to move down to hit player
            if diffX < 0:
                this.X += 1
            else:
                this.X -= (not not diffX) # Should give either 1 or 0.
            if diffY < 0:
                this.Y += 1
            else:
                this.Y -= (not not diffY)
            # Add boundary checking
            if this.X == 0: # Left side
                this.X += 1
            if this.X == world.WORLD_X - 1: # Right side
                this.X -= 1
            if this.Y == 0: # Top
                this.Y += 1
            if this.Y == world.WORLD_Y - 1: # Bottom
                this.Y -= 1
            this.attributes["effects"]["mov_del"] = effect.effect(this, this.attributes["mov_spd"])
        # Attack code
        this.attributes["to_atk"] -= delta_time
        if this.attributes["to_atk"] <= 0:
            this.attributes["to_atk"] = this.attributes["atk_spd"] - 200 + this.attributes["HP"] # He attacks faster with less HP
            # Find which direction to shoot
            diffX = world.player.X - this.X # How much it needs to move left to hit player
            diffY = world.player.Y - this.Y # How much it needs to move down to hit player
            if diffX < 0:
                diffX = -1
            else:
                diffX = int(not not diffX)
            if diffY < 0:
                diffY = -1
            else:
                diffY = int(not not diffY)
            world.objects.append(attack.boss_attack(this.X + diffX, this.Y + diffY, diffX, diffY, this.attributes["damage"], this.attributes["range"], 250, this))
        
        # Update all effects.
        eff_del_list = []
        for eff_name in this.attributes["effects"]:
            eff = this.attributes["effects"][eff_name]
            eff.tick(delta_time)  # Tick effect
            if eff.time <= 0:           # Remove effect
                eff_del_list.append(eff_name)
        for eff_name in eff_del_list:
            this.attributes["effects"][eff_name].uneffect(this)
            del this.attributes["effects"][eff_name]
        del eff_del_list

        if this.attributes["HP"] <= 0:
            this.die()
            world.load("tutorial.boss-killed")
            world.objects = [world.player] + world.objects
            world.player.X = 10
            world.player.Y = 10
            world.dispworld()
            return True
def load():
    variables['Player'] = ssave.load(s, 'player')
    world.load(ssave.load(s, 'world'))  #load the world
    variables['World'] = world._world
    data = ssave.load(s, 'game')  # retrieve game data
    variables['Game variables']['Current turn'] = data[
        'turn']  # set current turn
    variables['Game variables']['Previous turn'] = data[
        'prev. turn']  # set previous turn
Exemple #4
0
    def collide(this, other):
        "If collided with player, brings them to the new map."
        if other.type == "player":
            world.load(this.attributes["newmap"])
            world.objects = [world.player] + world.objects

            world.player.X = this.attributes["locx"]
            world.player.Y = this.attributes["locy"]
            this.attributes["used"] = True
            # Print world out
            world.dispworld()
            return True
Exemple #5
0
 def update(this, delta_time):
     if this.attributes["HP"] <= 0:
         this.die()
         if world.player.attributes["level"] >= 2: # If they're level 2, they leveled up and need to be notified.
             world.load("tutorial.2-killed")
             world.objects = [world.player] + world.objects
             if world.player.X == world.WORLD_X - 1: # If they're on the portal
                 world.player.X -= 1 # Push them back a bit
             world.dispworld()
             return True
         return
     super().update(delta_time)
Exemple #6
0
 def update(this, delta_time):
     if this.attributes["HP"] <= 0:
         this.die()
         if world.player.attributes[
                 "level"] >= 2:  # If they're level 2, they leveled up and need to be notified.
             world.load("tutorial.2-killed")
             world.objects = [world.player] + world.objects
             if world.player.X == world.WORLD_X - 1:  # If they're on the portal
                 world.player.X -= 1  # Push them back a bit
             world.dispworld()
             return True
         return
     super().update(delta_time)
Exemple #7
0
    def __init__(self):
        compressedTextures = ConfigVariableString('compressed-textures','1') # Compresses Textures on load (increases loadtime / framerate)
        ShowBase.__init__(self)
        
        ## Debug Values (True/False)
        self.fpsMeter = True
        
        debug.checkDebugSettings(self)

        self.KeyBindings()

        ## Load World
        world.load('prisonCrater')

        ## Add Player to World
        self.playerBox = NodePath('player')
        self.player = Actor("data/models/hm.bam",
                            {"run":"data/models/hm-run.bam",
                             "idle":"data/models/hm.bam"})
        self.player.reparentTo(self.playerBox)
        self.player.setScale(.01)
        self.playerBox.reparentTo(render)
        self.isMoving = False

        ## Create Camera
        base.disableMouse()
        self.cameratarget = self.render.attachNewNode('Camera Target')
        base.camera.setPos(self.playerBox.getX(),self.playerBox.getY()+20,self.playerBox.getZ()+5)
        self.cameratarget.setPos(self.playerBox.getX(),self.playerBox.getY(),self.playerBox.getZ()+6)
        self.radius = 10
        self.XYAngle = .028
        self.ZAngle = .01

        ## Set Up Ground Collisions
        ## Player Collision
        base.cTrav = CollisionTraverser()
        self.ColHandler = CollisionHandlerFloor()       
        self.colGroundRay = CollisionNode('colGroundRay')
        self.colGroundRay.addSolid(CollisionRay(0,0,2,0,0,-1))
        self.playerCol = self.playerBox.attachNewNode(self.colGroundRay)
        base.cTrav.addCollider(self.playerCol,self.ColHandler)
        self.ColHandler.addCollider(self.playerCol,self.playerBox)
                                       
        ## Add main Game Loop to taskmanager
        taskMgr.add(self.gameLoop,'mainLoop')
Exemple #8
0
def load(save): # load a game
    import traceback
    try:
        global i
        global previ
        global player
        player = s.load(save, 'player') # load the player
        world.load(s.load(save, 'world')) #load the world
        data = s.load(save, 'game') # retrieve game data
        i = data['turn'] # set current turn
        previ = data['prev. turn'] # set previous turn
    except Exception as e:
        print(f''' Something went wrong :(
=========================
Please report this at https://github.com/TBBYT/Turn-Based-Game/issues
Error:''')
        traceback.print_exc()
        input('Press ENTER to quit to title')
def firstLoad():
    if player.load() == False:
        debug("#Player#")
        create_character()
        player.Health = player.MaxHealth
    if world.load() == False:
        debug("#World#")
        world.Turn = 1
        TN1_R1()
def game_loop():
    game_started = False

    while not game_started:
        user_input = input('New game(1)\nLoad game (2)\n')

        if user_input == '1':
            world.create_world(10)
            player_pos = world.spawn_player()
            game_started = True
            logger.warning('New game started')
        elif user_input == '2':
            try:
                player_pos = world.load()
                game_started = True
                logger.warning('Game loaded')
            except RuntimeError as error:
                logger.warning(error)

    won = False
    lose = False
    while not (won or lose):
        if world.is_trap_around(player_pos):
            logger.warning('There is a trap within one square from you!')
        else:
            logger.warning('No traps around.')
        if world.is_treasure_around(player_pos):
            logger.warning('There is a treasure within one square from you!')
        else:
            logger.warning('No treasures around.')

        input_is_valid = False
        while not input_is_valid:
            logger.warning(
                'Your move (w/a/s/d)? (Input \'save\' to save game)')
            user_input = input()

            input_is_valid = True
            if user_input in directions.keys():
                world.move_player(player_pos, directions[user_input])
            elif user_input == 'save':
                world.save(player_pos)
                logger.warning('Game saved.')
            else:
                logger.warning('Invalid input. Try again.')
                input_is_valid = False

        won = world.is_found_treasure(player_pos)
        lose = world.is_trapped(player_pos)

    if won:
        logger.warning('You won!')
    else:
        logger.warning('You lose!')

    world.print_world(player_pos)
Exemple #11
0
 def load_world(self, world_name):  # manually
     self.world = world.load(world_name)
     api.world = self.world
     if (self.player.nickname in self.world.players):
         player_dict = self.world.players[self.player.nickname]
         self.player.from_dict(player_dict)
         self.world.objects[self.player.uuid] = self.player
     else:
         self.world.add_player(self.player)
     self.calc_fov()
Exemple #12
0
def load_menu_world_data():
    path = "res/worlds"
    if not os.path.exists(path):
        os.makedirs(path)
    possible_loads = os.listdir(path)  # Get filenames
    commons.WORLD_SAVE_OPTIONS = []
    for i in range(len(possible_loads)):
        if possible_loads[i][-3:] == "dat":  # if it's a dat file
            world.load(possible_loads[i][:-4], load_all=False)

            world_data_surf = pygame.Surface((315, 60))
            world_data_surf.fill((50, 50, 50))
            pygame.draw.rect(world_data_surf, (60, 60, 60),
                             Rect(0, 0, 315, 60), 4)

            world_data_surf.blit(
                shared_methods.outline_text(world.world.name, (255, 255, 255),
                                            commons.DEFAULTFONT),
                (5, 3))  # name
            world_data_surf.blit(
                shared_methods.outline_text("Created: ", (255, 255, 255),
                                            commons.DEFAULTFONT),
                (5, 20))  # Creation date
            world_data_surf.blit(
                shared_methods.outline_text("Playtime: ", (255, 255, 255),
                                            commons.DEFAULTFONT),
                (5, 40))  # Playtime
            world_data_surf.blit(
                shared_methods.outline_text(
                    world.world.get_creation_date_string(), (230, 230, 0),
                    commons.DEFAULTFONT), (80, 20))  # Creation date
            world_data_surf.blit(
                shared_methods.outline_text(
                    str(int((world.world.play_time / 60) // 60)) + ":" +
                    str(int(world.world.play_time // 60 % 60)).zfill(2) + ":" +
                    str(int(world.world.play_time % 60)).zfill(2),
                    (230, 230, 0), commons.DEFAULTFONT), (90, 40))  # playtime

            world_data_surf.blit(surface_manager.misc_gui[10], (260, 7))

            commons.WORLD_SAVE_OPTIONS.append(
                [world.world.name, world_data_surf])
Exemple #13
0
def new_game():
    # Get their save name
    display.clear()
    display.flushinp()
    inpt = display.getch()
    curs_loc = 0
    file_name = ""

    display.printc(30, 9, "Enter your name:")
    while inpt != 10: # Until ENTER pressed
        if inpt == 8: # Backspace
            if curs_loc != 0:
                curs_loc -= 1
                file_name = file_name[:-1] # Remove last character
            display.printc(curs_loc + 30, 10, ' ')
        elif (inpt != -1) and (curs_loc < 45) and (chr(inpt) in "abcdefghijklmnopqrtsuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-1234567890 "): # Also don't let them get too long. 45 chosen arbitrarily because yeah.
            display.printc(curs_loc + 30, 10, chr(inpt))
            file_name += chr(inpt)
            curs_loc += 1
        display.refresh()
        inpt = display.getch()
    # Wait for release
    while display.keyDown(display.CONST.VK_RETURN):
        pass
    if file_name == len(file_name) * ' ':
        file_name = "default"
    world.save_name = file_name
    # Class select!
    # What color each class should be
    color_list = [display.RED, display.BLUE, display.YELLOW]
    # What the middle text is for each class
    text_list = ["+  Warrior   +", "+    Mage    +", "+   Thief    +"]
    # The box of '+'s top and bottom
    box = '+' * 14

    # Number of rows each box takes up. 3 for the box + 2 for the space below
    box_size = 5
    # Where the boxes start display on y-axis
    box_start = 4
    # Left side of boxes
    box_left = 32
    # Clear screen and set up menu.
    display.clear()
    for i in range(len(text_list)):
        display.printc(box_left, box_start + i * box_size, box)
        display.printc(box_left, box_start + i * box_size + 1, text_list[i])
        display.printc(box_left, box_start + i * box_size + 2, box)

    # Draw first box in color
    display.printc(box_left, box_start, box, color_list[0])
    display.printc(box_left, box_start + 1, text_list[0], color_list[0])
    display.printc(box_left, box_start + 2, box, color_list[0])

    choice = 0;
    
    
    display.refresh()
    while True:
        # Check for choice down/up
        if display.keyDown(ord('Q')) or display.keyDown(display.CONST.VK_UP):
            # Redraw current box in white
            display.printc(box_left, box_start + choice * box_size, box)
            display.printc(box_left, box_start + choice * box_size + 1, text_list[choice])
            display.printc(box_left, box_start + choice * box_size + 2, box)
            # If decrementing choice would bring it below zero, set it to one past last
            if choice == 0:
                choice = len(text_list)
            # And decrement it.
            choice -= 1

            # Redraw new box in correct color.
            display.printc(box_left, box_start + choice * box_size, box, color_list[choice])
            display.printc(box_left, box_start + choice * box_size + 1, text_list[choice], color_list[choice])
            display.printc(box_left, box_start + choice * box_size + 2, box, color_list[choice])
            # Refresh display
            display.refresh()
            # Wait for release
            while display.keyDown(ord('Q')) or display.keyDown(display.CONST.VK_UP):
                pass
        if display.keyDown(ord('E')) or display.keyDown(display.CONST.VK_DOWN):
            # Redraw current box in white
            display.printc(box_left, box_start + choice * box_size, box)
            display.printc(box_left, box_start + choice * box_size + 1, text_list[choice])
            display.printc(box_left, box_start + choice * box_size + 2, box)
            # Go down
            choice += 1
            # Wrap options
            if choice == len(text_list):
                choice = 0
            # Redraw new box in correct color.
            display.printc(box_left, box_start + choice * box_size, box, color_list[choice])
            display.printc(box_left, box_start + choice * box_size + 1, text_list[choice], color_list[choice])
            display.printc(box_left, box_start + choice * box_size + 2, box, color_list[choice])
            # Refresh display
            display.refresh()
            # Wait for release
            while display.keyDown(ord('E')) or display.keyDown(display.CONST.VK_DOWN):
                pass

        # Check if they chose an option
        if display.keyDown(display.CONST.VK_RETURN):
            # Basic player. Choice will modify it's attributes.
            world.player = player.player(world.WORLD_X // 2, world.WORLD_Y - 3)

            hat =    start_eq.start_hat()
            shirt =  start_eq.start_shirt()
            pants =  start_eq.start_pants()
            weapon = start_eq.start_weapon()
            ring =   start_eq.start_ring()
            sp = spell.spell(heal.manaCost, heal.heal, heal.name, heal.icon, heal.color)
            pclass = ""
            if not choice: # Choice was 0, so warrior
                pclass = "warrior"
            if choice == 1: # Choice was Mage
                pclass = "mage"
            if choice == 2: # Choice was Thief
                pclass = "thief"

            world.player.attributes["class"] = pclass
            world.player.attributes["items"] = [hat, shirt, pants, ring, weapon, sp] # Give them their equips
            world.player.attributes["hat"] = hat
            hat.equip(world.player)
            world.player.attributes["shirt"] = shirt
            shirt.equip( world.player)
            world.player.attributes["pants"] = pants
            pants.equip(world.player)
            world.player.attributes["ring"] = ring
            ring.equip(world.player)
            world.player.attributes["weapon"] = weapon
            weapon.equip(world.player)
            world.player.attributes["spell"] = sp
            

            # Load starting world
            world.load("tutorial.start")
            world.objects = [world.player] + world.objects
            return
Exemple #14
0
    pyglet.text.Label('y',
                      x=window.width - 10,
                      y=window.height - 70,
                      anchor_x='right',
                      anchor_y='top',
                      font_name='consolas',
                      font_size=15,
                      batch=hud_batch)
}

# follows the player's sprite
camera = camera.Camera(window, player.sprite)
window.push_handlers(camera)

#loaded_world = world.load('default_world')
loaded_world = world.load('gigamir')
#loaded_world = world.World(width=512, height=512)

api.game_world = loaded_world

loaded_world.objects[player.uuid] = player
loaded_world.spawn(2, 2, 'test:zombie')


def gen_vertex(x=0, y1=0):
    vertex_data = []
    texture_data = []
    for i in range(loaded_world.height):
        y2 = y1 + api.TILE_WIDTH
        x1 = x
        for j in range(loaded_world.width):
Exemple #15
0
        CLIENTS[addr] = data
        print "%s %s" % (addr, data)
        cmd_args = data.split(':', 1)
        cmd = cmd_args[0]
        if cmd not in ('save', 'load'):
            args = cmd_args[1]
        if cmd == 'connect':
            CLIENTS[addr] = args
            print '%s connected' % args
            start = 'world:' + world.get_all()
            s.sendto(start, addr)
        elif cmd == 'move':
            world.update_player(args)
            for client in CLIENTS:
                if addr == client: continue
                s.sendto(data, client)
        elif cmd == 'update':
            world.update(args)
            # naively echo to all other clients
            for client in CLIENTS:
                if addr == client: continue
                s.sendto(data, client)
        elif cmd == 'save':
            world.save()
        elif cmd == 'load':
            # Any clients that are connected now disagree with the server.
            world.load()
finally:
    print 'Goodbye world'
    s.close()
Exemple #16
0
    def update(this, delta_time):
        # Movement code
        if not ("mov_del" in this.attributes["effects"]):
            diffX = this.X - world.player.X  # How much it needs to move left to hit player
            diffY = this.Y - world.player.Y  # How much it needs to move down to hit player
            if diffX < 0:
                this.X += 1
            else:
                this.X -= (not not diffX)  # Should give either 1 or 0.
            if diffY < 0:
                this.Y += 1
            else:
                this.Y -= (not not diffY)
            # Add boundary checking
            if this.X == 0:  # Left side
                this.X += 1
            if this.X == world.WORLD_X - 1:  # Right side
                this.X -= 1
            if this.Y == 0:  # Top
                this.Y += 1
            if this.Y == world.WORLD_Y - 1:  # Bottom
                this.Y -= 1
            this.attributes["effects"]["mov_del"] = effect.effect(
                this, this.attributes["mov_spd"])
        # Attack code
        this.attributes["to_atk"] -= delta_time
        if this.attributes["to_atk"] <= 0:
            this.attributes[
                "to_atk"] = this.attributes["atk_spd"] - 200 + this.attributes[
                    "HP"]  # He attacks faster with less HP
            # Find which direction to shoot
            diffX = world.player.X - this.X  # How much it needs to move left to hit player
            diffY = world.player.Y - this.Y  # How much it needs to move down to hit player
            if diffX < 0:
                diffX = -1
            else:
                diffX = int(not not diffX)
            if diffY < 0:
                diffY = -1
            else:
                diffY = int(not not diffY)
            world.objects.append(
                attack.boss_attack(this.X + diffX, this.Y + diffY, diffX,
                                   diffY, this.attributes["damage"],
                                   this.attributes["range"], 250, this))

        # Update all effects.
        eff_del_list = []
        for eff_name in this.attributes["effects"]:
            eff = this.attributes["effects"][eff_name]
            eff.tick(delta_time)  # Tick effect
            if eff.time <= 0:  # Remove effect
                eff_del_list.append(eff_name)
        for eff_name in eff_del_list:
            this.attributes["effects"][eff_name].uneffect(this)
            del this.attributes["effects"][eff_name]
        del eff_del_list

        if this.attributes["HP"] <= 0:
            this.die()
            world.load("tutorial.boss-killed")
            world.objects = [world.player] + world.objects
            world.player.X = 10
            world.player.Y = 10
            world.dispworld()
            return True
Exemple #17
0
	def load_world(self, name):
		self.world = world.load(name)
		api.world = self.world
Exemple #18
0
def run_map(map_name, pipe):
    try:
        display.init_logger(map_name)
        world.load(map_name.split(';')[0]) # Only load everything before first ;
        world.world_name = map_name
        display.log("Map started")
        start_time = time.clock()
        since_start = 0

        time_until_messages = 0 # How many ms before we send out messages again. Let's not overload the client
        # We handle messages before entering the loop to avoid a race condition as
        #  the map is started before any message is sent (as not to overflow pipe's buffer)
        handle_messages(pipe)
        while True:
            # Calculate delta time
            delta_time = int((time.clock() - start_time) * 1000) - since_start
            if delta_time > 100:
                display.log("Capped tick at " + str(delta_time) + "ms. " + str(len(world.objects)) + "objects, "+ str(len(world.players)) + " players total")
                delta_time = 100
            delta_time = max(0, delta_time) # Don't have ticks with negative time!
            since_start += delta_time
            time_until_messages -= delta_time
            print(delta_time, " ", end="\r")

            # If there are messages, handle them.
            if (pipe.poll()):
                if handle_messages(pipe):
                    display.end_logger()
                    return

            world.to_del.clear()
            world.to_del_plr.clear()

            continue_loop = False
            # Update objects
            obj_update_list = world.players + world.objects


            for index in range(len(obj_update_list)):
                obj = obj_update_list[index]

                # Update it
                obj.update(delta_time)

                if obj.type != "player": # Don't check player collisions as they can only collide with other players.
                    for coll in obj_update_list[:index]:    # Check for collision
                        if coll.X == obj.X and coll.Y == obj.Y:
                            obj.collide(coll) # Call collisions
                            coll.collide(obj)

                #Check if out of bounds
                if world.out_of_bounds(obj.X, obj.Y):
                    world.to_del.append(obj)

                if obj.blocks_map_exit:
                    continue_loop = True

            # Delete objects that need to be deleted.
            for obj in set(world.to_del): # Set to remove duplicates
                world.objects.remove(obj)


            # Remove players that left
            for plr in set(world.to_del_plr):
                world.save_player(plr)
                world.players.remove(plr)

            # Handle move requests.
            for req in world.move_requests:
                pipe.send(("mov", req)) # Send request
            world.move_requests.clear()

            if time_until_messages <= 0:
                # Send data to players.
                send_data = {"type" : "update", "tiles" : []}

                for obj in world.objects + world.players:
                    if obj.char() != '\0':
                        send_data["tiles"].append({"color" : obj.color(), "chr" : obj.char(), "x": obj.X, "y": obj.Y})

                # Send update to all players
                for plr in world.players:
                    try:
                        if plr.attributes["using_inv"]:
                            pass # TODO: what now?
                        else:
                            plr.attributes["pipe"].send(JSON.dumps(send_data))
                            plr.send_extra_data()
                    except Exception as ex:
                        pass
                time_until_messages = 16 # Reset time

            if not continue_loop: # Nothing blocking.
                pipe.send(("end", ))
                display.log("Ending map")
                display.end_logger()
                while pipe.recv() != ("end",): # Wait for acknowledge of end.
                    pass
                return


    except Exception as ex:
        pipe.send(("end", ))
        display.log("Ending map due to error!")
        display.log(str(traceback.format_exc()))
        display.end_logger()
        while pipe.recv() != ("end",): # Wait for acknowledge of end.
            pass
        return
Exemple #19
0
import world
import json

from Strategy.srv import ListRequest, ListResponse  "==> format of .srv file ==> string name #name of commmand e.g. give me list
                                                    "                            ------------ 
                                                    "                            string name #return list, 
                                                    "                                         this probably won't be a string?
from std_msgs.msg import String

with open("scenario_file.yaml") as file:
    
    scenario = yaml.load(file)
    
with open("environment file.world") as file:
    
    environment = world.load(file)
    
class TropyList:
    def __init__(self):
        self.location_trophies = "info from scenario file"
        
        
    def get_list(self, req):
        rospy.loginfo('List requested')
         #Create list
         #Info from scenario file is already a list
         
        
        response = ListResponse()
        return response