示例#1
0
def load(file_in):
    messages.colorBackground()
    file_descriptor = open(file_in)
    lines = file_descriptor.readlines()
    global rows, cols
    rows = len(lines) - 1
    cols = len(lines[-1])

    if settings[GENERATE_RANDOM_MAP]:
        messages.say('generating random terrain', down=5)
        randomlymodify(lines)
        for line in lines:
            print line[:cols]

    file_descriptor.close()
    tiles = []
    for c in range(cols):
        tiles.append([])
        for r in range(rows):
            # Essentially we used the character (e.g. 'Q') to access the
            # dictionary entries (which are Tile object instances)
            tiles[c].append(tile.tile[lines[r][c]])
            # Notice that there is a transposition here.

    return Room(tiles, lines)
示例#2
0
def prepareRandomLevel(screen, cols=0, rows=0):
    messages.colorBackground()
    if not cols:
        cols = int(getChoiceUnbounded("Room width?", [str(x) for x in range(30, 61, 5)]))
    if not rows:
        rows = int(getChoiceUnbounded("Room height?", [str(x) for x in range(20, 61, 5)]))
    room.globalize_dimensions(rows, cols)

    lines = [" " * cols for x in range(rows + 1)]
    room.randomlymodify(lines)
    tiles = []
    for c in range(cols):
        tiles.append([])
        for r in range(rows):
            tiles[c].append(tile.tile[lines[r][c]])
    r = room.Room(tiles, lines)
    graphics.extract_dimensions(lines)

    world = pygame.Surface((graphics.world_w, graphics.world_h))
    t = topbar.TopBar(screen)
    test.mark(r.background)
    r.topbar = t
    return world, t, r
示例#3
0
    def modify_setting(self):
        if self.setting in want_bools:
            settings[self.setting] = not settings[self.setting]
        elif self.setting in want_ints and self.setting in max_val and self.setting in min_val:
            settings[self.setting] += 1
            if settings[self.setting] > max_val[self.setting]:
                settings[self.setting] = min_val[self.setting]
        else:
            messages.colorBackground()
            # messages.say("Pick a new value", down = 4)

            allowed_keys = range(
                pygame.K_0, pygame.K_9 + 1)
            allowed_keys += [pygame.K_PERIOD]
            allowed_keys += [pygame.K_e]
            allowed_keys += [pygame.K_MINUS]

            '''loop is for error checking'''
            while True:
                # message = messages.smallfont.render("Set new value for '%s'" % toChange, 1, [255, 255, 255])
                # pygame.display.get_surface().blit(message, (600, 15 * (usedindex + 3)))
                m = "Set new value for '%s'" % self.setting
                position = pygame.Rect(0, 0, 290, 30)
                # position.x = 600 #Leaning right
                position.centerx = graphics.screen_w / 2
                # position.y = 15 * (usedindex + 4.3)
                # Leaning up
                position.centery = graphics.screen_h / 2
                out = getString(
                    allowed_keys, str(settings[self.setting]), textpos=position, message=m)
                # out = getString(allowed_keys, str(settings[toChange]))

                # quit
                if out == -1:
                    break

                # cancel
                elif out == 0:
                    break

                try:
                    val = 0
                    if "." in out:
                        val = float(out)
                    else:
                        val = int(out)

                    problems = problem_with_setting(
                        self.setting, val)
                    if problems:
                        messages.colorBackground()
                        messages.say(problems, down=4)
                        continue

                    settings[self.setting] = val
                    break

                except:
                    messages.colorBackground()
                    messages.say(
                        "Error. Pick a new value", down=4)

            save_settings()
        self.needs_update = True
