Exemplo n.º 1
0
    def __init__(self):

        self.tablero_barcos = Tablero(10)
        self.tablero_barcos.coloca_barcos_random()
        self.tablero_disparos = Tablero(10)
        self.vidas = 20
        self.disparos = []
Exemplo n.º 2
0
def intentar_mover(una_fila, una_columna):
    global jugador, filas, columnas, puntaje, recompensa, mi_posicion, reiniciar
    if reiniciar == True:
        Tablero.reiniciar_juego()
    nueva_fila = Tablero.jugador[0] + una_fila
    nueva_columna = Tablero.jugador[1] + una_columna
    puntaje += recompensa
    if (nueva_fila >= 0) \
            and (nueva_fila < filas) \
            and (nueva_columna >= 0) \
            and (nueva_columna < columnas) \
            and not ((nueva_fila, nueva_columna) in paredes):
        Tablero.tablero.coords(Tablero.mi_posicion,
                               nueva_fila * ancho + ancho * 2 / 10,
                               nueva_columna * ancho + ancho * 2 / 10,
                               nueva_fila * ancho + ancho * 8 / 10,
                               nueva_columna * ancho + ancho * 8 / 10)
        Tablero.jugador = (nueva_fila, nueva_columna)
    for (i, j, c, w) in celdas_especiales:
        if nueva_fila == i and nueva_columna == j:
            puntaje -= recompensa
            puntaje += w
            if puntaje > 0:
                print("[Exito] puntaje obtenido: ", puntaje)
            else:
                print("[Fallo] puntaje obtenido: ", puntaje)
            reiniciar = True
            return
 def __init__(self, Board_Xdim, Board_Ydim, Ply_num):
     #! estado actual del game del board
     currentState = Tablero([], Board_Xdim, Board_Ydim)  # Tablero.py
     currentState.Initiate()  # Tablero.py
     self.State = Nodo(currentState)  # Nodos.py
     # numero de jugadores
     self.Ply_num = Ply_num
     self.Score = 0
Exemplo n.º 4
0
 def copiaTablero(self, tablero):
     #nuevo tablero
     nt = Tablero()
     nt.turno , nt.numeroDeTurno = tablero.turno, tablero.numeroDeTurno
     for i in range(8):
         for j in range(8):
             nt.mundo[i][j] = tablero.mundo[i][j]
     return nt
Exemplo n.º 5
0
 def __init__(self, jugador1, jugador2):
     self.tablero = Tablero()
     self.jugadores = {
         Color.Blancas: jugador1,
         Color.Negras: jugador2
     } if jugador1.color == Color.Blancas else {
         Color.Blancas: jugador2,
         Color.Negras: jugador1
     }
Exemplo n.º 6
0
class Juego:

    #Inicializa el tablero con los jugadores ingresados
    #El "jugador1" siempre es el que mueve primero
    def __init__(self, jugador1, jugador2):
        self.tablero = Tablero()
        self.jugadores = { Color.Blancas : jugador1, Color.Negras : jugador2 } if jugador1.color == Color.Blancas else { Color.Blancas : jugador2, Color.Negras : jugador1 }

    #Aplica la mejor jugada del jugador con color "color", modificando el tablero actual
    #"color" es el string "blancas" o "negras"
    def __jugada(self, color):
        jugador = self.jugadores[color]
        # Actualiza el tablero
        jugador.mejor_jugada(self.tablero)

    #Retorna la tupla para el tablero actual
    def __obtener_tupla_tablero(self):
        return self.tablero.tupla

    #Retorna true si hay un ganador para el tablero actual
    def __hay_ganador(self):
        return self.tablero.tupla["fichas_blancas_en_punta_opuesta"] == 10 or self.tablero.tupla["fichas_negras_en_punta_opuesta"] == 10
    
    #Retorna el ganador solo en caso que haya (hay_ganador == true) sino retorna None
    def __ganador(self):
        if self.tablero.tupla["fichas_blancas_en_punta_opuesta"] == 10:
            return self.jugadores[Color.Blancas].nombre
        elif self.tablero.tupla["fichas_negras_en_punta_opuesta"] == 10:
            return self.jugadores[Color.Negras].nombre
        else :
            return None

    #Jugar una partida entre los jugadores que son atributos de la clase Juego
    #Devuelve el color del ganador
    def jugar(self, color_que_empieza):
        turnos = 0
        color_segundo = Color.Negras if color_que_empieza == Color.Blancas else Color.Blancas
        while not self.__hay_ganador():
            self.__jugada(color_que_empieza)
            if not self.__hay_ganador():
                self.__jugada(color_segundo)
                if self.__hay_ganador():
                    self.jugadores[color_que_empieza].perdi(self.tablero)
            else:
                self.jugadores[color_segundo].perdi(self.tablero)
            if turnos % 100 == 0:
                self.tablero.imprimir_tablero_con_fichas()
            turnos += 1
            if turnos >= 300:
                self.jugadores[color_que_empieza].empate(self.tablero)
                self.jugadores[color_segundo].empate(self.tablero)
                break
        print("Tablero final")
        self.tablero.imprimir_tablero_con_fichas()
        return self.__ganador()
Exemplo n.º 7
0
class Juego:
    def __init__(self):
        self.tablero = Tablero()
        self.validador = Validador()

    def get_num_negras(self):
        return self.tablero.get_num_negras()

    def get_num_blancas(self):
        return self.tablero.get_num_blancas()

    def get_mover_negras(self):
        return self.validador.get_mover_negras()

    def get_mover_blancas(self):
        return self.validador.get_mover_blancas()

    def clean_game(self):
        self.tablero.limpiar_tablero()
        self.validador.reset_validador()

    def get_tablero(self):
        return self.tablero.get_tablero()

    def get_valores_tablero(self):
        return self.tablero.get_valores_tablero()

    def hay_movimientos_validos(self):
        return self.validador.hay_movimientos_validos(self.tablero)

    def get_estado_juego(self, turno):
        return self.validador.get_estado_juego(turno, self.tablero)

    def llenar_tablero(self, row, i):
        self.tablero.llenar_tablero(row, i)

    def llenar_fichas(self, row):
        return self.tablero.llenar_fichas(row)

    def flip(self, direction, fila, columna, color):
        self.validador.flip(direction, fila, columna, color, self.tablero)

    def set_ficha(self, fila, columna, valor):
        return self.validador.set_ficha(fila, columna, valor, self.tablero)

    def cambiar_turno(self, valor):
        return self.validador.cambiar_turno(valor, self.tablero)

    def escanear_pos(self, fila, columna, color):
        return self.validador.escanear_pos(fila, columna, color, self.tablero)

    def get_movimientos_permitidos(self, color):
        return self.validador.get_movimientos_permitidos(color, self.tablero)
