def test_key_functions(self):
     words = ["alfalfa", "animal", "apple", "acoustic"]
     self.assertIterableEqual(minmax(words, key=len), ("apple", "acoustic"))
     def a_count(word): return word.count('a')
     self.assertIterableEqual(minmax(words, key=a_count), ("apple", "alfalfa"))
     with self.assertRaises(TypeError):
         minmax([1], lambda x: x)
def runAll(game):
    strong.strongDom(game)
    print ""
    weak.weakDom(game)
    print ""
    very_weak.veryWeakDom(game)
    print ""
    purenash.PSNE(game)
    print ""
    maxmin.maxmin(game)
    print ""
    minmax.minmax(game)
    print ""
Exemple #3
0
 def reset(self):
     # Reset the state of the environment to an initial state
     self.game = Game(self.board_width, self.board_height)
     self.steps = 0
     if (self.game.current_player==1): #  so ist immer der RL Agent als erstes im step dran und kann keinen illegalen zug machen wenn er als action das selbe feld wählt wie der Gegner
         self.game.play(find_best_move(minmax(self.game,4)), self.game.current_player) 
     return np.array(self.game.board)
Exemple #4
0
    def resolve(rng, candidates):
        assert rng[0] <= rng[1]

        found = []
        garbage = []
        puramierda = []

        for pl in candidates:
            if pl[0] <= rng[0] and rng[1] <= pl[1]:
                found.append(pl)
            elif pl[0] == rng[0] or rng[1] == pl[1]:
                garbage.append(pl)
            elif pl[0] < rng[0] or rng[1] < pl[1]:
                puramierda.append(pl)

        lfound = len(found)
        if lfound == 1:
            return found[0]

        if lfound == 0:
            lgarbage = len(garbage)
            if lgarbage == 1:
                errors.append('found garbage for %s %s' % (drug, rng))
                toshow = garbage
                ret = garbage[0]
            else:
                if lgarbage > 1 or len(puramierda):
                    errors.append('found PURA MIERDA for %s %s' % (drug, rng))
                    toshow = garbage + puramierda
                else:
                    errors.append('no dice for %s %s' % (drug, rng))
                    toshow = candidates
                ret = None
        elif lfound > 1:
            found2 = []
            for pl in found:
                if ((pl[0] == rng[0] <= rng[1])
                        or (rng[0] <= rng[1] == pl[1])):
                    found2.append(pl)

            if len(found2) == 1:
                ret = found2[0]
            else:
                (_, imin) = mm.minmax((t[1] - t[0] for t in found),
                                      warg=True)[0]
                ret = found[imin]

            errors.append('too many dice for %s %s:' % (drug, rng))
            toshow = found

        for t in toshow:
            errors.append('  %s' % (t, ))
        errors.append('')

        return ret
Exemple #5
0
    def resolve(rng, candidates):
        assert rng[0] <= rng[1]

        found = []
        garbage = []
        puramierda = []

        for pl in candidates:
            if pl[0] <= rng[0] and rng[1] <= pl[1]:
                found.append(pl)
            elif pl[0] == rng[0] or rng[1] == pl[1]:
                garbage.append(pl)
            elif pl[0] < rng[0] or rng[1] < pl[1]:
                puramierda.append(pl)

        lfound = len(found)
        if lfound == 1:
            return found[0]

        if lfound == 0:
            lgarbage = len(garbage)
            if lgarbage == 1:
                errors.append('found garbage for %s %s' % (drug, rng))
                toshow = garbage
                ret = garbage[0]
            else:
                if lgarbage > 1 or len(puramierda):
                    errors.append('found PURA MIERDA for %s %s' % (drug, rng))
                    toshow = garbage + puramierda
                else:
                    errors.append('no dice for %s %s' % (drug, rng))
                    toshow = candidates
                ret = None
        elif lfound > 1:
            found2 = []
            for pl in found:
                if ((pl[0] == rng[0] <= rng[1]) or
                    (rng[0] <= rng[1] == pl[1])):
                    found2.append(pl)

            if len(found2) == 1:
                ret = found2[0]
            else:
                (_, imin) = mm.minmax((t[1]-t[0] for t in found), warg=True)[0]
                ret = found[imin]

            errors.append('too many dice for %s %s:' % (drug, rng))
            toshow = found

        for t in toshow:
            errors.append('  %s' % (t,))
        errors.append('')

        return ret
