Example #1
0
        def _setup_display():
            pygame.display.set_mode((1280, 600))
            pygame.display.set_caption('Famished Tournament')
            self.screen = pygame.display.get_surface()
            self.done = False

            self.start_button = PygButton((325, 395, 140, 40), 'Start')
            self.help_button = PygButton((485, 395, 110, 40), 'Help')
            self.options_button = PygButton((615, 395, 175, 40), 'Options')
            self.exit_button = PygButton((810, 395, 105, 40), 'Exit')
Example #2
0
 def __init__(self, resolution, winner_name):
     self.resolution = resolution
     self.origin = ((resolution[0] - self.MENU_SIZE) / 2,
                    (resolution[1] - self.MENU_SIZE) / 2)
     space_from_border = (self.MENU_SIZE - self.BUTTON_SIZE[0]) / 2
     button_origin_x = self.origin[0] + space_from_border
     self.new_game_button = PygButton(
         (button_origin_x, self.origin[1] + 144, self.BUTTON_SIZE[0],
          self.BUTTON_SIZE[1]), 'New Game')
     self.quit_button = PygButton(
         (button_origin_x, self.origin[1] + 192, self.BUTTON_SIZE[0],
          self.BUTTON_SIZE[1]), 'Quit')
     self.all_buttons = [self.new_game_button, self.quit_button]
     self.game_over_menu = GameOverMenu(winner_name)
Example #3
0
    def init_buttons(self, resolution):
        self.all_buttons = []
        #main game option buttons
        space_from_border = (self.MENU_SIZE - self.BUTTON_SIZE[0]) / 2
        button_origin_x = self.origin[0] + space_from_border
        b_width = self.BUTTON_SIZE[0]
        b_height = self.BUTTON_SIZE[1]

        s_p_button_frame = (button_origin_x, self.origin[1] + 60, b_width,
                            b_height)
        self.single_player = PygButton(s_p_button_frame, 'Single Player')
        self.all_buttons.append(self.single_player)

        m_p_button_frame = (button_origin_x, self.origin[1] + 120, b_width,
                            b_height)
        self.multy_player = PygButton(m_p_button_frame, 'Multy Player')
        self.all_buttons.append(self.multy_player)

        p_v_a_i_button_frame = (button_origin_x, self.origin[1] + 180, b_width,
                                b_height)
        self.player_vs_ai = PygButton(p_v_a_i_button_frame, 'Player vs AI')
        self.all_buttons.append(self.player_vs_ai)

        #AI difficulty buttons
        b_width = self.MODE_BUTTON_SIZE[0]
        b_height = self.MODE_BUTTON_SIZE[1]

        normal_button_frame = (button_origin_x, self.origin[1] + 220, b_width,
                               b_height)
        self.normal = PygButton(normal_button_frame, 'Normal')
        self.normal.bgcolor = (128, 128, 128)
        self.chosed_mode_button = self.normal
        self.all_buttons.append(self.normal)

        nightmare_button_frame = (button_origin_x + 92, self.origin[1] + 220,
                                  b_width, b_height)
        self.nightmare = PygButton(nightmare_button_frame, 'Nightmare')
        self.all_buttons.append(self.nightmare)

        inferno_button_frame = (button_origin_x + 184, self.origin[1] + 220,
                                b_width, b_height)
        self.inferno = PygButton(inferno_button_frame, 'Inferno')
        self.all_buttons.append(self.inferno)
        #Sound and Help buttons
        b_width = (self.BUTTON_SIZE[0] - 2) / 2
        b_height = (self.BUTTON_SIZE[1] - 2)
        sound_button_frame = (button_origin_x, self.origin[1] + 280, b_width,
                              b_height)
        self.sound = PygButton(sound_button_frame, 'Sound')
        self.all_buttons.append(self.sound)
        #        help_button_frame = (button_origin + b_width + 2 ,
        #                              self.origin[1] + 280, b_width, b_height)
        #        self.help = PygButton(help_button_frame, 'Help')
        #        self.all_buttons.append(self.help)

        #Quit button
        b_width = self.BUTTON_SIZE[0]
        b_height = self.BUTTON_SIZE[1]
        quit_button_frame = (button_origin_x, self.origin[1] + 340, b_width,
                             b_height)
        self.quit = PygButton(quit_button_frame, 'Quit')
        self.all_buttons.append(self.quit)
