Exemplo n.º 1
0
def end_game():
  if settings.JS_REPLAY_FILE or settings.JS_REPLAY_FILENAME:
    jsplayer.save_world_turns(m.world_turns)
    jsplayer.end_world(m.world_data)

  last_ai_data = m.world_turns[-1][1]
  log.info("END GAME SCORES")
  for t in last_ai_data:
    team = t["team"]
    ai_class = m.world.team_map[team].__class__
    log.info("%s\t%s", team, ai_class.__name__)
    for k in t:
      log.info("  %s:\t%s", k, t[k])
Exemplo n.º 2
0
def appengine_main(ais, appengine_file_name=None, tournament_key=None):
  from google.appengine.api import files
  from appengine.appengine import record_game_to_db, mark_timed_out_ai
  from google.appengine.runtime import DeadlineExceededError

  ai_module.clear_ai_colors()
  start_time = time.time()

  if not appengine_file_name:
    appengine_file_name = files.blobstore.create(mime_type='text/html')
  settings.JS_REPLAY_FILENAME = appengine_file_name

  world_turns = []
  w = world.World()
  turns_left = settings.END_GAME_TURNS
  deadlined = False
  for ai_class in ais:
    ai_player = w.addAI(ai_class)
    ai_module.generate_ai_color(ai_player)

  try:
    for i in xrange(settings.GAME_LENGTH):
        w.spinAI()
        if w.Turn():
          if turns_left > 0:
            turns_left -= 1
          else:
            break

        t = w.dumpTurnToDict(shorten=True)
        s = w.dumpScores()

        world_turns.append((t,s))

        if len(world_turns) >= settings.BUFFER_SIZE:
          with files.open(appengine_file_name, 'a') as replay_file:
            settings.JS_REPLAY_FILE = replay_file
            jsplayer.save_world_turns(world_turns)
            replay_file.close()

          world_turns = []
          gc.collect()

    log.info("Finished simulating the world")
  except KeyboardInterrupt, e:
    mark_timed_out_ai(w)
    raise
Exemplo n.º 3
0
def main(ai_classes=[]):
  w = world.World()
  ai_module.clear_ai_colors()
  global CliWorld, ncurses

  CliWorld = w
  if settings.NCURSES:
    import ncurses_gui
    ncurses_gui.redirect_outputs()
    ncurses = ncurses_gui.NcursesGui()


  for ai_class in ai_classes:
    ai_player = w.addAI(ai_class)
    if ai_player:
      ai_module.generate_ai_color(ai_player)

  w.world_turns = []
  turns_left = settings.END_GAME_TURNS
  if settings.NCURSES:
    ncurses.init(w)

  for i in xrange(settings.GAME_LENGTH):
      w.spinAI()
      if w.Turn():
        if turns_left > 0:
          turns_left -= 1
        else:
          break

      t = w.dumpTurnToDict(shorten=True)
      s = w.dumpScores()

      w.world_turns.append((t,s))

      if settings.NCURSES:
        ncurses.update(t, s)

      if len(w.world_turns) >= settings.BUFFER_SIZE:
        jsplayer.save_world_turns(w.world_turns)
        w.world_turns = []
        gc.collect()

  log.info("Finished simulating the world")
Exemplo n.º 4
0
def main(ai_classes=[]):
    w = world.World()
    ai_module.clear_ai_colors()
    global CliWorld, ncurses

    CliWorld = w
    if settings.NCURSES:
        import ncurses_gui
        ncurses_gui.redirect_outputs()
        ncurses = ncurses_gui.NcursesGui()

    for ai_class in ai_classes:
        ai_player = w.addAI(ai_class)
        if ai_player:
            ai_module.generate_ai_color(ai_player)

    w.world_turns = []
    turns_left = settings.END_GAME_TURNS
    if settings.NCURSES:
        ncurses.init(w)

    for i in xrange(settings.GAME_LENGTH):
        w.spinAI()
        if w.Turn():
            if turns_left > 0:
                turns_left -= 1
            else:
                break

        t = w.dumpTurnToDict(shorten=True)
        s = w.dumpScores()

        w.world_turns.append((t, s))

        if settings.NCURSES:
            ncurses.update(t, s)

        if len(w.world_turns) >= settings.BUFFER_SIZE:
            jsplayer.save_world_turns(w.world_turns)
            w.world_turns = []
            gc.collect()

    log.info("Finished simulating the world")
