コード例 #1
0
ファイル: room.py プロジェクト: yeahpython/bees-bees-bees
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
ファイル: ui.py プロジェクト: yeahpython/bees-bees-bees
def waitForEnter(hidemessage=0):
    if not hidemessage:
        messages.say("Press [enter] to continue", down=1)
    pygame.display.flip()
    clock = pygame.time.Clock()
    while True:
        clock.tick(60)
        if pygame.event.get(pygame.QUIT):
            global time_to_quit
            time_to_quit = True
            break

        clicks.get_more_clicks()
        if clicks.mouseups[0]:
            break
        key_states = pygame.key.get_pressed()
        if key_states[pygame.K_RETURN]:
            break
コード例 #3
0
ファイル: ui.py プロジェクト: yeahpython/bees-bees-bees
def waitForKey(key, message=0):
    if message:
        messages.say(message, down=1)
    else:
        print "saying Press " + pygame.key.name(key) + " to exit"
        print "graphics.outline is", graphics.outline
        messages.say("Press " + pygame.key.name(key) + " to exit", down=1)
    pygame.display.flip()
    clock = pygame.time.Clock()
    while not pygame.event.get(pygame.QUIT):
        clock.tick(60)
        key_states = pygame.key.get_pressed()
        if key_states[key]:
            break
        if pygame.event.get(pygame.QUIT):
            global time_to_quit
            time_to_quit = True
            break
        pygame.event.pump()