Exemple #6
0
    def step(self, action):
        # Execute one time step within the environment (each player makes a move)
        self.game.play(action, self.game.current_player)
        if (not self.game.get_status()):
            self.game.play(find_best_move(minmax(self.game,4)), self.game.current_player) 
            self.game.get_status()
        self.steps += 1
        reward = float(-self.game.winner) / self.steps 
        
        done = self.game.get_status()

        obs = self.game.board
        return obs, reward, done, {} #TODO was ist {}
Exemple #7
0
def sp2ts(sp, bn=None, binwidth=1):
    #  SP2TS Converts spike times to time series.
    #
    #  TS = SP2TS(SP, BN, BINWIDTH) returns a time series with bin
    #  width, BINWIDTH, with boundaries, BN(1:2), when given a vector
    #  of spike times, SP.
    #       If omitted, BN defaults to [minmax(SP),1].
    # Spike times are in ms and

    # Origninal MATLAB Code adapted from:
    # Bijan Pesaran

    # Author: Seth Richards
    # Version Date: 2020/06/11

    # THIS VERSION DOES NOT WORK WITH NON INTEGER BIN SIZE

    if bn is None:
        bn = [np.transpose(minmax(sp)), 1]

    if bn.shape[1] < 3:
        bn[2] = 1e3

    ts = []
    diffTemp = np.multiply(abs(bn[1] - bn[0]), bn[2])
    x = np.linspace(bn[0], bn[1], np.true_divide(diffTemp, binwidth + 1))

    if isinstance(sp, dict):

        for tr in sp:
            historgamSet = np.true_divide(sp[tr], bn[2])

            # throwAway sets values of ts_tmp to bin size per bin
            ts_tmp, cthrowAway = np.histogram(historgamSet, np.int(x))
            ts1 = [0, ts_tmp[1:-2], 0]
            ts = np.array([ts, ts1])

    else:
        # throwAway sets values of ts_tmp to bin size per bin
        ts_tmp, throwAway = np.histogram(sp, x)
        ts = [0, ts_tmp[1:-2], 0]

    return ts
Exemple #8
0
def _range(seq):
    if not seq: return 0, None
    min_, max_ = mm.minmax(seq)
    return max_ - min_, min_, max_
Exemple #9
0
import minmax
print(minmax.minmax(minmax.lessthan, 's', 'p', 'a', 'a'))
Exemple #10
0
def lims(col):
    vals = tuple(x for x in col if x is not None)
    return mm.minmax(vals) if len(vals) else (None, None)
Exemple #11
0
game = Game(BOARD_WIDTH, BOARD_HIGHT)
print(game.board)
# game.current_player= 1
# game.play(2, 1)
# game.play(2, -1)
# game.play(4, 1)
# game.play(4, -1)




# before = datetime.datetime.now()
# minmax(game,7)
# after = datetime.datetime.now()
# print(after-before)
print(find_best_move(minmax(game,4)))




input = np.fliplr(np.rot90(game.board, axes=(1,0)))

print(Back.BLUE, end ="")
for i in range(len(input)):
    for j in range(len(input[i])):
        if input[i][j]==-1:
            print('\033[31m' + "\u25CF" , end =" ")
        elif input[i][j]==1:
            print('\033[33m' + "\u25CF" , end =" ")
        else:
            print('\033[30m' + "\u25CF" , end =" ")
 def test_same_item_multiple_times(self):
     self.assertIterableEqual(minmax([8, 8, 8]), (8, 8))
     self.assertIterableEqual(minmax([7, 5, 6, 5, 7]), (5, 7))
 def test_with_out_of_order_numbers(self):
     self.assertIterableEqual(minmax([10, 8, 7, 5.0, 3, 6, 2]), (2, 10))
Exemple #14
0
def lims(col):
    vals = tuple(x for x in col if x is not None)
    return mm.minmax(vals) if len(vals) else (None, None)
import numpy as np
from minmax import minmax