Exemplo n.º 5
0
def end_game():
    global CliWorld
    for ai in CliWorld.AI:
        log.info("%s:%s", ai.__class__, ai.score)

    if settings.NCURSES:
        ncurses.end()

    # Save the world information to an output file.
    if settings.JS_REPLAY_FILE or settings.JS_REPLAY_FILENAME:
        jsplayer.save_world_turns(CliWorld.world_turns)
        jsplayer.end_world(CliWorld.dumpWorldToDict())

    try:
        if settings.PROFILE_AI:
            CliWorld.printAIProfiles()
    except Exception, e:
        log.warn("""
There was a problem saving AI profile information. Profiling
information can get corrupted if the game is interrupted.
""")
Exemplo n.º 6
0
def end_game():
  global CliWorld
  for ai in CliWorld.AI:
    log.info("%s:%s", ai.__class__, ai.score)

  if settings.NCURSES:
    ncurses.end()

  # Save the world information to an output file.
  if settings.JS_REPLAY_FILE or settings.JS_REPLAY_FILENAME:
    jsplayer.save_world_turns(CliWorld.world_turns)
    jsplayer.end_world(CliWorld.dumpWorldToDict())

  try:
    if settings.PROFILE_AI:
      CliWorld.printAIProfiles()
  except Exception, e:
    log.warn("""
There was a problem saving AI profile information. Profiling
information can get corrupted if the game is interrupted.
""")
Exemplo n.º 7
0
        raise
    except DeadlineExceededError, e:
        mark_timed_out_ai(w)
        deadlined = True
    except Exception, e:
        traceback.print_exc()
    finally:
        for ai in w.AI:
            log.info("%s:%s", ai.__class__, ai.score)

        if not deadlined:
            with gcs.open(appengine_file_name, 'w',
                          content_type='text/html') as replay_file:
                settings.JS_REPLAY_FILE = replay_file
                if world_turns:
                    jsplayer.save_world_turns(world_turns)
                # Save the world information to an output file.
                if settings.JS_REPLAY_FILE or settings.JS_REPLAY_FILENAME:
                    jsplayer.end_world(w.dumpWorldToDict())

                replay_file.close()

    log.info("Saved as: %s", appengine_file_name)
    log.info("http://localhost:8080/replays/%s", appengine_file_name)

    end_time = time.time()
    run_time = end_time - start_time

    record_game_to_db(w, replay_blob_key, run_time, tournament_key)

    return w
Exemplo n.º 8
0
          world_turns = []
          gc.collect()

    log.info("Finished simulating the world")
  except KeyboardInterrupt, e:
    raise
  except Exception, e:
    traceback.print_exc()
  finally:
    for ai in w.AI:
      log.info("%s:%s", ai.__class__, ai.score)

    with files.open(appengine_file_name, 'a') as replay_file:
      settings.JS_REPLAY_FILE = replay_file
      if world_turns:
        jsplayer.save_world_turns(world_turns)
      # Save the world information to an output file.
      if settings.JS_REPLAY_FILE or settings.JS_REPLAY_FILENAME:
        jsplayer.end_world(w.dumpWorldToDict())
      replay_file.close()


  files.finalize(appengine_file_name)
  replay_blob_key = files.blobstore.get_blob_key(appengine_file_name)

  log.info("Saved to: %s", replay_blob_key)
  log.info("Saved as: %s", appengine_file_name)
  log.info("http://localhost:8080/replays/%s", replay_blob_key)

  end_time = time.time()
  run_time = end_time - start_time