Exemplo n.º 8
0
def strings_movi(Tablero):
    SAdD = Tablero.salto_adelante_D()
    SAdI = Tablero.salto_adelante_I()
    SAtD = Tablero.salto_atras_D()
    SAtI = Tablero.salto_atras_I()

    if (SAdD | SAdI | SAtD | SAtI) != 0:
        SAdD = [(1 + i - i // 9, 1 + (i + 8) - (i + 8) // 9)
                for (i, bit) in enumerate(bin(SAdD)[::-1]) if bit == '1']
        SAdI = [(1 + i - i // 9, 1 + (i + 10) - (i + 8) // 9)
                for (i, bit) in enumerate(bin(SAdI)[::-1]) if bit == '1']
        SAtD = [(1 + i - i // 9, 1 + (i - 8) - (i - 8) // 9)
                for (i, bit) in enumerate(bin(SAtD)[::-1]) if bit == '1']
        SAtI = [(1 + i - i // 9, 1 + (i - 10) - (i - 10) // 9)
                for (i, bit) in enumerate(bin(SAtI)[::-1]) if bit == '1']

        if Tablero.activo == NEGRO:
            movi_reg = [
                "%i a %i" % (orig, dest) for (orig, dest) in SAdD + SAdI
            ]
            movi_inversa = [
                "%i a %i" % (orig, dest) for (orig, dest) in SAtD + SAtI
            ]
            return movi_reg + movi_inversa
        else:
            movi_inversa = [
                "%i a %i" % (orig, dest) for (orig, dest) in SAdD + SAdI
            ]
            movi_reg = [
                "%i a %i" % (orig, dest) for (orig, dest) in SAtD + SAtI
            ]
            return movi_inversa + movi_reg

    AdD = Tablero.adelante_D()
    AdI = Tablero.adelante_I()
    AtD = Tablero.atras_D()
    AtI = Tablero.atras_I()

    AdD = [(1 + i - i // 9, 1 + (i + 4) - (i + 4) // 9)
           for (i, bit) in enumerate(bin(AdD)[::-1]) if bit == '1']
    AdI = [(1 + i - i // 9, 1 + (i + 5) - (i + 5) // 9)
           for (i, bit) in enumerate(bin(AdI)[::-1]) if bit == '1']
    AtD = [(1 + i - i // 9, 1 + (i - 4) - (i - 4) // 9)
           for (i, bit) in enumerate(bin(AtD)[::-1]) if bit == '1']
    AtI = [(1 + i - i // 9, 1 + (i - 5) - (i - 5) // 9)
           for (i, bit) in enumerate(bin(AtI)[::-1]) if bit == '1']

    if Tablero.activo == NEGRO:
        movi_reg = ["%i a %i" % (orig, dest) for (orig, dest) in AdD + AdI]
        movi_inversa = ["%i a %i" % (orig, dest) for (orig, dest) in AtD + AtI]
        return movi_reg + movi_inversa
    else:
        movi_reg = ["%i a %i" % (orig, dest) for (orig, dest) in AtD + AtI]
        movi_inversa = ["%i a %i" % (orig, dest) for (orig, dest) in AdD + AdI]
        return movi_inversa + movi_reg
Exemplo n.º 9
0
def jugar():

    if usuario.cantidadJugadas == 0 and usuario.nivelJugador == 1:

        nivelInicio = nivel.getNivel(usuario.nivelJugador)
        Tablero.mostrarNivel(nivelInicio)

    if usuario.cantidadJugadas == 15:
        print("***********  P E R D I O  ************")
        menu.saludoBienvenida()

    nivelactual = nivel.getNivel(usuario.nivelJugador)
    print("")
    ingresoCoordenada = input("Ingrese la coordenada :  ")
    ingresoCoordenada.lower()

    coordenada = pidoCoordenada.recibeCoordenadaDeJuego(ingresoCoordenada)
    tableroNuevo = modificoTablero.coordenadaCambiaMatriz(
        nivelactual, coordenada)
    print("")
    Tablero.mostrarNivel(tableroNuevo)
    usuario.incrementarCantidadJuagadas()
    print("")
    print("Ud lleva " + str(usuario.cantidadJugadas) +
          " jugadas de 15 permitidas")
    nivelGanado = calculaSituacionJuego.estaTableroCompletamenteApagado(
        tableroNuevo)

    if not nivelGanado:
        elniveldeljugador = usuario.nivelJugador
        print("Nivel " + str(elniveldeljugador))
        jugar()
    else:
        print("")
        print("Ud ha ganado el nivel. Felicitaciones.  ")
        usuario.incrementaPuntaje()
        print("Ud tiene " + str(usuario.puntaje) + " puntos")
        print("")
        queQuiereHacerElJugador = str(
            input(
                "ingrese S para salir del juego, ingrese R para reiniciar o ingrese Y para seguir jugando "
            ))
        queQuiereHacerElJugador.lower()
        if queQuiereHacerElJugador == 'y':
            nivelactual = usuario.nivelTablero + 1
            proximoNivel = nivel.getNivel(nivelactual)
            usuario.pasarDeNivel()
            usuario.reseteoJugadas()
            Tablero.mostrarNivel(proximoNivel)
            jugar()

        if queQuiereHacerElJugador == 's':
            print("        Ud esta saliendo del juego !!!!!!!!")
            exit
            menu.saludoBienvenida()

        if queQuiereHacerElJugador == 'r':
            print("Ud ha seleccionado reiniciar el juego")
            modoPredeterminado.iniciarModoPredeterminado()
Exemplo n.º 10
0
    def __init__(self):
        self.background = pygame.image.load(
            "resources/images/main_background.jpg")
        self.background_1 = pygame.image.load("resources/images/table.jpg")
        self.tablero_img = pygame.image.load("resources/images/tablero.png")
        self.plantilla_img = pygame.image.load(
            "resources/images/plantilla.png")
        pygame.font.init()
        myfont = pygame.font.SysFont('Arial', 50)
        self.textsurface = myfont.render('Ubongo', False, (0, 0, 0))
        self.arrow = pygame.image.load("resources/images/arrow.png")
        self.x = 450
        self.y = 560
        self.election = 1
        self.Fase_Menu = True
        self.Fase_Tablero_ini = False
        self.Fase_Puzzle = False
        self.Fase_Tablero = False
        self.Tablero_Ubongo = Tablero.Tablero()
        self.gema_roja = pygame.image.load("resources/images/gema_roja.png")
        self.gema_azul = pygame.image.load("resources/images/gema_azul.png")
        self.gema_verde = pygame.image.load("resources/images/gema_verde.png")
        self.gema_morada = pygame.image.load(
            "resources/images/gema_morado.png")
        self.controlador = Controller.Controller()
        self.pc_img = pygame.image.load("resources/images/Pc.png")
        self.jugador_img = pygame.image.load("resources/images/Jugador.png")
        self.puzzle_azul = pygame.image.load(
            "resources/images/puzzle_azul.png")
        self.puzzle_celeste = pygame.image.load(
            "resources/images/puzzle_celeste.png")
        self.puzzle_cian = pygame.image.load(
            "resources/images/puzzle_cian.png")
        self.puzzle_marron = pygame.image.load(
            "resources/images/puzzle_marrón.png")
        self.puzzle_naranja = pygame.image.load(
            "resources/images/puzzle_naranja_claro.png")
        self.puzzle_vacio = pygame.image.load(
            "resources/images/espacio_blanco.png")
        self.puzzle_negro = pygame.image.load(
            "resources/images/espacio_vacio.png")
        self.puzzles = [
            self.puzzle_azul, self.puzzle_celeste, self.puzzle_cian,
            self.puzzle_marron, self.puzzle_naranja, self.puzzle_vacio,
            self.puzzle_negro
        ]

        self.posComputadora = 0
        self.intentos = []
Exemplo n.º 11
0
    def __init__(self, longTablero=vpd.LONG_TABLERO, equipos=vpd.EQUIPOS):
        self.NUM_EQUIPOS = len(equipos)

        self.tablero = Tablero.Tablero(longTablero, equipos)
        self.tablero.colocaFichasIniciales()

        self.io = dpc.DamasPorConsola()

        self.turno = 0
        self.ronda = 0

        self.equipoActual = None
        self.turnoConcluido()

        self.io.intro()
Exemplo n.º 12
0
def ejecutar():
    global descuento
    time.sleep(1)
    diferencial = 1
    juego = 1
    while True:
        un_jugador = Tablero.jugador
        maximo_actual, maximo_valor = matriz_maxima(un_jugador)
        (un_jugador, una_posicion, un_puntaje,
         otro_jugador) = mover(maximo_actual)

        # Actualizamos la matriz
        maximo_actual, maximo_valor = matriz_maxima(otro_jugador)
        incrementar_matriz(un_jugador, una_posicion, diferencial,
                           un_puntaje + descuento * maximo_valor)

        juego += 1.0
        if Tablero.puedo_reiniciar():
            Tablero.reiniciar_juego()
            time.sleep(0.01)
            juego = 1.0

        diferencial = pow(juego, -0.1)
        time.sleep(0.1)
Exemplo n.º 13
0
    def __init__(self, filas, columnas):
        """Constructor

        Crea un tablero con el número de filas y columnas indicado

        Args:
            self: Instancia actual
            filas: Filas totales a crear
            columnas: Columnas totales a 
        """
        self.tablero = Tablero.Tablero(filas, columnas)
        self.vista = VistaTablero.VistaTablero(filas, columnas, self.tablero)
        self.lbGeneraciones = Label(master=self.vista.getMaster(),
                                    text="Generaciones = 0")
        self.lbGeneraciones.grid(row=filas + 6, column=0, columnspan=5)
        self.textoSegundos = StringVar()
        self.textSegundos = Entry(master=self.vista.getMaster(),
                                  width=5,
                                  textvariable=self.textoSegundos)
        self.textSegundos.grid(row=filas + 7, column=3, columnspan=5)
        self.lbSegundos = Label(master=self.vista.getMaster(),
                                text="Segundos:")
        self.lbSegundos.grid(row=filas + 7, column=0, columnspan=5)
        self.bIniciar = Button(master=self.vista.getMaster(),
                               text="Continuar",
                               command=self.iniciar)
        self.bIniciar.grid(row=filas + 8, column=0, columnspan=4)
        self.bParar = Button(master=self.vista.getMaster(),
                             text="Parar",
                             command=self.parar,
                             state=DISABLED)
        self.bParar.grid(row=filas + 9, column=0, columnspan=4)
        self.bCargar = Button(master=self.vista.getMaster(),
                              text="Cargar",
                              command=self.cargar)
        self.bCargar.grid(row=filas + 10, column=0, columnspan=4)
        self.bGuardar = Button(master=self.vista.getMaster(),
                               text="Guardar",
                               command=self.guardar)
        self.bGuardar.grid(row=filas + 11, column=0, columnspan=4)
        self.bAleatorio = Button(master=self.vista.getMaster(),
                                 text="Aleatorio",
                                 command=self.aleatorio)
        self.bAleatorio.grid(row=filas + 12, column=0, columnspan=4)
        self.counter = 0
        self.continuar = False
        self.t = threading.Thread(target=self.vivir)
Exemplo n.º 14
0
def listaFinal():
    print("Slecciona una opción: \n", "1 - A* cargando archivo\n",
          "2 - A* Mapa aleatorio\n",
          "3 - Profundidad Uniforme cargando Archivo\n",
          "4 - Profundidad Uniforme mapa aleatorio")

    opcion = int(input("Opción: "))

    globals()["metaOculta"] = []
    if opcion == 2 or opcion == 4:
        archivo = "aleatoria.txt"
        tablerito = Tablero.Tablero()
        tablerito.GenLadrillos()
        globals()["metaOculta"] = tablerito.GenMeta()
    else:
        archivo = "mapa3.txt"

    mapaEnd = Mapa(archivo)
    globals()["listaLadrillos"] = Funciones.enlistarLadrillos(mapaEnd.mapa, 2)

    if (globals()["metaOculta"] == []):
        globals()["metaOculta"] = [
            4, 17
        ]  #Funciones.generarMeta(globals()["listaLadrillos"])

    if (opcion == 1 or opcion == 2):
        globals()["algoritmo"] = "A*"

    if (opcion == 3 or opcion == 4):
        globals()["algoritmo"] = "pU"

    A = Algoritmo(mapaEnd.mapa)

    for i in range(len(A.caminata)):
        if (globals()["algoritmo"] == "A*"):
            print(A.caminata[i].tipo, A.caminata[i].pos, A.caminata[i].muerte,
                  "Puerta ->", A.caminata[i].puerta, " , ", A.caminata[i].f,
                  " , ", A.caminata[i].posEnemigos)
        if (globals()["algoritmo"] == "pU"):
            print(A.caminata[i].tipo, A.caminata[i].pos, A.caminata[i].muerte,
                  "Puerta ->", A.caminata[i].puerta, " , ", A.caminata[i].g,
                  " , ", A.caminata[i].posEnemigos)
    """for i in range(len(A.caminata)):
        print(dibujarMapa.camino(A.caminata[i]), "\n", i)"""

    return [A.caminata, archivo]
Exemplo n.º 15
0
import Tablero
import IA_Damas
import IA
import IA_Damas_Random

NEGRO, BLANCO = 0, 1

f = open('logfile', 'w')

for i in range(100):
    print("Juego: " + str(i))
    B = Tablero.TableroDamas()
    cpu_1 = IA_Damas.IA_Damas(
        lambda Tablero: IA.funcion_de_movimiento(Tablero, 4))
    cpu_2 = IA_Damas.IA_Damas(
        lambda Tablero: IA.funcion_de_movimiento(Tablero, 6))
    jugador_actual = B.activo
    Turno = 1
    while not B.se_termino():
        f.write(str(B))
        if Turno % 100 == 0:
            print("Numero de Turnos: " + str(Turno))
        B.hacer_movi(cpu_1.hacer_movi(B))
        if B.activo == jugador_actual:
            continue
        jugador_actual = B.activo
        Turno += 1
        while not B.se_termino() and B.activo == jugador_actual:
            B.hacer_movi(cpu_2.hacer_movi(B))
        jugador_actual = B.activo
    if B.activo == BLANCO:
Exemplo n.º 16
0
    tablero.mover_inicial(Posicion(x_fin,y_fin),Jugador)
def empezar(tablero):
    for i in range(2):
        if not tablero.fin_juego():
            mostrar(tablero)
            mover_usuario_inicial(tablero)
            tablero.mover_inicial(que_hacer_inicial(tablero),ia)
    for i in range(1):
        if not tablero.fin_juego():
            mostrar(tablero)
            mover_usuario_inicial(tablero)
            tablero.mover_inicial(que_hacer(tablero,ia).objetivo,ia)

def mostrar(tablero):
   tablero.imprimir_bonito()
tablero = Tablero()
empezar(tablero)
fin = False
while not fin:
    fin = tablero.fin_juego()
    if not fin:
        mostrar(tablero)
    fin = tablero.fin_juego()
    if not fin:
        mover_usuario(tablero)
    fin = tablero.fin_juego()
    if not fin:
        tablero.mover_m(que_hacer(tablero,ia))
mostrar(tablero)
print("Fin del juego!")
Exemplo n.º 17
0
def termino(Tablero):
    return len(Tablero.sacar_movi()) == 0
Exemplo n.º 18
0
from time import sleep

import Tictactoe
import Tablero
import Jugador
import QLearning

ai = QLearning.QLearning()
ai2 = QLearning.QLearning()

jugador1 = Jugador.Jugador("player1", 'X', ai)
jugador2 = Jugador.Jugador("player2", 'O', None)

jugadores = []
jugadores.append(jugador1)
jugadores.append(jugador2)

tablero = Tablero.Tablero()
game = Tictactoe.tictactoe(tablero, jugadores)

game.encender()

#while True:
#    game.new_game()
#    if game.iterations == 3:
#        game.new_game(t="q")
#        break
Inter = {}
lista = []
Conjunto, INTS = DPLL(conjuntoClausulas, Inter)
print("True : Satisfacible , False : Insatisfacible")

print("-------", INTS)
for i in INTS:
    if INTS[i]:
        lista.append(i)
    else:
        lista.append("-" + i)
if Conjunto == (True):
    if len(lista) == 0:
        print(u"Error: la lista de interpretaciones está vacía")
    else:
        print("Guardando interpretaciones en archivo...")
        import csv
        archivo = ('tableros_automatico.csv')
        with open(archivo, 'w') as output:
            writer = csv.writer(output, lineterminator='\n')
            writer.writerows([lista])

        print("Interpretaciones guardadas  en " + archivo)

        import Tablero as V
        print("Dibujando su tablero: ")
        V.dibujar([lista])

print("FIN")
Exemplo n.º 20
0
class Jugador:
    def __init__(self):

        self.tablero_barcos = Tablero(10)
        self.tablero_barcos.coloca_barcos_random()
        self.tablero_disparos = Tablero(10)
        self.vidas = 20
        self.disparos = []

    # def barcos(self):
    #
    #     array_barcos_1_pos = np.array([Barco((1, 'C'), 1), Barco((3, 'H'), 1), Barco((6, 'I'), 1), Barco((8, 'C'), 1)])
    #
    #     array_barcos_2_pos = np.array([Barco((1, 'F'), 2, 0), Barco((1, 'I'), 2, 1), Barco((10, 'G'), 2, 1)])
    #
    #     array_barcos_3_pos = np.array([Barco((3, 'A'), 3, 0), Barco((5, 'E'), 3, 1)])
    #
    #     array_barcos_4_pos = np.array([Barco((8, 'F'), 4, 1)])
    #
    #     return np.concatenate((array_barcos_1_pos, array_barcos_2_pos, array_barcos_3_pos, array_barcos_4_pos))

    def imprimir_tablero(self):
        titulo = np.array(cs.LISTA_CARACTERES)
        print("  ", titulo, "           ", titulo)
        print("")
        for i in range(len(cs.LISTA_NUMEROS)):
            if i != 9:
                numero = str(cs.LISTA_NUMEROS[i]) + " "
            else:
                numero = str(cs.LISTA_NUMEROS[i])

            print(numero, self.tablero_barcos.matriz[i], "        ", numero,
                  self.tablero_disparos.matriz[i])

        print("\n")

    '''def posicion_random(self):

        x = random.randint(0, 9)

        y = random.randint(0, 9)

        return (x, y)

    def barcos_random(self):

        for propiedades in cs.TIPOS_BARCO:

            contador = 0

            while contador < propiedades[1]:

                posicion = self.posicion_random()

                x = posicion[0]

                y = posicion[1]

                slicing_sur = self.tablero_barcos.matriz[x: x + propiedades[0], y]

                slicing_norte = self.tablero_barcos.matriz[x: x - propiedades[0]:-1, y]

                slicing_este = self.tablero_barcos.matriz[x, y: y + propiedades[0]]

                slicing_oeste = self.tablero_barcos.matriz[x, y:y - propiedades[0]:-1]

                if cs.BARCO_CHAR not in slicing_sur and len(slicing_sur) == propiedades[0]:

                    self.tablero_barcos.matriz[x: x + propiedades[0], y] = cs.BARCO_CHAR
                    contador += 1

                elif cs.BARCO_CHAR not in slicing_norte and len(slicing_norte) == propiedades[0]:

                    self.tablero_barcos.matriz[x: x - propiedades[0]:-1, y] = cs.BARCO_CHAR
                    contador += 1

                elif cs.BARCO_CHAR not in slicing_este and len(slicing_este) == propiedades[0]:

                    self.tablero_barcos.matriz[x, y: y + propiedades[0]] = cs.BARCO_CHAR
                    contador += 1

                elif cs.BARCO_CHAR not in slicing_oeste and len(slicing_oeste) == propiedades[0]:

                    self.tablero_barcos.matriz[x, y:y - propiedades[0]:-1] = cs.BARCO_CHAR
                    contador += 1'''

    def disparar(self, posicion, a_jugador):

        self.disparos.append(posicion)

        posicion_traducida = self.traducir_posicion(posicion)

        if a_jugador.tablero_barcos.matriz[
                posicion_traducida[0], posicion_traducida[1]] == cs.BARCO_CHAR:

            self.tablero_disparos.matriz[
                posicion_traducida[0], posicion_traducida[1]] = cs.TOCADO_CHAR

            a_jugador.tablero_barcos.matriz[
                posicion_traducida[0], posicion_traducida[1]] = cs.TOCADO_CHAR

            a_jugador.vidas -= 1

            return True

        else:

            self.tablero_disparos.matriz[posicion_traducida[0],
                                         posicion_traducida[1]] = cs.FALLO_CHAR

            a_jugador.tablero_barcos.matriz[
                posicion_traducida[0], posicion_traducida[1]] = cs.FALLO_CHAR

            return False

    def traducir_posicion(self, posicion):

        x = posicion[0] - 1

        y = cs.LISTA_CARACTERES.index(posicion[1])

        return (x, y)
Exemplo n.º 21
0
class Partida:

    print
    print " ------------"
    print "| 4 EN LINEA |"
    print " ------------"
    print

    while True:
        print "1. Nueva partida"
        print "2. Cargar partida"
        print "================="
        print

        modoDeJuego = input("Modo de juego: ")
        print

        if modoDeJuego == 1:
            nombre1 = raw_input("Nombre del jugador 1: ")
            nombre2 = raw_input("Nombre del jugador 2: ")

            jugador1 = Jugador.Jugador(nombre1, 21, "rojo")
            jugador2 = Jugador.Jugador(nombre2, 21, "amarillo")

            jugador1.crearFichas()
            jugador2.crearFichas()

            tablero = Tablero.Tablero()
            turno = 1

            break

        elif modoDeJuego == 2:
            with open('partidaGuardada.pkl', 'rb') as binario:
                jugador1 = pickle.load(binario)
                jugador2 = pickle.load(binario)
                tablero = pickle.load(binario)
                turno = pickle.load(binario)

                binario.close()
                print "Partida cargada!"
                print
            break

        else:
            print "ERROR: Elige un modo de juego valido!"

    print
    tablero.pintarse()

    while jugador1.getNumFichas() > 0 or jugador2.getNumFichas() > 0:

        if turno == 1:
            jugadorActual = jugador1
        else:
            jugadorActual = jugador2

        print
        print "Turno del jugador %i (%s)" % (turno, jugadorActual.getNombre())
        print "Color de ficha %s (%c)" % (jugadorActual.getFicha().getColor(),
                                          jugadorActual.getFicha().pintarse())

        numColumna = input("Numero de columna (0 para guardar partida): ")
        print

        if numColumna == 0:
            with open('partidaGuardada.pkl', 'wb') as binario:
                pickle.dump(jugador1, binario, pickle.HIGHEST_PROTOCOL)
                pickle.dump(jugador2, binario, pickle.HIGHEST_PROTOCOL)
                pickle.dump(tablero, binario, pickle.HIGHEST_PROTOCOL)
                pickle.dump(turno, binario, pickle.HIGHEST_PROTOCOL)

                binario.close()
                print
                print "Partida guardada!"
                print

            break

        elif 0 < numColumna <= tablero.getNumColumnas():
            if tablero.ponerFicha(numColumna,
                                  jugadorActual.sacarFicha().getNumero()):
                print
                print "VICTORIA DEL JUGADOR %i (%s: %i puntos)!!" % (
                    turno, jugadorActual.getNombre(),
                    jugadorActual.getPuntos())
                break

            jugadorActual.setNumFichas(jugadorActual.getNumFichas() - 1)
            if turno == 1:
                turno = 2
            else:
                turno = 1

        else:
            print
            print "ERROR: Introducir numeros del 1 al %i o 0 para guardar." % tablero.getNumColumnas(
            )

    if jugador1.getNumFichas() == jugador2.getNumFichas() == 0:
        print
        print "EMPATE!!"
Exemplo n.º 22
0
def main(nivel_palabras, config_fichas, nivel = 'Facil', tiempo_ronda = 30, tiempo_partida = 320,cargarJuego=False):

    if(cargarJuego):
        with open("partida_guardada", "rb") as f: #antes de entrar se fija que exista
            diccionario2 = load(f)
        tablero = diccionario2['tablero']
        atril = diccionario2['atril_jugador']
        atril_pc =diccionario2['atril_computadora']


        jugar = diccionario2['juego']
        letras_de_atril = 7
        tiempo_ini = jugar.get_hora()
        puntaje_total= jugar.get_puntaje_jugador()

        #moodif
        lista_de_palabras = diccionario2['juego'].get_lista_palabras()
        #ver lo del tiempo
        tiempo_max = tiempo_ronda * 100  # tiempo maximo de turno
        tiempo_comienzo_juego = int(round(time.time() * 100))
        tiempo_fin_juego = tiempo_partida * 100  # Este es el tiempo total de partida
        palabras_permitidas= jugar.get_nivel()
        jugar.mostrar_dificultad(nivel, nivel_palabras) #???
        nombre=jugar.get_nombre()
    else:
        nombre = RegistroPartidas.ingresar_usuario()
        filas = 15
        columnas = 15
        puntaje_total=0

        letras_de_atril = 7
        tablero = Tablero.Tablero(filas,columnas)
        atril = Atril.Atril(letras_de_atril)
        atril_pc = Atril.Atril_PC(letras_de_atril)
        palabras_permitidas = nivel_palabras
        diccionario = Fichas.crear_diccionario()


        jugar = Jugar.Jugar()
        letras_de_atril = 7

        print(jugar.get_turno())
        tiempo_max = tiempo_ronda * 100  # tiempo maximo de turno
        tiempo_comienzo_juego = int(round(time.time() * 100))
        tiempo_fin_juego = tiempo_partida * 100  # Este es el tiempo total de partida
        lista_de_palabras = []
        tiempo_ini=0
        jugar.mostrar_dificultad(nivel, nivel_palabras)

    fichas_jugador = Fichas.crear_bolsa_de_fichas(config_fichas)
    fichas_compu = Fichas.crear_bolsa_de_fichas(config_fichas)

    start_time = int(round(time.time() * 100))
    tiempo_computadora = 0  # inicializo el tiempo actual en 0
    puntajes_letras = Fichas.crear_diccionario_de_puntos(config_fichas)
    diccionario = Fichas.crear_diccionario()
    continuar= atril.agregar_letras(fichas_jugador) #si no hay suficientes fichas  devuelve false

    if(continuar):

        atril_pc.agregar_letras(fichas_compu)
    else:
        sg.popup("upsss, no hay suficientes letras, prueba agregar mas", background_color='#2C2C2C', text_color='#E1BF56', button_color=('white', '#E1BF56'), font=('Helvetica', 12))
        ScrabbleAR.main()



    current_time = 0
    imagen = '/imagenes/scrabble.png'

    # ------ Column Definition ------ #
    column1 = tablero.crear_tablero(nivel)
    column2=[[sg.Text('Fin del juego:', background_color='#2C2C2C', text_color=('#E1BF56'), font=('Helvetica', 12))],
             [sg.Text('', size=(8, 2), font=('Helvetica', 20), justification='center', key='timer_juego', background_color='#2C2C2C', text_color=('#E1BF56'))],
             [sg.Button(button_text='Finalizar Juego',key=('fin_juego'), button_color=('white', '#E1BF56'))],
             [sg.Text('Ultimas Palabras ingresadas', background_color='#2C2C2C', text_color=('#E1BF56'), font=('Helvetica', 12))],
             [sg.Listbox(values=(lista_de_palabras), size=(30, 6),key='lista', background_color='#545454', text_color=('#E1BF56'))],
             [sg.Button(button_text='Posponer partida', key=('Posponer'), button_color=('white', '#E1BF56'))],
             [sg.Text(key='quien_juega',background_color='#2C2C2C', text_color=('#E1BF56'),size=(21,1))]]
    # ------ Menu Definition ------ #
    menu_def = [['Menu', ['Ver modo']],
                 ]
    letter_atril = { 'size' : (3, 2), 'pad' : (0,0), 'button_color' : ('white', '#C8C652')}
    #-----------------------LAYOUT VENTANA-----------------------------------
    layout= []
    layout.append([sg.Menu(menu_def, tearoff=True)])
    atril_PC = [[sg.Button(key=('Atril_PC', i), button_text='?', **letter_atril) for i in range(letras_de_atril)]]
    imagen = [[sg.Text(' '*10, background_color='#2C2C2C'), sg.Image((os.getcwd()+imagen), size=(370, 40), background_color='#2C2C2C')]]
    layout.append([sg.Column(atril_PC, background_color='#2C2C2C'), sg.Column(imagen, background_color='#2C2C2C')])
    PC = [sg.Text('', size=(8, 1), font=('Helvetica', 20), justification='center', key='tempo_compu', background_color='#2C2C2C', text_color=('#E1BF56')), sg.Text('Puntaje computadora: ', font='Helvetica', background_color='#2C2C2C', text_color=('#E1BF56')), sg.Text(atril_pc.get_puntaje(), key='puntPC', font='Helvetica', background_color='#2C2C2C', text_color=('#E1BF56' ),size=(20, 1) )]
    layout.append(PC)
    layout.append([sg.Column(column1, background_color='#2C2C2C'), sg.Column(column2, background_color='#2C2C2C')])
    layout.append([sg.Text('Seleccione una letra de abajo', auto_size_text=True, font='Helvetica', background_color='#2C2C2C', text_color=('#E1BF56'))])
    layout.append([sg.Button(key=('Atril_jugador', i) , button_text= atril.get_espacio_fichas()[i].get_letra(), **letter_atril) for i in range(letras_de_atril)])
    botones = [sg.Button(key='vali', button_text='Validar', button_color=('white', '#E1BF56'), font='Helvetica'),sg.Button(button_text='Cambiar letras',key ="cambiar_letras", button_color=('white', '#E1BF56'), font='Helvetica'), sg.Button(button_text='devolver', key='devolver_al_atril', button_color=('white', '#E1BF56'), font='Helvetica'), sg.Text('Puntaje total: ', font='Helvetica', background_color='#2C2C2C', text_color=('#E1BF56')), sg.Text(puntaje_total, key='punt', font='Helvetica', background_color='#2C2C2C', text_color=('#E1BF56'),size=(20,1))]
    layout.append([sg.Checkbox("", key=('Checkbox', i), size=(2, 2), background_color='#2C2C2C', text_color='#E1BF56')for i in range(letras_de_atril)])
    layout.append(botones)
    layout.append([sg.Text('', size=(8, 1), font=('Helvetica', 20), justification='center', key='timer_jugador', background_color='#2C2C2C', text_color=('#E1BF56'))]) #Temporizador

    window = sg.Window('Scrabble', background_color='#2C2C2C').Layout(layout)
    
    if (cargarJuego):
        tablero.cargar_tablero(window)

    while continuar:
        event, values = window.Read(timeout=0)
        if int(round(time.time() * 100))-tiempo_comienzo_juego> tiempo_fin_juego or event== 'fin_juego' or atril.get_terminar_juego() or atril_pc.get_terminar_juego():  # el juego terminó
            atril.devolver_fallo(window,tablero)
            window.Close()
            #guardo el puntaje y datos del usuario
            if(atril.get_terminar_juego()):
                sg.popup('se terminaron los cambios de atril, se termina el juego ', background_color='#2C2C2C', text_color='#E1BF56', button_color=('white', '#E1BF56'), font=('Helvetica', 12))
            #muestro una ventana con el ganador, opcion retornar al menu
            RegistroPartidas.muestra_Ganador(puntaje_total, atril_pc.get_puntaje(), atril, atril_pc, puntajes_letras, nivel, nombre)

            break
        elif event== 'Posponer':
            jugar.cargar_datos(puntaje_total,atril_pc.get_puntaje(),fichas_jugador, fichas_compu, lista_de_palabras,nivel_palabras,tiempo_transcurrido,nombre)
            jugar.guardar_partida(tablero,atril,atril_pc,jugar)
            sg.Popup("SE GUARDO LA PARTIDA", background_color='#2C2C2C', text_color='#E1BF56', button_color=('white', '#E1BF56'), font=('Helvetica', 12))
            window.Close()
        else:
            # turno de la computadora

            if jugar.get_turno()=='computadora':
                window.Element('quien_juega').Update("COMPUTADORA JUGANDO")
                start_time=int(round(time.time()*100)) # momento en el que empiezo a contar
                window.Read(timeout=0)
                current_time= 0 #tiempo transcurrido
                tiempo_computadora = int(round(time.time()*100))-current_time - start_time
                window.Element('tempo_compu').Update('{:02d}:{:02d}.{:02d}'.format((tiempo_computadora // 100) // 60,(tiempo_computadora // 100) % 60, tiempo_computadora % 100))

                #Juega la computadora
                palabra_armada = atril_pc.jugar_turno(tablero, diccionario, window, fichas_compu, puntajes_letras, palabras_permitidas)
                if(palabra_armada != ' ' and palabra_armada != ''):
                    lista_de_palabras.append(palabra_armada)
                    window.Element('lista').Update(values=lista_de_palabras)
                #actualizo los relojes
                tiempo_computadora = int(round(time.time()))-current_time - start_time
                window.Element('tempo_compu').Update('{:02d}:{:02d}.{:02d}'.format((tiempo_computadora // 100) // 60,(tiempo_computadora // 100) % 60, tiempo_computadora % 100))

                #-------actualizo reloj total
                tiempo_transcurrido = int(round(time.time() * 100)) - tiempo_comienzo_juego
                window.Element('timer_juego').Update('{:02d}:{:02d}.{:02d}'.format((tiempo_transcurrido // 100) // 60,(tiempo_transcurrido// 100) % 60, tiempo_transcurrido % 100))


                if (tiempo_computadora > tiempo_max):
                    print('terminoeltiempo')
                jugar.cambiar_turno()

                tiempo_computadora = int(round(time.time()*100))-current_time - start_time
                window.Element('tempo_compu').Update('{:02d}:{:02d}.{:02d}'.format((tiempo_computadora // 100) // 60,(tiempo_computadora // 100) % 60, tiempo_computadora % 100))

            #turno del jugador
            elif jugar.get_turno()=='jugador':
                window.Element('quien_juega').Update(" TU TURNO ")
                #se termino el tiempo del jugador
                if (current_time> tiempo_max):
                    sg.Popup('Termino el tiempo', background_color='#2C2C2C', text_color='#E1BF56', button_color=('white', '#E1BF56'), font=('Helvetica', 12))
                    print('terminoeltiempo jugador') # insertat
                    atril.devolver_fallo(window,tablero)
                    jugar.cambiar_turno()
                    continue    #no sacar el continue, lo que hace es volver al while sin pasar por lo que esta abajo

                # no se termino el tiempo del jugador
                
                if event == 'devolver_al_atril':
                    atril.devolver_fallo(window, tablero)

                if event in atril.listado_botones():
                    atril.click(tablero, event)
                elif event in tablero.listado_botones():
                    tablero.click(atril, event, window)

                elif event == "cambiar_letras":
                    atril.devolver_fallo(window,tablero)
                    if (atril.get_cambios_atril()>0):
                        atril.cambiar_letras(fichas_jugador,window,tablero,values,fichas_jugador,jugar)
                    else:
                        sg.Popup('no hay mas cambios de atril', background_color='#2C2C2C', text_color='#E1BF56', button_color=('white', '#E1BF56'), font=('Helvetica', 12))
                elif event in atril.listado_botones():
                    atril.click(tablero, event)

                elif event == 'vali':
                    puntaje_total = tablero.click_validar(atril, tablero, window, diccionario, puntaje_total, fichas_jugador, puntajes_letras, jugar, palabras_permitidas, lista_de_palabras)
                elif event=='Ver modo':
                    restantes=  tiempo_fin_juego - tiempo_transcurrido
                    jugar.mostrar_modos(nivel, nivel_palabras,tiempo_max,tiempo_fin_juego,restantes)
                    pass #todo: agregar texto al menu
                elif event == None:
                    break;
                current_time = int(round(time.time() * 100)) - (
                    tiempo_computadora) - start_time  # tiempo actual - tiempo de la computadora - el momento en que empezo
                tiempo_transcurrido=int(round(time.time() * 100))+tiempo_ini -tiempo_comienzo_juego
                window.Element('timer_juego').Update('{:02d}:{:02d}.{:02d}'.format((tiempo_transcurrido// 100) // 60, (tiempo_transcurrido // 100) % 60,
                                                  tiempo_transcurrido % 100))  # muestro el contador
                window.Element('timer_jugador').Update('{:02d}:{:02d}.{:02d}'.format((current_time // 100) // 60, (current_time // 100) % 60, current_time % 100)) #muestro el contador


    window.Close()
    print('llega ??')
Exemplo n.º 23
0
 def __init__(self):
     self.tablero = Tablero()
     self.validador = Validador()
Exemplo n.º 24
0
 def __init__(self):
     while True:
         self.tablero = None
         self.limpiar()
         self.menu_principal = self.leer_entero(
             'Menú Principal: \n'
             '1 - Nuevo Juego \n'
             '2 - Cargar Partida \n'
             '0 - Salir \n', True)
         # Cargo Tablero y configuracion
         if self.menu_principal == Menu_Principal.NUEVO_JUEGO:
             while True:
                 try:
                     valores = input(
                         'Ingrese el tamaño en formato "fila x columna": '
                     ).split('x')
                     if len(valores) != 2 or not str(
                             valores[0]).isnumeric() or not str(
                                 valores[1]).isnumeric():
                         raise FormatoIncorrecto(
                             'Las dimensiones del tablero requieren que sean expresadas en formato "fila x columna". Ej: 5x5.'
                         )
                     else:
                         fila, columna = (int(x) for x in valores)
                         if fila > 30 or columna > 60:
                             raise FormatoIncorrecto(
                                 'Las dimensiones del tablero no deben superar a 30x60.'
                             )
                         if fila < 3 or columna < 3:
                             raise FormatoIncorrecto(
                                 'Las dimensiones del tablero deben superar a 3x3.'
                             )
                         self.tablero = Tablero(fila, columna)
                         break
                 except FormatoIncorrecto as e:
                     print(str(e))
         elif self.menu_principal == Menu_Principal.CARGAR_PARTIDA:
             try:
                 persistencia.printList()
                 self.tablero = persistencia.cargar(
                     input('Ingrese el nombre de la partida: '))
             except IOError:
                 input(
                     'No se encontro una partida con ese nombre. \nPresione la tecla "Enter" para continuar...'
                 )
         elif self.menu_principal == Menu_Principal.SALIR:
             break  #Cierro el programa
         self.limpiar()
         if self.tablero != None:
             #Cargo Configuraciones si no estan seteadas
             try:
                 if self.tablero.modo_de_juego == Modo_De_Juego.NOTSET:
                     self.tablero.modo_de_juego = (self.leer_entero(
                         'Seleccione el modo de juego: \n'
                         '1 - Normal \n'
                         '2 - Paso a paso \n'
                         '3 - Vida Estática \n'
                         '0 - Salir \n', True))
                 if self.tablero.modo_de_juego != Modo_De_Juego.VIDA_ESTATICA and \
                         self.tablero.modo_de_juego != Modo_De_Juego.NOTSET and \
                         self.tablero.modo_de_generacion == Modo_De_Generacion.NOTSET:
                     self.tablero.modo_de_generacion = self.leer_entero(
                         'Seleccione el método de generación: \n'
                         '1 - Aleatorio \n'
                         '2 - Manual \n'
                         '0 - Salir \n', True)
                     if self.tablero.modo_de_generacion == Modo_De_Generacion.RANDOM:
                         while True:
                             try:
                                 self.tablero.random(
                                     self.leer_entero(
                                         'Ingresar número de células vivas: '
                                     ))
                                 break
                             except IndexError as ex:
                                 print(str(ex))
                     elif self.tablero.modo_de_generacion == Modo_De_Generacion.MANUAL:
                         self.editar_tablero()
                     elif self.tablero.modo_de_generacion == Modo_De_Generacion.NOTSET:
                         break
                 elif self.tablero.modo_de_juego == Modo_De_Juego.VIDA_ESTATICA and self.tablero.celulas_random == 0:
                     while True:
                         try:
                             self.tablero.random(
                                 self.leer_entero(
                                     'Ingresar número de células vivas: '))
                             break
                         except IndexError as ex:
                             print(str(ex))
                 elif self.tablero.modo_de_juego == Modo_De_Juego.NOTSET:
                     break
                 self.limpiar()
                 # Inicia el juego
                 print(self.tablero.impresion_tablero())
                 while True:
                     accion = None
                     if self.tablero.modo_de_juego == Modo_De_Juego.VIDA_ESTATICA:
                         self.tablero.vida_estatica()
                         input(
                             'Presione la tecla "Enter" para continuar...')
                         break
                     else:
                         if self.tablero.modo_de_juego == Modo_De_Juego.PASOAPASO:
                             accion = self.leer_entero(
                                 '1 - Siguiente Generación \n'
                                 '2 - Editar \n'
                                 '3 - Guardar \n'
                                 '0 - Salir \n', True)
                         if self.tablero.modo_de_juego == Modo_De_Juego.NORMAL or accion == Accion.SIGUENTE:
                             if self.tablero.modo_de_juego == Modo_De_Juego.NORMAL:
                                 time.sleep(0.1)
                             if self.tablero.finalizo:
                                 input(
                                     'Se encontró un tablero estatico.'
                                     if self.tablero.estatico else
                                     'El juego ha finalizado.' +
                                     '\nPresione la tecla "Enter" para volver al menú principal...'
                                 )
                                 break
                             self.limpiar()
                             self.tablero.actualizar_celulas()
                             print(self.tablero.impresion_tablero())
                         elif accion == Accion.EDITAR:
                             self.editar_tablero()
                         elif accion == Accion.GUARDAR:
                             persistencia.guardar(
                                 self.tablero,
                                 input('Ingrese el nombre de la partida: '))
                         elif accion == Accion.SALIR:
                             break
             except IndexError:
                 input(
                     'Por favor ingresar un valor valido.\nPresione la tecla "Enter" para continuar...'
                 )
             except (KeyboardInterrupt):
                 persistencia.guardar(
                     self.tablero,
                     input('Ingrese el nombre de la partida: '))
             except Exception as ex:
                 input(
                     str(ex) +
                     '\nPresione la tecla "Enter" para continuar...')
Exemplo n.º 25
0
def main():
    print("Bienvenido")

    n = -1
    while not n in [1, 2]:
        n = input("Cantidad de jugadores humanos? (1, 2): ")
        try:
            n = int(n)
        except ValueError:
            print("Ingrese 1, or 2.")

    if n == 2:
        B = Tablero.Tablero()
        print("Negro va primero.")
        Turno = 1
        jugador_actual = B.activo
        while not termino(B):
            print(B)

            Movimientos = B.sacar_movi()

            if B.salto:
                print("Salto.")
                print("")
            else:
                print("Turno %i" % Turno)
                print("")

            for (i, opcion) in enumerate(strings_movi(B)):
                print("opcion " + str(i) + ": " + opcion)

            while True:
                movi_idx = input("Ingrese que movimiento quieres hacer: ")
                try:
                    movi_idx = int(movi_idx)
                except ValueError:
                    print("Ingrese un numero valido.")
                    continue

                if movi_idx in range(len(Movimientos)):
                    break
                else:
                    print("Ingrese un numero valido.")
                    continue

            B.hacer_movi(Movimientos[movi_idx])

            if B.activo == jugador_actual:
                print("Debe saltar.")
                continue
            else:
                jugador_actual = B.activo
                Turno += 1

        print(B)
        if B.activo == BLANCO:
            print("Gano negro!")
        else:
            print("Gano blanco!")

        return 0
    else:
        modulo_de_IA = "IA_Damas_Random"  ##input("Nombre del IA: ")
        __import__(modulo_de_IA)
        modulo_de_IA = sys.modules[modulo_de_IA]
        cpu = IA_Damas.IA_Damas(modulo_de_IA.funcion_de_movimiento)
        while True:
            choice = input("0 para ir primero o 1 para ir segundo: ")
            try:
                choice = int(choice)
                break
            except ValueError:
                print("Ingrese 0 o 1.")
                continue
        Turno = 0
        B = Tablero.Tablero()
        jugador_actual = B.activo
        print("Negro va primero.")
        while not B.se_termino():
            print(B)
            if Turno % 2 == choice:
                Movimientos = B.sacar_movi()
                if B.salto:
                    print("Salta.")
                    print("")
                else:
                    print("Turno %i" % (Turno + 1))
                    print("")
                for (i, opcion) in enumerate(strings_movi(B)):
                    print("opcion " + str(i) + ": " + opcion)
                while True:
                    movi_idx = input("Ingrese que movimiento quieres hacer: ")
                    try:
                        movi_idx = int(movi_idx)
                    except ValueError:
                        print("Ingrese un numero valido.")
                        continue
                    if movi_idx in range(len(Movimientos)):
                        break
                    else:
                        print("Ingrese un numero valido.")
                        continue
                B.hacer_movi(Movimientos[movi_idx])
                if B.activo == jugador_actual:
                    print("Debe saltar.")
                    continue
                else:
                    jugador_actual = B.activo
                    Turno += 1
            else:
                B.hacer_movi(cpu.hacer_movi(B))
                if B.activo == jugador_actual:
                    print("Debe saltar.")
                    continue
                else:
                    jugador_actual = B.activo
                    Turno += 1
        print(B)
        if B.activo == BLANCO:
            print("Gano negro!")
        else:
            print("Gano blanco!")
        return 0
Exemplo n.º 26
0
def ejecutar():
    global descuento
    time.sleep(1)
    diferencial = 1
    juego = 1
    while True:
        un_jugador = Tablero.jugador
        maximo_actual, maximo_valor = matriz_maxima(un_jugador)
        (un_jugador, una_posicion, un_puntaje,
         otro_jugador) = mover(maximo_actual)

        # Actualizamos la matriz
        maximo_actual, maximo_valor = matriz_maxima(otro_jugador)
        incrementar_matriz(un_jugador, una_posicion, diferencial,
                           un_puntaje + descuento * maximo_valor)

        juego += 1.0
        if Tablero.puedo_reiniciar():
            Tablero.reiniciar_juego()
            time.sleep(0.01)
            juego = 1.0

        diferencial = pow(juego, -0.1)
        time.sleep(0.1)


juego = threading.Thread(target=ejecutar)
juego.daemon = True
juego.start()
Tablero.comenzar()
Exemplo n.º 27
0
            else:
                return False, Interpretacion


# TRUE : Satisfacible
# FALSE : Insatisfacible

Inter = {}

Conjunto, Interpretacion = DPLL(conjuntoClausulas, Inter)
print("True : Satisfacible , False : Insatisfacible")

if Conjunto == (True):
    if len(INTS) == 0:
        print(u"Error: la lista de interpretaciones está vacía")
    else:
        print("Guardando interpretaciones en archivo...")
        import csv
        archivo = ('tableros_automatico.csv')
        with open(archivo, 'w') as output:
            writer = csv.writer(output, lineterminator='\n')
            writer.writerows(INTS)

        print("Interpretaciones guardadas  en " + archivo)

        import Tablero as V
        print("Dibujando su tablero: ")
        V.dibujar(INTS)

print("FIN")
Exemplo n.º 28
0
class Game:
	def __init__(self):
		evaluacion=Tablero()
		algoritmo=Minimax()
		self.tablero=Tablero(evaluacion.evaluar_suma_peso)
		self.tablero.cargar_fichas()
		self.minimax=Minimax(algoritmo.minimax);
	def quien_gano(self):
		value=self.tablero.evaluar_suma(1)
		if(value < 0):
			return "Perdiste!!!"
		return "Ganaste!!!"
	
	def juega_computadora(self):
		old_move_computadora,new_move_computadora=self.minimax.start(self.tablero)
		print "score : ", new_move_computadora
		lista, comer_move=self.tablero.comer_fichas(old_move_computadora)
		if(len(lista)-1==0):
			self.tablero.mover_ficha(old_move_computadora,new_move_computadora)
			lista.append(old_move_computadora)
			lista.append(new_move_computadora)
			comer_move=[]
		if(self.tablero.es_dama(new_move_computadora,Ficha.COMPUTADORA)):
			self.tablero.crear_dama(new_move_computadora, Ficha.COMPUTADORA)
		return lista,comer_move
		'''

		'''
	def traducir_a_index(self, move):
		return move.i*8+move.j%8
		
	def juega_usuario(self,x,y):
		
		'''
		debe verificar si:
		se comio una ficha y actualizar el tablero
		'''
	def realizar_movimiento(self, old_move, new_move):
		if(self.tablero.es_valido_move(old_move,new_move)):
			if(self.es_dama_usuario(old_move)):
				#prueba una posicion
				self.tablero.mover_ficha(old_move, new_move)
				comer_move=self.tablero.get_pos_ficha_anterior(old_move,new_move)
				if(not self.tablero.es_duenho(comer_move, Ficha.COMPUTADORA)):
					comer_move=None
			else:
				comer_move=self.tablero.comer_ficha(old_move, new_move)
				self.tablero.mover_ficha(old_move, new_move)
				if(self.es_dama_usuario(new_move)):
					self.tablero.crear_dama(new_move)
			if not (comer_move==None):
				print self.tablero
				self.tablero.eliminar_ficha(comer_move)
				return comer_move.i*Tablero.MAX_DIM+comer_move.j%Tablero.MAX_DIM
			return True
		return False
		
	def route_valido(self, old_move, new_move):
		copia=self.tablero.get_copia()
		if(copia.es_valido_move(old_move,new_move)):
			return True
		return False
	
	def esta_bloqueada(self, move):
		if(self.tablero.casillas[move.i][move.j].duenho==Ficha.BLOQUEADA):
			return True;
		return False
	'''
	verifica si una casilla esta ocupada por el duenho
	'''
	def ocupe_casilla(self, move, duenho=Ficha.USUARIO):
		if(self.tablero.es_vacio(move.i, move.j) or not self.tablero.casillas[move.i][move.j].duenho==duenho):
			return False
		return True
	
	def eliminar_ficha(self, move):
		self.tablero.casillas[move.i][move.j]=Ficha()
	
	def es_dama_usuario(self,move):
		return self.tablero.es_dama(move, Ficha.USUARIO)
	def es_dama_computadora(self, move):
		return self.tablero.es_dama(move, Ficha.COMPUTADORA)
	def es_ficha_usuario(self,move):
		return self.tablero.casillas[move.i][move.j].duenho==Ficha.USUARIO
	def es_ficha_computadora(self, move):
		return self.tablero.casillas[move.i][move.j].duenho==Ficha.COMPUTADORA
Exemplo n.º 29
0
        """
        Como matrizBase tiene la matriz horizontal y vertical juntas, se necesita
        indice para que a nivel del eje x se pueda llegar hasta la matriz vertical.
        Por eso, en la llamada para obtener la matriz vertical se suma el tamaño del
        kakuro (lo que abarca la matriz horizontal) más 1 (saltar el espacio en blanco -> \n).
        """
        matriz = []
        for i in range(tamanioKakuro):
            matriz.append([])

            for j in range(tamanioKakuro):
                matriz[i].append(matrizBase[i + indice][j])

        return matriz


tk = Tk()

interfazUsuario = InterfazUsuario(tk)

kakuro = Kakuro()
tableroKakuro = Tablero.Tablero()

#archivoTmp = Archivo()
#archivoTmp.CrearArchivoTemp()
#archivoTmp.EscribirEnArchivoTemp("Mensaje")
#print(archivoTmp.LeerArchivoTemp())
#archivoTmp.CerrarArchivoTemp()
#print(archivoTmp.ObtenerDirectorio())

tk.mainloop()
Exemplo n.º 30
0
          [sg.Button('Salir del juego', size = (20, 1), key = 'Salir')]]
          
if(os.path.isfile("Guardado.json")):
    diseño += [[sg.Button('Continuar partida', size=(20, 1), key = "Continua")]]
    
window = sg.Window('Menu', diseño)

configuracion = {'Dificultad':'Medio', 'PuntajeJugador':0, 'PuntajeCPU':0, 'Tiempo':10, 'Palabras':[], 'Bolsa':[]}

while True:
    evento, f = window.read()
    if evento in ('Inicio', 'Continua'):
        if(evento == 'inicio') and (os.path.isfile('Guardado.json')):
            segundoEvento, f = sg.Window('Partida anterior guardada', [[sg.Text('Desea continuar la partida anterior?')], [sg.Button('Aceptar'), sg.B('Cancelar') ]]).read()
            if segundoEvento == 'Aceptar':
                remove('Guardado.json')
            else:
                continue    
        window.close()
        configuracion['Palabras'] = setDificultad(configuracion['Dificultad'])
        Tablero.Jugar(configuracion, evento)
    elif evento == "Puntos":
        window.hide()
        puntuaciones()
    elif evento == 'Configuracion':
        window.hide()
        configuracion = ajustes(configuracion)
        window.UnHide()
    elif evento in (None, 'Salir'):
        break
Exemplo n.º 31
0
	def __init__(self):
		evaluacion=Tablero()
		algoritmo=Minimax()
		self.tablero=Tablero(evaluacion.evaluar_suma_peso)
		self.tablero.cargar_fichas()
		self.minimax=Minimax(algoritmo.minimax);