Example #4
0
pygame.mixer.init()
pygame.font.init()

screen = pygame.display.set_mode((WIDTH, HEIGHT), FLAGS, 32)

from objects import *
from interaction import interaction
import re

bg = pygame.image.load('images/map.png').convert()

total_frames, total_frames_before = 0, 0
paused = False
clock = pygame.time.Clock()

button1 = PygButton((WIDTH / 2 - 60, 100, 120, 40), 'Play')
quitButton = PygButton((WIDTH / 2 - 60, 200, 120, 40), 'Quit')
button3 = PygButton((WIDTH / 2 - 60, 100, 120, 40), 'Continue')
button4 = PygButton((WIDTH / 2 - 60, 150, 120, 40), 'Quit')
button5 = PygButton((WIDTH / 2 - 60, 100, 120, 40), 'Try again')
upgradesButton = PygButton((WIDTH / 2 - 60, 150, 120, 40), 'Upgrades')
upgradePistol1 = PygButton((WIDTH / 2 - 125, 150, 250, 40), 'Upgrade Pistol accuracy $100')
upgradePistol2 = PygButton((WIDTH / 2 - 125, 200, 250, 40), 'Upgrade Pistol speed $100')
upgradePistol3 = PygButton((WIDTH / 2 - 125, 250, 250, 40), 'Upgrade Pistol damage $100')
upgradeShotgun1 = PygButton((WIDTH / 2 - 125, 150, 250, 40), 'Upgrade Shotgun speed $300')
upgradeShotgun2 = PygButton((WIDTH / 2 - 125, 200, 250, 40), 'Upgrade Shotgun damage $300')
upgradeShotgun3 = PygButton((WIDTH / 2 - 125, 250, 250, 40), 'Increase number of pellets $300')
upgradeMGun1 = PygButton((WIDTH / 2 - 140, 150, 280, 40), 'Upgrade Machine Gun speed $420')
upgradeMGun2 = PygButton((WIDTH / 2 - 140, 200, 280, 40), 'Upgrade Machine Gun damage $420')
upgradeMGun3 = PygButton((WIDTH / 2 - 140, 250, 280, 40), 'Upgrade Machine Gun accuracy $420')
upgradeBazooka1 = PygButton((WIDTH / 2 - 125, 150, 250, 40), 'Upgrade Bazooka speed $550')
def simulate_flooding(manifest_filename, display_class = None,
                         init_state = None, height = None):
    '''
    Runs a simulation, and displays it in a GUI window OR saves all frames
    as PNG images.

    Normal operation is to read all options from a manifest file, given by
    manifest_filename. If you want to use a custom surface geometry (anything
    other than a square or hex grid), you'll need to supply your own initial
    state (whatever your display object will use, but must be an iterable and
    contain surface_crns.base.Node objects) and a class that can display your
    state (should subclass surface_crns.views.grid_display.SurfaceDisplay),
    which you should pass as "init_state" and "DisplayClass", respectively.
    '''

    ################################
    # READ MANIFEST AND INITIALIZE #
    ################################
    # Parse the manifest
    print("Reading information from manifest file " + manifest_filename + "...")
    manifest_options = \
                readers.manifest_readers.read_manifest(manifest_filename)

    opts = SynchronousCellularAutomataOptionParser(manifest_options)

    print(" Done.")

    if opts.capture_directory != None:
        from signal import signal, SIGPIPE, SIG_DFL
        import subprocess as sp
        base_dir = opts.capture_directory
        MOVIE_DIRECTORY = base_dir
        DEBUG_DIRECTORY = os.path.join(base_dir, DEBUG_SUBDIRECTORY)
        FRAME_DIRECTORY = os.path.join(base_dir, FRAME_SUBDIRECTORY)
        for d in [base_dir, MOVIE_DIRECTORY, DEBUG_DIRECTORY, FRAME_DIRECTORY]:
            if not os.path.isdir(d):
                os.mkdir(d)
        os.environ["SDL_VIDEODRIVER"] = "dummy"
        print("SDL_VIDEODRIVER set to 'dummy'")
    else:
        FRAME_DIRECTORY = ""

    # Initialize simulation
    if init_state:
        grid = init_state
    else:
        if opts.grid is None:
            raise Exception("Initial grid state required.")
        grid = opts.grid



    if height:
        #print("there is already a height")
        height_grid = height
    else:
        #print("there is NOT already a height, need to go to options")
        if opts.height is None:
            raise Exception("Initial grid state required.")
        #print("went to options")
        height_grid = opts.height
        #print(height_grid)
        #print("done print AFTER going to options")


    simulation = SynchronousSimulator(surface= grid,
                            heightgrid = height_grid,
                            seed= opts.rng_seed,
                            simulation_duration= opts.max_duration)

    simulation.init_wall_time = process_time()
    seed = simulation.seed
    time = simulation.time
    event_history = EventHistory()

    if not opts.capture_directory is None:
        simulation.pixels_saved = 0
        simulation.frame_number = 0
        simulation.capture_time = 0

    ################
    # PYGAME SETUP #
    ################
    print("Beginning Pygame setup...")
    if opts.grid_type == 'parallel_emulated':
        from views.grid_display \
                import ParallelEmulatedSquareGridDisplay
        grid_display = ParallelEmulatedSquareGridDisplay(grid = grid,
                            colormap = opts.COLORMAP,
                            emulation_colormap = opts.emulation_colormap,
                            horizontal_buffer = opts.horizontal_buffer,
                            vertical_buffer = opts.vertical_buffer,
                            cell_height = opts.cell_height,
                            cell_width = opts.cell_width,
                            representative_cell_x = opts.representative_cell_x,
                            representative_cell_y = opts.representative_cell_y,
                            min_x = MIN_GRID_WIDTH,
                            min_y = 0,
                            pixels_per_node = opts.pixels_per_node,
                            display_text = opts.display_text)
    elif opts.grid_type == 'standard':
        if display_class:
            DisplayClass = display_class
        elif opts.grid_type == "standard" and opts.surface_geometry == "square":
            DisplayClass = SquareGridDisplay
        elif opts.grid_type == "standard" and opts.surface_geometry == "hex":
            DisplayClass = HexGridDisplay
        grid_display = DisplayClass(grid = grid,
                                    colormap = opts.COLORMAP,
                                    min_x = MIN_GRID_WIDTH,
                                    min_y = 0,
                                    pixels_per_node = opts.pixels_per_node,
                                    display_text = opts.display_text)
    else:
        raise Exception("Unrecognized grid type '" + opts.grid_type + "'")

    legend_display = LegendDisplay(colormap = opts.COLORMAP)

    # Width only requires legend and grid sizes to calculate
    display_width  = grid_display.display_width + legend_display.display_width

    # Width used to calculate time label and button placements
    time_display  = TimeDisplay(display_width)

    button_y      = time_display.display_height + grid_display.display_height+1
            # max(legend_display.display_height, grid_display.display_height) + 1
    #(int(display_width/2) - (button_width + button_buffer), button_y,
    play_back_button  = PygButton(rect =
         (legend_display.display_width + button_buffer, button_y,
         button_width, button_height),
                             caption = '<<')
    step_back_button  = PygButton(rect =
         (play_back_button.rect.right + button_buffer, button_y,
         button_width, button_height),
                             caption = '< (1)')
    pause_button  = PygButton(rect =
         (step_back_button.rect.right + button_buffer, button_y,
         button_width, button_height),
                              caption = 'Pause')
    step_button  = PygButton(rect =
        (pause_button.rect.right + button_buffer, button_y,
         button_width, button_height),
                             caption = '(1) >')
    play_button  = PygButton(rect =
        (step_button.rect.right + button_buffer, button_y,
         button_width, button_height),
                             caption = '>>')
    clip_button = PygButton(rect =
        (play_button.rect.right + 4*button_buffer, button_y,
         button_width * 1.1, button_height),
                            caption = 'Uncache')

    display_height = max(legend_display.display_height + \
                2*legend_display.VERTICAL_BUFFER + time_display.display_height,
                         button_y + button_height + 2*button_buffer)

    if opts.debug:
        print("Initializing display of size " + str(display_width) + ", " +
                str(display_height) + ".")
    display_surface = pygame.display.set_mode((display_width,
                                                   display_height), 0, 32)
    simulation.display_surface = display_surface
    # except:
    #     display_surface = pygame.display.set_mode((display_width,
    #                                                display_height))
    if opts.debug:
        print("Display initialized. Setting caption.")
    pygame.display.set_caption(f'Surface CRN Simulator (Seed: {seed})')
    if opts.debug:
        print("Caption set, initializing clock.")
    fpsClock = pygame.time.Clock()

    if opts.debug:
        print("Clock initialized. Filling display with white.")
    # Initial render
    display_surface.fill(WHITE)
    print("Pygame setup done, first render attempted.")

    # Make the options menu.
    #opts_menu = MainOptionMenu()
    #opts_menu.update()

    time_display.render(display_surface, x_pos = 0,
                                         y_pos = 0)
    legend_display.render(display_surface, x_pos = 0,
                                          y_pos = time_display.y_pos +
                                                  time_display.display_height)
    grid_display.render(display_surface, x_pos = legend_display.display_width,
                                         y_pos = time_display.y_pos +
                                                 time_display.display_height)

    if opts.saving_movie:
        simulation.display_surface_size = display_height * display_width
    else:
        play_back_button.draw(display_surface)
        step_back_button.draw(display_surface)
        pause_button.draw(display_surface)
        step_button.draw(display_surface)
        play_button.draw(display_surface)
        clip_button.draw(display_surface)

    pygame.display.flip()
    update_display(opts, simulation, FRAME_DIRECTORY)

    if "SDL_VIDEODRIVER" in os.environ:
        real_time = os.environ["SDL_VIDEODRIVER"] != "dummy"
    else:
        real_time = True

    # State variables for simulation
    next_reaction_time = 0
    prev_reaction_time = 0
    next_reaction = None
    prev_reaction = None
    running = True #TEMPORARY FIX ME!!!
    first_frame = True
    last_frame  = False
    running_backward = False

    # Resource limit flags
    terminate = False
    termination_string = ""

    print("Beginning simulation....")
    # Iterate through events
    while True:
        # Check for interface events
        for event in pygame.event.get():
            if 'click' in play_back_button.handleEvent(event):
                running = True
                running_backward = True
                last_frame = False
            if 'click' in step_back_button.handleEvent(event):
                running = False
                last_frame = False
                if event_history.at_beginning():
                    time = 0
                    time_display.time = 0
                    time_display.render(display_surface, x_pos = 0, y_pos = 0)
                    pygame.display.update()
                else:
                    prev_reaction = event_history.previous_event()
                    event_history.increment_event(-1)
                    if not event_history:
                        continue
                    prev_reaction_rule = prev_reaction.rule
                    for i in range(len(prev_reaction.participants)):
                        cell = prev_reaction.participants[i]
                        state = prev_reaction_rule.inputs[i]
                        cell.state = state
                    display_next_event(prev_reaction, grid_display)
                    if event_history.at_beginning():
                        time = 0
                    else:
                        # Note that this is NOT the same as the time from the
                        # "previous event" that we're currently processing --
                        # it's actually the time of the event *before* the one
                        # we just undid.
                        time = event_history.previous_event().time
                    time_display.time = time
                    time_display.render(display_surface, x_pos = 0, y_pos = 0)
                    pygame.display.update()
            if 'click' in pause_button.handleEvent(event):
                running = False
            if 'click' in step_button.handleEvent(event):
                running = False
                first_frame = False
                # Process a single reaction
                reading_history = False
                if not event_history.at_end():
                    reading_history = True
                    next_reaction = event_history.next_event()
                    event_history.increment_event(1)
                    next_reaction_rule = next_reaction.rule
                    for i in range(len(next_reaction.participants)):
                        cell = next_reaction.participants[i]
                        state = next_reaction_rule.outputs[i]
                        cell.state = state
                if not next_reaction:
                    next_reaction = simulation.process_next_reaction()
                    if not reading_history:
                        event_history.add_event(next_reaction)
                        event_history.increment_event(1)
                if next_reaction:
                    next_reaction_time = next_reaction.time
                    display_next_event(next_reaction, grid_display)
                    time = next_reaction_time
                    time_display.time = time
                    time_display.render(display_surface, x_pos = 0, y_pos = 0)
                    pygame.display.update()
                    next_reaction = None
                    if opts.debug:
                        print("State after update: " + str(grid))
            if 'click' in play_button.handleEvent(event):
                running = True
                running_backward = False
                first_frame = False
            if 'click' in clip_button.handleEvent(event):
                event_history.clip()
                simulation.time = time
                simulation.reset()
                for rxn in list(simulation.event_queue.queue):
                    print(rxn)
            if event.type == pygl.QUIT:
                if opts.saving_movie:
                    movie_file.close()
                current_state = FINISHED_CLEAN
                cleanup_and_exit(simulation, current_state)
        # Don't do anything if paused.
        if not running:
            pygame.display.update()
            continue

        # Update time
        if opts.debug:
            print(f"Updating time: time = {time}, running_backward = "
                  f"{running_backward}, first_frame = {first_frame}, "
                  f"last_frame = {last_frame}")
        if running_backward and not first_frame:
            #prev_reaction_time = time
            time -= opts.speedup_factor * 1./opts.fps
            last_frame = False
        elif not running_backward and not last_frame:
            #next_reaction_time = time
            time += opts.speedup_factor * 1./opts.fps
            first_frame = False
        if opts.debug:
            print(f"Updating time to {time}")
        time_display.time = time
        time_display.render(display_surface, x_pos = 0,
                            y_pos = 0)

        # Process any simulation events that have happened since the last tick.
        if opts.debug:
            print("Checking for new events...")
        if running_backward and not first_frame:
            if opts.debug and not event_history.at_beginning():
                print(f"While running backwards, checking if there are any "
                      f"events: time = {time}, previous event time = "
                      f"{event_history.previous_event().time}")
            while not event_history.at_beginning() and \
             event_history.previous_event().time > time:
                prev_reaction = event_history.previous_event()
                if event_history.at_beginning():
                    first_frame = True
                event_history.increment_event(-1)
                # if opts.debug:
                #     print("While running backwards, undoing reaction: "
                #           f"{prev_reaction}")
                for i in range(len(prev_reaction.participants)):
                    cell  = prev_reaction.participants[i]
                    state = prev_reaction.rule.inputs[i]
                    cell.state = state
                next_reaction_time = prev_reaction_time
                prev_reaction_time = prev_reaction.time if prev_reaction \
                                                        else 0
                if opts.debug:
                    print("Displaying a new event")
                display_next_event(prev_reaction, grid_display)
                if opts.debug and not event_history.at_beginning():
                    print(f"While running backwards, checking if there are any "
                      f"events: time = {time}, previous event time = "
                      f"{event_history.previous_event().time}")
        elif not running_backward and not last_frame:
            while (not event_history.at_end() or not simulation.done()) \
               and next_reaction_time < time:
                if event_history.at_end():
                    next_reaction = simulation.process_next_reaction()
                    if next_reaction:
                        event_history.add_event(next_reaction)
                        event_history.increment_event(1)
                else:
                    next_reaction = event_history.next_event()
                    event_history.increment_event(1)
                    for i in range(len(next_reaction.participants)):
                        cell = next_reaction.participants[i]
                        state = next_reaction.rule.outputs[i]
                        cell.state = state

                prev_reaction_time = next_reaction_time
                next_reaction_time = next_reaction.time if next_reaction \
                                                    else opts.max_duration + 1
                if opts.debug:
                    print("Displaying a new event")
                display_next_event(next_reaction, grid_display)

        # Render updates and make the next clock tick.
        if opts.debug:
            print("Updating display.")
        update_display(opts, simulation, FRAME_DIRECTORY)
        if real_time:
            fpsClock.tick(opts.fps)

        # Movie-capturing termination conditions
        if not opts.capture_directory is None:
            if simulation.pixels_saved > CUTOFF_SIZE:
                termination_string = "Simulation terminated after " + \
                                     str(simulation.pixels_saved) + \
                                     " pixels saved (~" + \
                                     str(CUTOFF_SIZE/10000000) +" Mb)."
                current_state = MAX_PIXELS
                terminate = True

            # Check the timer. If it's been more than an hour, terminate.
            if process_time() - simulation.init_wall_time > CUTOFF_TIME:
                termination_string = "Simulation cut off at max " \
                                     "processing time"
                current_state = MAX_TIME
                terminate = True

            if simulation.done() or time > opts.max_duration:
                termination_string = "Simulation finished."
                current_state = FINISHED_CLEAN
                terminate = True

            if terminate:
                display_surface = simulation.display_surface
                width = display_surface.get_size()[0]
                text_display = TextDisplay(width)
                text_display.text = termination_string
                text_display.render(display_surface, x_pos = 0, y_pos = 0)
                frame_filename = os.path.join(FRAME_DIRECTORY,
                            f"{opts.movie_title}_{simulation.frame_number}.png")
                if opts.debug:
                    print("Saving final frame at: " + frame_filename)
                pygame.image.save(display_surface, frame_filename)

                # Use ffmpeg to convert images to movie.
                if os.name == 'nt':
                    ffmpeg_name = 'ffmpeg.exe'
                elif os.name == 'posix':
                    # ffmpeg_name = 'ffmpeg'
                    name_found = False
                    for possible_name in ['/usr/local/bin/ffmpeg',
                                          '/usr/bin/ffmpeg']:
                        if os.path.isfile(possible_name):
                            ffmpeg_name = possible_name  # EW: not finding it?
                            name_found = True
                            break
                    if not name_found:
                        raise Exception("Could not find executable ffmpeg in"
                                        " any of the expected locations!")
                else:
                    raise Exception("Unexpected OS name '" + os.name + "'")

                signal(SIGPIPE, SIG_DFL)
                # width = display_surface.get_width()
                # height = display_surface.get_height()
                movie_filename = os.path.join(".", MOVIE_DIRECTORY,
                                              opts.movie_title + ".mp4")
                if opts.debug:
                    print("Writing movie to  file " + movie_filename +
                                 "\n")
                command = [ffmpeg_name,
                           '-y', # Overwrite output file
                           #'-framerate', str(opts.fps),
                           '-start_number', '1', # EW: might it default to
                                                 # starting with 0?
                           '-i', os.path.join(FRAME_DIRECTORY,
                                              opts.movie_title + "_%d.png"),
                           # Try to use better-than-default decoder
                           '-vcodec', 'h264',
                           # Need this for Quicktime to be able to read it
                           '-pix_fmt', 'yuv420p',
                           # Set a higher-than-default bitrate
                           '-crf', '18',
                           '-an', #no audio
                           # Width and height need to be divisible by 2.
                           # Round up if necessary.
                           '-vf', 'pad=ceil(iw/2)*2:ceil(ih/2)*2',
                           movie_filename
                           ]
                print("Calling ffmpeg with: " + str(command))
                print("And right now the current dir is " + os.getcwd())
                print("opts.capture_directory = " + opts.capture_directory)

                if opts.debug:
                    print("Writing movie with command:\n")
                    print("\t" + str(command) + "\n")
                debug_output_stream = open(os.path.join(opts.capture_directory,
                                                        "debug",
                                                        "ffmpeg_debug.dbg"),'w')
                proc = sp.Popen(command,
                                stdout = debug_output_stream,
                                stderr = sp.STDOUT)
                proc.communicate()
                if opts.debug:
                    print("Finished ffmpeg call.")

                cleanup_and_exit(simulation, current_state)

        # Live termination conditions
        if opts.debug:
            print("Checking for simulation completion...")
        if (event_history.at_end() and running and not running_backward and \
           (simulation.done() or time > opts.max_duration)) \
           or terminate:
            if opts.debug:
                print("Done! Cleaning up now.")
            last_frame = True
            running = False
            # Set the time to final time when done.
            time = opts.max_duration
            time_display.time = time
            time_display.render(display_surface, x_pos = 0,
                                y_pos = 0)#opts_menu.display_height)
            if next_reaction:
                display_next_event(next_reaction, grid_display)
            update_display(opts, simulation, FRAME_DIRECTORY)
            if opts.debug:
                print("Simulation state at final time " + \
                      str(opts.max_duration) + ":")
                print(str(grid))

        if event_history.at_beginning() or time == 0:
            first_frame = True