# Example 1:
X = np.array([0, 15, -9, 7, 12, 3, -21])
print(minmax(X))
# Output:
# array([0.58333333, 1.        , 0.33333333, 0.77777778, 0.91666667,
#  0.66666667, 0.        ])

# Example 2:
Y = np.array([2, 14, -13, 5, 12, 4, -19])
print(minmax(Y))
# Output:
# array([0.63636364, 1.        , 0.18181818, 0.72727273, 0.93939394,
#        0.6969697 , 0.        ])
Exemple #16
0
#    mmax=None
#    def __init__(self, mmin = -10, mmax = 10):
#        MinMax.mmin = mmin
#        MinMax.mmax = mmax
#    
#    def random(self):
#        return random.randrange(self.mmin, self.mmax)
#        
#    def prinT(self):
#        print "Minium {min}, maximum {max}".format(min=MinMax.mmin, max=MinMax.mmax)
        
# TODO
# Parse imported arguments
       

m1 = minmax.minmax()

math_action = ('+', '-', '*', '/')

question="Enter the number: "
line=""

while line != "quit":
	x = m1.random()
	y = m1.random()

	action=math_action[random.randrange(0,4)]
	if action == '+':
		correct = x + y
		oper = "+"
	elif action == '*':
Exemple #17
0
 def __init__(self):
     self.board = SimpleBoard()
     self.minmax = minmax.minmax()
     self.its_reds_turn = True
     self.max_depth = 6