コード例 #4
0
ファイル: brain.py プロジェクト: yeahpython/bees-bees-bees
    def visualize(self, surface):
        background = pygame.Surface((graphics.screen_w, graphics.screen_h))
        background.fill((0, 0, 0))

        tosay = [
            "left / right: turn around",
            "up / down: move around",
            "z: zoom out",
            "x: zoom in",
            "c: reset zoom",
            "s: toggle negatives",
            "l: toggle lines",
            "p: toggle physics simulation",
            "q: quit",
            "o: back"
        ]

        for i, message in enumerate(tosay):
            messages.say(message, time=0, down=i, surface=background, color=[
                         255, 255, 255], size="small")

        hscale = 700 / 4
        vscale = 30
        hoff = 100
        voff = 100
        sf = pygame.display.get_surface()
        locations = {}
        velocities = {}
        scalefactor = 1
        translation = matrix([0, 0, 0])
        rotation = 0
        for i, layer in enumerate(self.nodes):
            for j in range(layer.shape[1]):
                #locations[(i,j)] = matrix([i*hscale + hoff, j*vscale + voff])
                locations[(i, j)] = matrix(
                    [i * 200, j * 10,  random.random() * 10 - 5])
                theta = random.random() * 2 * 3.1415926
                velocities[
                    (i, j)] = 0.1 * matrix([math.cos(theta), math.sin(theta), random.random() * 2 - 1])

        self.drawfromlocationtable(locations, sf, 1, translation)
        #pygame.draw.circle(sf, (0, 255, 255), (100, 100), int(50 * random.random()) + 10, 1)

        clock = pygame.time.Clock()
        done = 0
        currmax = self.evaluate(locations)
        n = 0
        simulatephysics = True
        scalerate = 1.3
        #a = raw_input('type "1" for low res, "2" for high res \n')
        shownegatives = 1
        showlines = 0
        quit = 0
        previous_key_states = []
        key_downs = []

        consecutive_no_improvement = 0

        while not (done or pygame.event.get(pygame.QUIT)):
            n += 1
            clock.tick(60)
            key_presses = pygame.event.get(pygame.KEYDOWN)
            key_states = pygame.key.get_pressed()

            if previous_key_states:
                key_downs = [
                    new and not old for new, old in zip(key_states, previous_key_states)]
            else:
                previous_key_states = [0 for key in key_states]
                key_downs = [0 for key in key_states]

            if key_states[pygame.K_q]:
                quit = 1
                done = 1

            if key_downs[pygame.K_s]:
                shownegatives = not shownegatives

            if key_downs[pygame.K_p]:
                simulatephysics = not simulatephysics

            if key_downs[pygame.K_l]:
                showlines = not showlines

            stepsize = 100

            moving = False
            if key_states[pygame.K_z]:
                moving = True
                scalefactor *= scalerate
                avelocs(locations, scalefactor)

            if key_states[pygame.K_x]:
                moving = True
                scalefactor /= scalerate
                avelocs(locations, scalefactor)

            if key_downs[pygame.K_c]:
                moving = True
                scalefactor = 1.0
                translation *= 0

            if key_states[pygame.K_UP]:
                moving = True
                translation[0, 1] -= stepsize
                avelocs(locations, scalefactor)

            if key_states[pygame.K_DOWN]:
                moving = True
                translation[0, 1] += stepsize
                avelocs(locations, scalefactor)

            pi = 3.1415926

            if key_states[pygame.K_LEFT]:
                moving = True
                rotation += 0.05 * pi

                #translation[0,0] -= stepsize
            if key_states[pygame.K_RIGHT]:
                moving = True
                rotation -= 0.05 * pi

            if simulatephysics and not moving:
                '''
                # random improvement
                for _ in range(5):
                        oldlocations = deepcopy(locations)
                        for k in locations:
                                locations[k] += matrix(5 * np.random.random((1,3)) - 3)
                        if not (pygame.key.get_pressed()[pygame.K_z] or pygame.key.get_pressed()[pygame.K_x]):
                                scalefactor = scalefactor**0.8 * automaticscale(locations)**0.2
                        avelocs(locations,scalefactor)
                        new_value = self.evaluate(locations)
                        if new_value > currmax:
                                locations = oldlocations
                                currmax = new_value
                                consecutive_no_improvement = 0

                        else:
                                consecutive_no_improvement += 1
                                if consecutive_no_improvement > 1000:
                                        simulatephysics = False'''

                for i, layer in enumerate(self.nodes):
                    for j in range(layer.shape[1]):
                        locations[(i, j)] += velocities[(i, j)] * 100
                self.computevelocities(velocities, locations)
                for i, layer in enumerate(self.nodes):
                    for j in range(layer.shape[1]):
                        locations[(i, j)] += velocities[(i, j)] * 100
                if not (pygame.key.get_pressed()[pygame.K_z] or pygame.key.get_pressed()[pygame.K_x]):
                    scalefactor = scalefactor**0.8 * \
                        automaticscale(locations)**0.2
                avelocs(locations, scalefactor)
                if all_nodes_stationary(velocities, scalefactor):
                    simulatephysics = False
                    for i, layer in enumerate(self.nodes):
                        for j in range(layer.shape[1]):
                            velocities[(i, j)] *= 0

            detailed = 0
            if 1 or n % 10 == 0 or key_states[pygame.K_SPACE]:
                detailed = 1

            activekeys = [pygame.K_l, pygame.K_s, pygame.K_z, pygame.K_c,
                          pygame.K_x, pygame.K_UP, pygame.K_DOWN, pygame.K_LEFT, pygame.K_RIGHT]
            if 1 or simulatephysics or any(key_states[key] for key in activekeys):
                sf.blit(background, (0, 0))
                self.drawfromlocationtable(
                    locations, sf, scalefactor, translation, detailed, rotation, shownegatives, showlines, time=n)
                #messages.say("scaling is " + str(scalefactor), 0, down = 20, size = "small")
                pygame.display.flip()
            if key_states[pygame.K_o]:
                done = 1

            previous_key_states = key_states[:]
        return quit