Exemplo n.º 9
0
class MapGUI:
    # The frame queue is created in the class definition,
    # instead of in the __init__ so that the internal imports
    # needed by multiprocessing can success in safe mode.
    frame_queue = multiprocessing.Queue(settings.BUFFER_SIZE)
    def __init__(self):
        # Initialize Widgets

        self.initialize_map_window()
        # Initialize the world
        self.world = world.World()
        self.ai_drawables = {}
        self.colors = {}
        self.guiTurn = 0
        ai.clear_ai_colors()

        # Initialize our pixbuf queue
        self.stopped = False
        self.frame_queue = MapGUI.frame_queue
        self.lock = RLock()

        self.processes = []
        self.world_turns = []
        self.world_data = {}

    def initialize_map_window(self):
        self.window = gtk.Window()
        box = gtk.HBox()
        self.key_area = gtk.VBox()
        key_outer = gtk.ScrolledWindow()
        key_outer.add_with_viewport(self.key_area)
        key_outer.set_size_request(200, -1)

        screen = gtk.gdk.screen_get_default()
        self.drawSize = min(screen.get_width(), screen.get_height())
        box.pack_end(key_outer, False)


        self.map_area = gtk.DrawingArea()

        box.pack_start(self.map_area, True)
        self.window.add(box)
        self.window.show_all()
        self.map_area.connect("expose-event", self.map_expose_event_cb)
        self.window.resize(700, 500)
        self.window.connect("destroy", end_threads)


    def draw_key_data(self):
        pass


    def add_ai(self, ai_class):
        a = self.world.addAI(ai_class)

        if not a:
          return

        ai.generate_ai_color(a)

        vbox = gtk.VBox()
        label_box = gtk.HBox()
        label_color_box = gtk.EventBox()
        label = gtk.Label(ai_class.__name__)
        label_color_box.set_size_request(20, -1)
        label_color_box.modify_bg(gtk.STATE_NORMAL,
          gtk.gdk.Color(*ai.AI_COLORS[a.team]))
        label_box.pack_start(label_color_box, False)
        label_box.pack_start(label)
        label_box.set_size_request(-1, 20)

        vbox.pack_start(label_box, False)
        labels = {}
        hbox = gtk.HBox()
        vbox.pack_start(hbox, False)
        for stat in ['moving', 'shooting', 'capturing', 'idle']:
          labels[stat] = gtk.Label("%s: 0" % (stat))
          hbox.pack_start(labels[stat])

        ai_misc_box = gtk.HBox()

        kill_label = gtk.Label("kills: 0")
        ai_misc_box.pack_start(kill_label, True)
        labels['kills'] = kill_label

        time_label = gtk.Label("time: 0")
        ai_misc_box.pack_start(time_label, True)
        labels['time'] = time_label

        vbox.pack_start(ai_misc_box, False)

        b_chart = pygtk_chart.bar_chart.BarChart()
        vbox.pack_start(b_chart)

        for stat in ['units', 'buildings']:
          area = pygtk_chart.bar_chart.Bar(stat, 0, stat)
          area.set_color(gtk.gdk.Color(*AI_STAT_COLORS[stat]))
          b_chart.add_bar(area)

        b_chart.grid.set_visible(False)
        b_chart.set_draw_labels(True)
        self.ai_drawables[str(a.team)] = (labels, b_chart)
        self.key_area.pack_start(vbox)

    def draw_grid(self, context):
        width = self.drawSize
        height = self.drawSize
        deltax = float(width)/self.drawSize
        deltay = float(height)/self.drawSize
        for i in xrange(self.world.mapSize):
            context.move_to(0, deltay*i)
            context.line_to(width, deltay*i)
            context.stroke()
            context.move_to(deltax*i, 0)
            context.line_to(deltax*i, height)
            context.stroke()

    def draw_map(self, world_data, turn_data):


        width = self.drawSize
        height = self.drawSize

        surface = cairo.ImageSurface (cairo.FORMAT_ARGB32, width, height)
        cr = cairo.Context (surface)
        gdkcr = gtk.gdk.CairoContext (cr)
        worldmap.draw_map(gdkcr, width, height, world_data, turn_data)

        self.guiTurn += 1

        # Draw the map
        cairo_context_final = self.map_area.window.cairo_create()
        pattern = cairo.SurfacePattern(surface)

        allocation = self.map_area.get_allocation()

        width = allocation.width
        height = allocation.height

        sx = width / float(self.drawSize)
        sy = height / float(self.drawSize)
        matrix = cairo.Matrix(xx=sx, yy=sy)
        cairo_context_final.transform(matrix)
        cairo_context_final.set_source(pattern)
        cairo_context_final.paint()



    def draw_map_and_ai_data(self):
        try:
          world_data, turn_data, ai_data = json.loads(self.frame_queue.get(False))
        except TypeError:
          end_game()
          sys.exit(0)
        except Queue.Empty, e:
          return

        self.world_turns.append((turn_data, ai_data))
        if len(self.world_turns) >= settings.BUFFER_SIZE:
          jsplayer.save_world_turns(self.world_turns)
          self.world_turns = []
        self.draw_map(world_data, turn_data)
        self.world_data.update(world_data)
        self.update_ai_stats(ai_data, world_data["colors"])