示例#4
0
def getChoiceBounded(title, given_options, allowcancel=False):
    '''Prompts you to choose one of the options. If the user clicks outside the box this returns None.'''

    options = given_options[:]
    if allowcancel:
        options.append("cancel")

    disp = pygame.display.get_surface()
    bg = pygame.Surface((disp.get_width(), disp.get_height()))
    bg.blit(disp, (0, 0))

    clock = pygame.time.Clock()
    currpos = 0
    updateview = 1

    hborder = 15

    optiondisplay = pygame.Surface(
        (min(300, graphics.screen_w - 2 * hborder), min(15 * (len(options) + 3), graphics.screen_h - 2 * hborder)))
    selectionimage = pygame.Surface(
        (optiondisplay.get_width() - 10, 50), flags=pygame.SRCALPHA)

    box = pygame.Rect((0, 0), (selectionimage.get_width(), 15))
    pygame.draw.rect(selectionimage, graphics.outline, box, 1)

    smallsteps = 0
    slowness = 6

    previous_key_states = []
    wet = 0

    oldxy = (-1, -1)

    # lean right
    # dest = optiondisplay.get_rect(right = graphics.screen_w - 15, top = 15)
    dest = optiondisplay.get_rect(
        centerx=graphics.screen_w / 2, centery=graphics.screen_h / 2)

    # list out options
    messages.colorBackground(surface=optiondisplay)
    messages.say(title, surface=optiondisplay, size="small")
    messagecount = 1
    for choice in options:
        messagecount = messages.say(
            choice, down=messagecount, surface=optiondisplay, size="small")

    while True:
        if pygame.event.get(pygame.QUIT):
            print "quit from getChoiceUnbounded"
            global time_to_quit
            time_to_quit = True
            return "quit"
        clicks.get_more_clicks()
        wet += 1

        x, y = pygame.mouse.get_pos()

        if oldxy != (x, y):
            oldxy = x, y
            i = (y - dest.y - 5) / 15 - 2
            if 0 <= i < len(options):
                if dest.left < x < dest.right and i != currpos:
                    currpos = i
                    updateview = 1

        if updateview:
            '''messages.colorBackground(surface = optiondisplay)
            messages.say(title, surface = optiondisplay, size = "small")
            messagecount = 1
            for choice in options:
                    messagecount = messages.say(choice, down = messagecount, surface = optiondisplay, size = "small")'''
            disp = pygame.display.get_surface()

            optionx = hborder
            optiony = graphics.screen_h - 15 * (len(options) + 4)
            optionpos = optionx, optiony

            # make it top right
            # center the options
            #dest = optiondisplay.get_rect(centerx = graphics.screen_w / 2, centery = graphics.screen_h / 2)

            disp.blit(optiondisplay, dest, special_flags=0)

            disp.blit(selectionimage, (dest.x + 5, dest.y + 35 + currpos * 15))

            # pygame.display.flip()
            pygame.display.update(dest)
            updateview = 0

        if clicks.mouseups[0]:
            oldxy = x, y
            i = (y - dest.y - 5) / 15 - 2
            if 0 <= i < len(options) and dest.left < x < dest.right:
                disp.blit(bg, (0, 0))
                return options[currpos]
            elif allowcancel:
                disp.blit(bg, (0, 0))
                return "cancel"

        clock.tick(60)

        '''stupid mac...'''
        #key_presses = pygame.event.get()
        key_states = pygame.key.get_pressed()
        #event = pygame.event.poll()

        # if event.type != pygame.NOEVENT:
        #   print event

        # if event.type == pygame.KEYDOWN and event.key == pygame.K_UP:
        if key_states[pygame.K_UP]:
            smallsteps -= 1
            if smallsteps == 0 or (previous_key_states and not previous_key_states[pygame.K_UP]):
                smallsteps = slowness
                currpos -= 1
                currpos %= len(options)
                updateview = 1

        # if event.type == pygame.KEYDOWN and event.key == pygame.K_DOWN:
        elif key_states[pygame.K_DOWN]:
            smallsteps -= 1
            if smallsteps == 0 or (previous_key_states and not previous_key_states[pygame.K_DOWN]):
                smallsteps = slowness
                currpos += 1
                currpos %= len(options)
                updateview = 1

        elif key_states[pygame.K_RETURN] and (previous_key_states and not previous_key_states[pygame.K_RETURN]):
            disp.blit(bg, (0, 0))
            return options[currpos]

        elif key_states[pygame.K_q]:
            disp.blit(bg, (0, 0))
            return

        previous_key_states = key_states[:]
        pygame.event.pump()