コード例 #5
0
ファイル: room.py プロジェクト: yeahpython/bees-bees-bees
    def __init__(self, tiles, lines):
        #generateringmap(80, 60, 20, 30)
        self.lines = lines
        graphics.extract_dimensions(self.lines)
        nextmessage = 6
        self.cols, self.rows = cols, rows

        for i in range(rows):
            for j in range(cols):
                drawpoint(i, j, lines)

        self.tiles = tiles
        self.camera = 0
        self.madness = 0
        self.stasis = False
        self.roomnumber = 0
        self.signal_new_tree = 0

        nextmessage = messages.say("reducing sides", 0, down=nextmessage)
        self.reduce_sides()

        nextmessage = messages.say("collision stuff", 0, down=nextmessage)
        self.optimize_convexes()

        if (DRAW_RANDOM_CIRCLES):
            nextmessage = messages.say(
                "computing density", 0, down=nextmessage)
            self.compute_densities()

        self.object_directory = [[[]
                                  for r in range(rows)] for c in range(cols)]
        self.background = pygame.Surface((graphics.world_w, graphics.world_h))
        self.collisionfield = pygame.Surface(
            (graphics.world_w, graphics.world_h))
        self.bgw = graphics.world_w
        self.bgh = graphics.world_h
        self.a = 0
        self.start_position = matrix([100, 100])
        for r in range(rows):
            for c in range(cols):
                if self.lines[r][c] == '!':
                    self.start_position = matrix(
                        [bw * c + bw / 2, bh * r + bh / 2])

        nextmessage = messages.say("drawing background", 0, down=nextmessage)
        if TIME_INITIALIZATION:
            backgroundstarttime = time.time()
        # Note that this sets the start position to wherever the '!' is
        self.draw(self.background)
        self.background.convert()
        self.draw(self.collisionfield, collision_only=1)
        self.collisionfield.convert()
        self.pixels = pygame.PixelArray(self.collisionfield)
        if TIME_INITIALIZATION:
            print "drawing background took", time.time() - backgroundstarttime, "seconds"

        self.food = []
        self.bees = []
        self.deadbees = []
        self.player = None
        self.topbar = None
        self.beehistory = 0
        self.bestbees = []
        self.timetosave = 100
        self.h = None
        self.dirtyareas = []
        self.visibles = []
        self.bullets = []
        self.painter = palette.Palette()
        self.recentdeaths = 0
        self.freespots = [(r, c) for r in range(rows)
                          for c in range(cols) if self.lines[r][c] == " "]

        # for r,c in self.freespots:
        #   pygame.draw.circle(self.background, [255, 255, 255], (int((c+0.5)*bw), int((r+0.5)*bh)), 10, 1)

        nextmessage = messages.say("precomputing vision", 0, down=nextmessage)
        self.precompute_vision()
コード例 #6
0
ファイル: panel.py プロジェクト: yeahpython/bees-bees-bees
    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
