예제 #1
0
파일: cpu.py 프로젝트: vladfi1/cpu-level-11
    def __init__(self, dump=True, dump_size=3600, dump_dir='experience/'):
        self.dump = dump
        self.dump_size = dump_size
        self.dump_dir = dump_dir

        # TODO This might not always be accurate.
        dolphin_dir = os.path.expanduser('~/.local/share/dolphin-emu')

        self.state = ssbm.GameMemory()
        self.sm = state_manager.StateManager([0, 1])
        self.write_locations(dolphin_dir)

        self.fox = fox.Fox()
        self.agent = agent.Agent()
        self.mm = menu_manager.MenuManager()

        try:
            print('Creating MemoryWatcher.')
            self.mw = memory_watcher.MemoryWatcher(
                dolphin_dir + '/MemoryWatcher/MemoryWatcher')
            print('Creating Pad. Open dolphin now.')
            self.pad = pad.Pad(dolphin_dir + '/Pipes/phillip')
            self.initialized = True
        except KeyboardInterrupt:
            self.initialized = False

        self.init_stats()
예제 #2
0
    def setUp(self):
        # Create a fifo for testing. We'll remove it in tearDown.
        self.fifo_path = os.getcwd() + '/fifo'
        os.mkfifo(self.fifo_path)

        self.pipe = os.open(self.fifo_path, os.O_RDONLY | os.O_NONBLOCK)
        self.pad = pad.Pad(self.fifo_path)
예제 #3
0
    def __init__(self, window_config, ball_config, pad_config,
                 bricks_config_list):
        """Конструктор Контроллера.
		Принимает объекты, которыми будет управлять контроллер: окно, мяч, ракетку, список кирпичей.
		Устанавливает начальное состояние игры:
		количество попыток игрока, нулевое начальное значение счета (разрушенных кирпичей).
		Сохраняет ссылки на контролируемые объекты."""
        self.HP = 3  # Три попытки
        self.score = 0  # Начальный нулевой счёт
        self.window = window.Window(
            window_config[0],
            window_config[1],
            window_config[2],
        )
        self.ball = ball.Ball(self.window, ball_config[0], ball_config[1],
                              ball_config[2], ball_config[5])
        self.ball.set_speed(ball_config[3], ball_config[4])
        self.pad = pad.Pad(self.window, pad_config[0], pad_config[1],
                           pad_config[2])
        self.brick_list = [
            brick.Brick(self.window, brick_config[0], brick_config[1],
                        brick_config[2], brick_config[3], brick_config[4])
            for brick_config in bricks_config_list
        ]
        self.max_score = len(
            self.brick_list)  # Счёт, при котором игрок победит
        # Привязка нажатия и отпускания клавиш к функции управления скоростью ракетки:
        self.window.canvas.bind("<KeyPress>", self.pad_speed_control)
        self.window.canvas.bind("<KeyRelease>", self.pad_speed_control)
예제 #4
0
def part_two(args, input_lines):
    "Process part two of the puzzle"

    # 1. Create the puzzle solver
    solver = pad.Pad(part2=True, text=input_lines)

    # 2. Determine the solution for part two
    solution = solver.part_two(verbose=args.verbose, limit=args.limit)
    if solution is None:
        print("There is no solution")
    else:
        print("The solution for part two is %s" % (solution))

    # 3. Return result
    return solution is not None
예제 #5
0
    def __init__(self, dump=True, dump_size=3600, dump_dir='experience/'):
        self.dump = dump
        self.dump_size = dump_size
        self.dump_dir = dump_dir

        # TODO This might not always be accurate.
        dolphin_dir = 'C:\\Program Files\\Dolphin\\Dolphin.exe'

        try:
            #print('Creating MemoryWatcher.')
            #self.mw = memory_watcher.MemoryWatcher(dolphin_dir + '/MemoryWatcher/MemoryWatcher')
            print('Creating Pad. Open dolphin now.')
            self.pad = pad.Pad(dolphin_dir)
            self.initialized = True
        except KeyboardInterrupt:
            self.initialized = False

        #self.init_stats(self)
        self.run(self)
예제 #6
0
    def reset(self):
        try:
            os.system("killall -s KILL dolphin-emu")
        except:
            pass
        dolphin_dir = find_dolphin_dir()
        if dolphin_dir is None:
            print('Could not find dolphin config dir.')
            return

        self.state = st.State()
        self.sm = state_manager.StateManager(self.state)
        write_locations(dolphin_dir, self.sm.locations())

        self.stats = stat.Stats()

        print('Start dolphin now. Press ^C to stop ')
        from subprocess import Popen
        Popen([
            "dolphin-emu", "--movie=/home/sci/workspace/Athena/falcon.dtm",
            "--exec=/home/sci/Downloads/Super Smash Bros. Melee (USA) (En,Ja) (v1.02).iso"
        ])
        self.mw = memory_watcher.MemoryWatcher(dolphin_dir +
                                               '/MemoryWatcher/MemoryWatcher')
        self.pad = p.Pad(dolphin_dir + '/Pipes/p3')
        #run(state, sm, mw, pad, stats)
        self.mm = menu_manager.MenuManager()
        self.last_frame = self.state.frame
        print(vars(self))
        #        while self.state.frame <= self.last_frame:
        #            self.last_frame = self.state.frame
        #            res = next(self.mw)
        #            if res is not None:
        #                self.sm.handle(*res)
        #               # print (res)
        #        print(vars(self))
        self.stall(0)
        d3 = self.get_data(copy.deepcopy(self.state))
        return d3