示例#5
0
def handle_player_input(key_presses, key_ups, key_states, gameobjects):
    time_gap = False
    try:
        r = gameobjects["room"]
        p = gameobjects["player"]
        c = gameobjects["camera"]
        world = gameobjects["world"]
        h = gameobjects["hive"]
        screen = gameobjects["screen"]
    except:
        raise Exception("Missing gameobjects. Have following keys:", [key for key in gameobjects])

    clicks.get_more_clicks()
    global time_to_quit
    # Handle player input
    if key_ups[pygame.K_e]:
        if r.bees:
            # for x in r.bees + r.food + [p] + r.bullets:
            #   x.draw(world)
            # c.draw()
            # pygame.display.flip()
            """this is for picking the closest bee"""
            """minbee = r.bees[0]
            for b in r.bees:
                if linalg.norm(b.xy - p.xy) < linalg.norm(minbee.xy - p.xy):
                    minbee = b"""

            minbee = random.choice(r.bees)
            messages.say("Loading", down=1)
            pygame.display.flip()
            minbee.visualize_intelligence(world, c)
            p.displaycolor = [255, 255, 255]
            pygame.draw.circle(world, [0, 0, 0], array(p.xy.astype(int))[0], int(p.forcefield))
            pygame.draw.circle(world, [255, 255, 255], array(p.xy.astype(int))[0], int(p.forcefield), 1)
            p.draw(world)
            # c.xy = minbee.xy * 1
            # c.updatesight()
            c.draw()
            pygame.display.flip()
            minbee.sample_path(world)
            c.draw()
            pygame.display.flip()
            waitForKey(pygame.K_w)
            time_gap = True

    if time_to_quit:
        game_progress.save_game(r)
        return

    test.record()
    world.blit(r.background, (0, 0))
    test.record("blitting background")

    togglers = {pygame.K_r: SHOW_EYES, pygame.K_h: SHOW_HELP, pygame.K_t: GENERATE_RANDOM_MAP, pygame.K_n: SHOW_NAMES}

    for key, variable in togglers.iteritems():
        if key_ups[key]:
            settings[variable] = not settings[variable]

    if key_ups[pygame.K_m]:
        print framecount
        r.madness += 1
        r.madness %= 5
        for b in r.bees:
            b.madness = r.madness

    if key_ups[pygame.K_a]:
        if key_states[pygame.K_UP]:
            p.shoot("up")
        else:
            p.shoot()

    if key_ups[pygame.K_x]:
        r.stasis = not r.stasis

    if key_ups[pygame.K_z]:
        print pygame.mouse.get_pos()

    # gameobjects["info_panel"].handle_event(pygame.mouse.get_pos(), "mouseover")

    """All mouse click stuff"""
    if clicks.mouseups[0]:
        event_taken = False
        if gameobjects["info_panel"].rect.collidepoint(pygame.mouse.get_pos()):
            mx, my = pygame.mouse.get_pos()
            x, y = mx - gameobjects["info_panel"].rect.x, my - gameobjects["info_panel"].rect.y

            event_taken = gameobjects["info_panel"].handle_event((x, y), "click")

        if not event_taken:
            for b in r.bees:
                b.skipupdate = True
            options = [
                "Move to another map",
                "Random 60 x 25",
                "Random 35 x 35",
                "Random 60 x 60",
                "Examine bee",
                "Save bees",
                "Extinction",
                "Load bees",
                "Delete bees",
                "Tweak variables",
                "Modify map",
                "View Shortcuts",
                "quit",
            ]
            choice = getChoiceUnbounded("select option", options, allowcancel=1)

            if choice != "cancel":
                if choice == "quit":
                    time_to_quit = True

                elif choice in ["Move to another map", "Random 60 x 25", "Random 35 x 35", "Random 60 x 60"]:
                    level = choice
                    if choice == "Move to another map":
                        level = enteredlevel()
                    if level == "quit":
                        time_to_quit = True

                    if level != "cancel":
                        print "MAGIC LEVEL MOVE WHOA"
                        gameobjects2 = {}
                        gameobjects2["room"] = r
                        gameobjects2["player"] = p
                        gameobjects2["hive"] = h
                        gameobjects2["camera"] = c
                        gameobjects2["world"] = world
                        gameobjects2["screen"] = screen

                        move_to_level(level, gameobjects2)

                        try:
                            r = gameobjects2["room"]
                            p = gameobjects2["player"]
                            c = gameobjects2["camera"]
                            world = gameobjects2["world"]
                            h = gameobjects2["hive"]
                            screen = gameobjects2["screen"]
                        except:
                            raise Exception("Missing gameobjects. Have following keys:", [key for key in gameobjects])

                elif choice == "Extinction":
                    if getChoiceUnbounded("Kill all bees?", ["no", "yes"], allowcancel=1) == "yes":
                        for b in r.bees:
                            b.health = -20
                        for b in r.bees + r.deadbees:
                            b.dead = 2
                        t.data = []

                elif choice == "Examine bee":
                    """this thing lets you examine the closest bee to you"""
                    if r.bees:
                        minbee = r.bees[0]
                        for b in r.bees:
                            if linalg.norm(b.xy - p.xy) < linalg.norm(minbee.xy - p.xy):
                                minbee = b
                        for x in r.bees + r.food + [p] + r.bullets:
                            x.draw(world)
                        c.draw()
                        pygame.display.flip()

                        while not time_to_quit:  # quit should work fine here
                            choice = getChoiceUnbounded(
                                "Examining nearest bee...what feature?",
                                ["Neural Network", "Movement"],
                                allowcancel=True,
                            )

                            if choice == "Neural Network":
                                command = minbee.show_brain(world)
                                if command:
                                    return

                            elif choice == "Movement":
                                c.draw()
                                messages.say("Loading", down=1)
                                pygame.display.flip()
                                minbee.visualize_intelligence(world, c)
                                minbee.sample_path(world)
                                c.draw()
                                pygame.display.flip()

                            elif choice == "cancel":
                                done = 1
                                break

                            elif choice == "quit":
                                time_to_quit = True

                elif choice == "Save bees":
                    beemap = {}
                    beenames = []

                    for b in r.bees:
                        label = b.firstname + " " + b.name
                        beemap[label] = b
                        beenames.append(label)

                    choice = getChoiceUnbounded("Pick a bee", beenames, allowcancel=True)

                    if choice == "quit":
                        time_to_quit = True

                    elif choice != "cancel":
                        b = beemap[choice]
                        # messages.colorBackground()
                        # messages.say("Pick a new name for the bee", down = 4)
                        rename = b.name
                        """loop is for error checks"""
                        while not time_to_quit:
                            rename = getString(string=b.name, message="Pick a new name for the bee")

                            # quit
                            if rename == -1:
                                break
                            # cancel
                            elif rename == 0:
                                break
                            elif any(specimen[0] == rename for specimen in h.specimens):
                                messages.colorBackground()
                                messages.say("Name taken. Pick a new name for the bee", down=4)
                                continue
                            else:
                                b.name = rename
                                break
                        h.save_bee(b)
                        h.savedata()

                elif choice == "Load bees":
                    loadedbeenames = []
                    for b in h.specimens:
                        loadedbeenames.append(b[0])

                    loadedbeenames.append("done")
                    loadedbeenames = loadedbeenames[-1::-1]
                    i = 0
                    while not time_to_quit:
                        name = getChoiceUnbounded("Loaded " + str(i) + " bees", loadedbeenames, allowcancel=True)
                        if name in ["done", "quit", "cancel"]:
                            break
                        else:
                            i += 1
                            b = h.make_bee(name, r, p)
                            r.bees.append(b)
                            b.flash = 50
                            b.xy[0, 0] = p.xy[0, 0]

                elif choice == "Delete bees":
                    i = 0
                    message = "Choose a bee to delete"
                    while not time_to_quit:
                        indexfromname = {}
                        loadedbeenames = []
                        for index, b in enumerate(h.specimens):
                            name = b[0]
                            loadedbeenames.append(name)
                            indexfromname[name] = index
                        loadedbeenames.append("done")
                        loadedbeenames = loadedbeenames[-1::-1]

                        if i:
                            message = "Deleted " + str(i) + " bees"
                        name = getChoiceUnbounded(message, loadedbeenames, allowcancel=True)
                        if name in ["quit", "done", "cancel"]:
                            break
                        else:
                            confirm = getChoiceUnbounded("Delete %s?" % name, ["no", "yes"], allowcancel=True)
                            if confirm != "yes":
                                continue
                            i += 1
                            indextoremove = indexfromname[name]
                            h.specimens = h.specimens[:indextoremove] + h.specimens[(indextoremove + 1) :]

                elif choice == "Tweak variables":
                    families = game_settings.families

                    """picking kinds of variables"""
                    while not time_to_quit:
                        family = getChoiceUnbounded("What kind of variable?", families.keys(), allowcancel=1)
                        if family == "cancel":
                            break

                        """picking variable"""
                        while not time_to_quit:
                            """takes "name: value" string to "name"."""
                            label_to_key = {key + ": " + str(settings[key]): key for key in families[family]}

                            """this is a bunch of informative labels"""
                            options = [x for x in sorted(label_to_key.keys())]

                            toChange = getChoiceUnbounded("Pick a variable to modify", options, allowcancel=1)

                            if toChange == "cancel":
                                break
                            toChange = label_to_key[toChange]
                            if toChange in want_bools:
                                settings[toChange] = not settings[toChange]
                                continue
                            elif toChange in want_ints and toChange in max_val and toChange in min_val:
                                settings[toChange] += 1
                                if settings[toChange] > max_val[toChange]:
                                    settings[toChange] = min_val[toChange]
                                continue
                            else:
                                """we have the name of the variable we want to change now"""

                                usedindex = 0
                                for i, entry in enumerate(options):
                                    if entry == toChange:
                                        usedindex = i

                                # messages.colorBackground()
                                # messages.say("Pick a new value", down = 4)

                                allowed_keys = range(pygame.K_0, pygame.K_9 + 1)
                                allowed_keys += [pygame.K_PERIOD]
                                allowed_keys += [pygame.K_e]
                                allowed_keys += [pygame.K_MINUS]

                                """loop is for error checking"""
                                while not time_to_quit:
                                    # message = messages.smallfont.render("Set new value for '%s'" % toChange, 1, [255, 255, 255])
                                    # pygame.display.get_surface().blit(message, (600, 15 * (usedindex + 3)))
                                    m = "Set new value for '%s'" % toChange
                                    position = pygame.Rect(0, 0, 290, 30)
                                    # position.x = 600 #Leaning right
                                    position.centerx = graphics.screen_w / 2
                                    # position.y = 15 * (usedindex + 4.3)
                                    # Leaning up
                                    position.centery = graphics.screen_h / 2
                                    out = getString(allowed_keys, str(settings[toChange]), textpos=position, message=m)
                                    # out = getString(allowed_keys, str(settings[toChange]))

                                    # quit
                                    if out == -1:
                                        break

                                    # cancel
                                    elif out == 0:
                                        break

                                    try:
                                        val = 0
                                        if "." in out:
                                            val = float(out)
                                        else:
                                            val = int(out)

                                        problems = problem_with_setting(toChange, val)
                                        if problems:
                                            messages.colorBackground()
                                            messages.say(problems, down=4)
                                            continue

                                        settings[toChange] = val
                                        break

                                    except:
                                        messages.colorBackground()
                                        messages.say("Error. Pick a new value", down=4)

                                save_settings()

                                # for key, value in settings.iteritems():
                                #   print key + ":", str(value)
                        if family == "quit" or time_to_quit:
                            time_to_quit = True
                            break

                elif choice == "Modify map":
                    messages.colorBackground()
                    messages.say("This is where I would modify the map", 500)

                elif choice == "View Shortcuts":
                    messages.colorBackground()
                    messagecount = 2
                    if settings[SHOW_EYES]:
                        messagecount = messages.say("[r]: Hide eyes", down=messagecount)
                    else:
                        messagecount = messages.say("[r]: Show eyes", down=messagecount)

                    if r.madness:
                        messagecount = messages.say("[m]: Don't draw trails", down=messagecount)
                    else:
                        messagecount = messages.say("[m]: Draw trails", down=messagecount)

                    if settings[GENERATE_RANDOM_MAP]:
                        messagecount = messages.say("[t]: Don't randomize maps when loading", down=messagecount)
                    else:
                        messagecount = messages.say("[t]: Randomize maps when loading", down=messagecount)

                    if r.stasis:
                        messagecount = messages.say("[a]: Resume deaths and births", down=messagecount)
                    else:
                        messagecount = messages.say("[a]: Pause deaths and births", down=messagecount)

                    messagecount = messages.say("[e]: Examine a random bee", down=messagecount)

                    messagecount = messages.say("Click anywhere to continue", down=messagecount)
                    waitForEnter(hidemessage=1)

            if time_to_quit:
                print "Saving game very rapidly, whee"
                game_progress.save_game(r)
                return

            screen.fill(graphics.background)
            # This is to trick the computer into thinking no time has passed
            time_gap = True
    gameobjects["player"] = p
    gameobjects["room"] = r
    gameobjects["world"] = world
    gameobjects["camera"] = c
    gameobjects["screen"] = screen
    gameobjects["hive"] = h
    return time_gap