Exemple #18
0
class main:
    while not done:

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                done = True
            if event.type == pygame.MOUSEBUTTONDOWN and not GUI and not QED:
                pos = pygame.mouse.get_pos()
                x, y = pos
                tabla.position(x, y, screen)
                tabla.drawBoard1(screen)

            if event.type == pygame.MOUSEBUTTONDOWN and GUI and not QED:
                pos = pygame.mouse.get_pos()
                x, y = pos
                if x > 200 and x < 600 and y > 200 and y < 300:
                    GUI = False
                if x > 200 and x < 600 and y > 500 and y < 600:
                    GUI = False
                    komp = True

        screen.fill(yellow)
        if GUI and not QED:
            text1 = font1.render('Igrac', True, WHITE)
            text2 = font1.render('Kompjuter', True, WHITE)
            pos = pygame.mouse.get_pos()
            x, y = pos
            if x > 200 and x < 600 and y > 200 and y < 300:
                btton(screen, 200, 200, text1, light)
                btton(screen, 200, 500, text2, dark)
            elif x > 200 and x < 600 and y > 500 and y < 600:
                btton(screen, 200, 200, text1, dark)
                btton(screen, 200, 500, text2, light)
            else:
                btton(screen, 200, 200, text1, dark)
                btton(screen, 200, 500, text2, dark)
        if QED:
            text_rect = text3.get_rect(center=(screen_width // 2,
                                               screen_height // 2))
            screen.blit(text3, text_rect)
        if not GUI and not QED:
            tabla.drawBoard1(screen)
            pygame.display.flip()
            tabla1 = copy.deepcopy(tabla)
            if tabla1.pobeda() == "red":
                QED = True
                text3 = font1.render('CRVENI JE POBEDIO', True, RED)
                text_rect = text3.get_rect(center=(screen_width // 2,
                                                   screen_height // 2))
                screen.blit(text3, text_rect)
            if tabla1.pobeda() == "white":
                QED = True
                text3 = font1.render('BELI JE POBEDIO', True, BLACK)
                text_rect = text3.get_rect(center=(screen_width // 2,
                                                   screen_height // 2))
                screen.blit(text3, text_rect)
            if tabla.turn == WHITE and komp and not QED:
                tr = minmax(DEPTH, tabla)
                tabla.drawBoard1(screen)

        pygame.display.flip()
        clock.tick(60)
    pygame.quit()
Exemple #19
0
def _range(seq):
    if not seq: return 0, None
    min_, max_ = mm.minmax(seq)
    return max_ - min_, min_, max_
Exemple #20
0
import minmax
import board
import time
import os
import time
m = minmax.minmax()
b = board.SimpleBoard()
g = board.Game()


def speed_test():
    mapstart = time.perf_counter()
    m.evaluator(b, b.RED)
    mapend = time.perf_counter()
    print("Time Elapsed: " + str(mapend - mapstart))

    mapstarter = time.perf_counter()
    m.evaluator2(b, b.RED)
    mapender = time.perf_counter()
    print("Time Elapsed2: " + str(mapender - mapstarter))
    #m.minimax(b, 4, b.RED, float('-inf'), float('inf'))


def even_fight():
    for i in range(100):
        time.sleep(0.40)
        #os.system("clear")
        mapstart = time.perf_counter()
        g.step()
        mapend = time.perf_counter()
        print("Time Elapsed: " + str(mapend - mapstart))
 def test_ordered_numbers(self):
     self.assertIterableEqual(minmax([0, 1, 2, 3, 4]), (0, 4))
 def test_strings(self):
     words = ["alfalfa", "animal", "apple", "acoustic", "axiom"]
     self.assertIterableEqual(minmax(words), ("acoustic", "axiom"))
 def test_single_item(self):
     self.assertIterableEqual(minmax([10]), (10, 10))
 def test_very_large_numbers(self):
     self.assertIterableEqual(
         minmax([2**1000, -2**1000]),
         (-2**1000, 2**1000),
     )
 def test_negative_numbers(self):
     self.assertIterableEqual(minmax([-10, -8, -7, -5, -3]), (-10, -3))
 def test_with_non_lists(self):
     self.assertIterableEqual(minmax((89, 17, 70, 9)), (9, 89))
     self.assertIterableEqual(minmax({8, 7, 5, 3, 9, 6, 2}), (2, 9))
     self.assertIterableEqual(minmax(n**2 for n in range(1, 4)), (1, 9))
     with self.assertRaises(ValueError):
         minmax(iter([]))
 def test_mixed_types(self):
     with self.assertRaises(TypeError):
         minmax(['a', 2])
Exemple #28
0
            ult_ttt.board[i].board[j] = row

choice = int(input("Type 1 to pit MTCS against Minimax, 2 to watch MCTS vs MCTS, 3 to play against MCTS: "))
while (choice != 1 and choice != 2):
    choice = int(input("Input must be 1,2 or 3: "))

if (choice == 1):
    st = State()
    Game = st.game
    player = 1
    while (Game.checkVictory() == 2):
        if (player < 0):
            print("Minimax Agent")
            temp = ultimate_ttt.ultimate_ttt()
            link_boards(Game, temp)
            temp.minmaxAgent = minmax.minmax(3)
            # code.interact(local=dict(globals(), **locals()))
            temp.last_move = (Game.last_move%10)
            chosenTile = temp.minmaxAgent.algorithm(temp, player, temp.getPossibleActions())
            pos= int(chosenTile % 10)
            game =  int((chosenTile - pos) / 10)
            Game.board[game - 1].place(player, pos)
            Game.last_move = chosenTile
            player *= -1

        else:
            print("MCTS Agent")
            Game = findNextMove(Game, player)
            player *= -1

        Game.draw()
 def test_error_on_empty_iterable(self):
     with self.assertRaises(ValueError):
         minmax([])
Exemple #30
0
#    mmin=None
#    mmax=None
#    def __init__(self, mmin = -10, mmax = 10):
#        MinMax.mmin = mmin
#        MinMax.mmax = mmax
#
#    def random(self):
#        return random.randrange(self.mmin, self.mmax)
#
#    def prinT(self):
#        print "Minium {min}, maximum {max}".format(min=MinMax.mmin, max=MinMax.mmax)

# TODO
# Parse imported arguments

m1 = minmax.minmax()

math_action = ('+', '-', '*', '/')

question = "Enter the number: "
line = ""

while line != "quit":
    x = m1.random()
    y = m1.random()

    action = math_action[random.randrange(0, 4)]
    if action == '+':
        correct = x + y
        oper = "+"
    elif action == '*':
 def test_response_min_and_max_attributes(self):
     words = ["alfalfa", "animal", "apple", "acoustic", "axiom"]
     output = minmax(words)
     self.assertIterableEqual(output.min, "acoustic")
     self.assertIterableEqual(output.max, "axiom")
Exemple #32
0
 def test_minmax(self):
     A = {randint(-100, 100) for _ in range(30)}
     expected = (min(A), max(A))
     actual = minmax(A)
     self.assertEqual(expected, actual)