예제 #7
0
    def reiniciar(self,
                  ancho=640,
                  alto=480,
                  titulo='pilas-engine',
                  con_aceleracion=None,
                  habilitar_mensajes_log=False,
                  x=None,
                  y=None,
                  capturar_errores=True,
                  pantalla_completa=False):
        """Genera nuevamente la ventana del videojuego."""

        # Si no especifica usar aceleracion de video, toma la
        # preferencia desde el archivo de configuración.
        if con_aceleracion == None:
            con_aceleracion = self.configuracion.aceleracion_habilitada()
            self.log(
                "No se especificó aceleración de video, así que se adopta la preferencia desde la configuración: con_aceleracion="
                + str(con_aceleracion))
        else:
            self.log("Se usa el parametro aceleracion=" + str(con_aceleracion))

        self.habilitar_mensajes_log(habilitar_mensajes_log)
        self.log("Iniciando pilas con una ventana de ", ancho, "x", alto)
        self.log(
            "Reiniciando pilas con los parametros",
            str({
                "ancho": ancho,
                "alto": alto,
                "titulo": titulo,
                "con_aceleracion": con_aceleracion,
                "capturar_errores": capturar_errores,
                "habilitar_mensajes_log": habilitar_mensajes_log,
                "x": x,
                "y": y
            }))
        self.actores = actores.Actores(self)
        self.actores.eliminar_actores_personalizados()
        self.eventos = eventos.Eventos(self)
        self.evento = self.eventos
        self.datos = datos.Datos(self)

        self.controles = controles.Controles(self)
        self.simbolos = simbolos.Simbolos(self)

        if not getattr(self, 'escenas', None):
            self.escenas = escenas.Escenas(self)

        self.escenas.eliminar_escenas_personalizadas()
        self.imagenes = imagenes.Imagenes(self)
        self.utils = utils.Utils(self)
        self.fondos = fondos.Fondos(self)
        self.colores = colores
        self.interfaz = interfaz.Interfaz(self)
        self._capturar_errores = capturar_errores

        if not getattr(self, 'depurador', None):
            self.depurador = depurador.Depurador(self)

        #if not self.configuracion.audio_habilitado():
        #    print "Nota: Iniciando con el sistema de audio deshabitado."

        self.musica = musica.Musica(self)
        self.sonidos = sonidos.Sonidos(self)

        if self.configuracion.pad_habilitado():
            self.pad = pad.Pad(self)
        else:
            self.pad = pad.PadDeshabilitado(self)

        self.habilidades = habilidades.Habilidades()

        es_reinicio = self.widget is not None

        if es_reinicio:
            self.log("Es un reinicio real (ya existia el objeto widget)")
        else:
            self.log(
                "El reinicio se hace por primera vez (es una inicializacion en realidad)"
            )

        if self._iniciado_desde_asistente and es_reinicio:
            parent = self._eliminar_el_anterior_widget()

        if con_aceleracion:
            self.log("Creando el widget canvas con aceleracion de video")
            self.widget = widget.WidgetConAceleracion(self, titulo, ancho,
                                                      alto,
                                                      self._capturar_errores)
        else:
            self.log("Creando el widget canvas SIN aceleracion de video")
            self.widget = widget.WidgetSinAceleracion(self, titulo, ancho,
                                                      alto,
                                                      self._capturar_errores)

        if self._iniciado_desde_asistente and es_reinicio:
            self._vincular_el_nuevo_widget(parent)

        self.widget.pantalla_completa = pantalla_completa

        self.escenas.Normal()

        self.comportamientos = comportamientos.Comportamientos()
        self._x = x
        self._y = y
예제 #8
0
파일: p3.py 프로젝트: markisus/p3
#!/usr/bin/env python3

import mw
import game_state
import pad
import sys

if __name__ == '__main__':
    if len(sys.argv) != 2:
        sys.exit('Usage: ' + sys.argv[0] + ' dolphin-home')
    home = sys.argv[1]

    pad = pad.Pad(home + '/Pipes/p3')
    mw = mw.MemoryWatcher(home + '/MemoryWatcher/MemoryWatcher')

    state = game_state.GameState()
    
    # Just print out addresses and values for now
    for address, value in mw:
        state.update(address, value)
        print(str(state))