コード例 #7
0
ファイル: ui.py プロジェクト: yeahpython/bees-bees-bees
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()
コード例 #8
0
ファイル: main.py プロジェクト: yeahpython/bees-bees-bees
def main_loop():
    print "\n" * 12 + "* * * * * NEW GAME * * * * *"

    """these things only need to happen once"""
    screen = pygame.display.get_surface()
    screen.fill(graphics.background)
    load_settings()

    messages.screen = screen

    clock = pygame.time.Clock()
    dt = 0

    world, t, r = 0, 0, 0

    loadedSavedGame = 0

    if getChoiceUnbounded("Load saved game?", ["yes", "no"]) == "yes":
        r = game_progress.load_game()

    if r:
        messages.say("Loading saved game", down=4)
        pygame.display.flip()
        world = pygame.Surface((graphics.world_w, graphics.world_h))
        t = r.topbar
        loadedSavedGame = 1
    else:
        """these are level-specific"""
        level = enteredlevel(allowcancel=0)
        if level == "quit":
            return
        world, t, r = preparelevel(screen, level)
    pygame.display.get_surface().fill((50, 50, 50))

    p = player.Player(r)

    # h = zoo.Beehive()
    h = zoo.Beehive("the fact that any argument is passed here means that I'll load saved bees")

    c = camera.Camera(p, world, screen, r)
    c.jump_to_player()

    # myfamilytree = familytree.FamilyTree()
    myspeciesplot = species_visualization.SpeciesPlot()

    # Generating new bees
    # r.bees = h.preserved_bees(r, p)
    if loadedSavedGame:
        for b in r.bees:
            b.player = p
    else:
        r.generate_bees(settings[MAXIMUM_BEES])
    r.h = h
    # for b in r.bees:
    #   b.randomize_position()

    framecount = 0

    previous_key_states = []
    key_ups = []

    global time_to_quit

    info_panel = StackingPanel()
    left = 0
    top = 0
    for family_name in game_settings.families:
        family_panel = ShrinkingPanel(min_width=250)
        top = 0
        title = MessagePanel(family_name)
        family_panel.children.append(title)

        title.onclick.append(get_toggler(family_panel))
        top += 30

        for entry in game_settings.families[family_name]:
            new_button = SettingButton(entry, y=top, typeface="DejaVu Sans", bold=True, italic=True, visible=False)
            top += 20
            family_panel.children.append(new_button)
        left += family_panel.rect.w
        info_panel.children.append(family_panel)

    # we should never see reassignment of gameobjects!
    gameobjects = {
        "room": r,
        "player": p,
        "hive": h,
        "camera": c,
        "world": world,
        "screen": screen,
        "info_panel": info_panel,
    }

    info_panel.children.append(StatisticsPanel(gameobjects))

    while not close(r):  # Main game loop # Don't need cancel and quit works
        if time_to_quit:
            try:
                print "Quitting indirectly at main loop. Saving room..."
                game_progress.save_game(r)
                break
            except Exception:
                print "Failed to save"
        framecount += 1

        test.begin_timing(test.segs, test.segdescriptors)
        key_presses = pygame.event.get(pygame.KEYDOWN)
        key_states = pygame.key.get_pressed()

        if previous_key_states:
            key_ups = [old and not new for new, old in zip(key_states, previous_key_states)]
        else:
            key_ups = [0 for x in key_states]

        previous_key_states = key_states[:]

        time_gap = handle_player_input(key_presses, key_ups, key_states, gameobjects)

        r = gameobjects["room"]
        c = gameobjects["camera"]
        h = gameobjects["hive"]
        world = gameobjects["world"]
        screen = gameobjects["screen"]
        p = gameobjects["player"]

        if time_gap:
            clock.tick(400)
            dt = 0
        mod = 20
        # each bee updates once every mod frames

        """Update"""
        for i, bee in enumerate(r.bees):
            bee.slow = 1  # (i + framecount) % mod

        test.add_sticky("main:playerupdate")
        p.update(dt, key_states, key_presses)
        test.remove_sticky("main:playerupdate")

        for phys in r.food + r.bullets:
            phys.update(dt, key_states, key_presses)

        test.add_sticky("bee")
        for b in r.bees:
            b.update(dt, key_states, key_presses)
            if b.request_family_tree_update:
                updatefamilytree = 1
                b.request_family_tree_update = 0
        test.remove_sticky("bee")

        screen.fill([0, 0, 0])

        if settings[SHOW_FAMILY_TREE]:
            test.add_sticky("tree")

            # draw every frame, since the tree follows the player around
            if settings[SPECIES_STYLE] == 3:
                if not framecount % settings[TREE_UPDATE_TIME]:
                    myspeciesplot.update(r.bees + r.deadbees)
                    for b in r.deadbees:
                        if b.dead == 2:
                            r.deadbees.remove(b)
                myspeciesplot.draw(
                    world, (int(p.xy[0, 0]) - myspeciesplot.w / 2, int(p.xy[0, 1]) - myspeciesplot.h / 2)
                )

            else:
                # update once every few frames
                if not framecount % settings[TREE_UPDATE_TIME]:
                    myspeciesplot.update(r.bees + r.deadbees)
                    myspeciesplot.draw(screen, (840, 0))

                    for b in r.deadbees:
                        if b.dead == 2:
                            r.deadbees.remove(b)

            updatefamilytree = 0

            if updatefamilytree:
                myfamilytree.update(r.bees)
                myfamilytree.draw(screen, (840, 0))
            test.remove_sticky("tree")

        test.add_sticky("room")
        # Necessarily comes afterwards so that the bees can see the player
        r.update()
        test.remove_sticky("room")

        """
        if r.signal_new_tree:
            r.signal_new_tree = 0
            myfamilytree.depth += 2*settings[TREE_V_SPACING]

        test.remove_sticky('tree') ##########
        """
        test.add_sticky("camera_update")
        c.follow_player(dt)  # Here so that room knows what to draw
        c.updatesight()
        test.remove_sticky("camera_update")

        test.add_sticky("main:drawing")
        test.add_sticky("main:drawing:test")
        test.draw(world, r)
        test.remove_sticky("main:drawing:test")
        test.add_sticky("main:drawing:bee")
        for x in r.bees:
            x.draw(world)
        test.remove_sticky("main:drawing:bee")
        test.add_sticky("main:drawing:other")
        for x in r.food + [p] + r.bullets:
            x.draw(world)
        test.remove_sticky("main:drawing:other")

        # Time
        dt = clock.tick(120)  # used to be 120

        # Make it seem like a slowed down version of 22fps if necessary
        dt = min(dt, 45)
        # print dt, "this is dt"
        test.add_sticky("main:drawing:camera")
        c.draw()
        test.remove_sticky("main:drawing:camera")

        info_panel.draw_to(screen)

        """
        seconds = pygame.time.get_ticks() / 1000

        t0 = ""

        if settings[SPECIES_STYLE] == 1:
            t0 += "Plotted on right: x: horizontal movement, y: generation"
        elif settings[SPECIES_STYLE] == 2:
            t0 += "Plotted on right: x: generation, y: vertical movement"
        elif settings[SPECIES_STYLE] == 3:
            t0 += "angle: direction, radius: generation"

        t.permanent_text = [t0]

        ta = "Time: " + str(seconds)
        tb = " | current bees: " + str(len(r.bees))
        tbb = " | total dead bees " + str(len(r.deadbees))
        tc = " |" + str(int(clock.get_fps()))+"fps"

        t.permanent_text += [
        ta + tb + tbb + tc,]

        if settings[SHOW_HELP]:
            t.permanent_text += [
            "click anywhere for options",
            "plotted on right: Recent lifetimes, max is %s" % (max(t.data) if t.data else "not defined"),
            "[a]: %s birth and deaths" % ("resume" if r.stasis else "pause"),
            "[g]: generate bees",
            "[e]: visualize paths of a random bee",
            "[r]: %s eyes" % ("hide" if settings[SHOW_EYES] else "show"),
            "[n]: %s names" % ("hide" if settings[SHOW_NAMES] else "show"),
            "[m]: %s visual madness" % ("decrease" if r.madness == 2 else "increase"),
            "[SPACE]: teleport to a random position",
            "[t]: turn %s random map generation" % ("off" if settings[GENERATE_RANDOM_MAP] else "on"),
            ]

        t.permanent_text.append("[h]: %s help" % ("hide" if settings[SHOW_HELP] else "show"))

        t.draw(screen)"""
        test.add_sticky("main:drawing:displayflip")
        pygame.display.flip()
        test.remove_sticky("main:drawing:displayflip")
        test.remove_sticky("main:drawing")

        for phys in r.bees + r.food + [p]:
            phys.visible = c.can_see(phys)

        test.summarizetimings(test.segs, test.segdescriptors)
        # if framecount % 30 == 0:
        #   print int(clock.get_fps()), "fps"
        pygame.event.pump()
コード例 #9
0
ファイル: main.py プロジェクト: yeahpython/bees-bees-bees
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