Example #1
0
class Game:
    def __init__(self):
        self.minBoardSize = 5
        self.maxBoardSize = 20
        self.board = Board(self.getBoardSize())
        self.board.displayBoard()
        self.Eskimo1 = Eskimo(input("Player 1, input your name:"))
        self.Eskimo2 = Eskimo(input("Player 2, input your name:"))
        self.currentPlayer = self.Eskimo1
        self.playing = False
        while self.playing:
            print("{0}, it is your turn! ".format(self.currentPlayer.getName()))
            # todo check if they lost
            # todo if they have then end, and current player lost
            self.swapPlayers()
            time.sleep(0.5)
            self.clearScreen()

    def getBoardSize(self):
        size = int(input("Please enter the size for the board: "))
        while not (self.minBoardSize < size < self.maxBoardSize):
            size = int(
                input("ERROR!: Please enter a size between {0} and {1}: ".format(self.minBoardSize, self.maxBoardSize)))
        return size

    @staticmethod
    def clearScreen():
        for x in range(30):
            print("")

    def swapPlayers(self):
        if self.currentPlayer == self.Eskimo1:
            self.currentPlayer = self.Eskimo2
        else:
            self.currentPlayer = self.Eskimo1
Example #2
0
def main():
	d = Dictionary()
	board = Board(dictionary=d)
	while len(board.words) < 150:
		print len(board.words)
		board = Board(dictionary=d)

	print board
	print "\n\ntype in p to reprint the board"
	words_found = set()

	t_end = time.time() + 60 * 2
	while time.time() < t_end:
		potential_word = raw_input("Word: ")
		if potential_word == 'p':
			print str(board) + "\n\n"
			continue
		if potential_word in words_found:
			print "You already found '{0}'".format(potential_word)
			continue
		if potential_word in board.words:
			words_found.add(potential_word)
			continue
		if not board.is_in_board(potential_word):
			print "{0} is not in the board\n".format(potential_word)
			continue
		if potential_word not in board.words:
			print "{0} is not a word\n".format(potential_word)
			continue
	print "Words found {0}: {1}".format(len(words_found), words_found)
	print "Possible words {0}: {1}".format(len(board.words), board.words)
Example #3
0
def convertBoard():
	
	fileName=askopenfilename(title = "Board Input", filetypes=[('Eagle V6 Board', '.brd'), ('all files', '.*')], defaultextension='.brd') 
	outFileName=asksaveasfilename(title="Board Output", filetypes=[('KiCad Board', '.brd'), ('all files', '.*')], defaultextension='.brd')
	
	logFile.write("*******************************************\n")
	logFile.write("Converting: "+fileName+"\n")
	logFile.write("Outputing: "+outFileName+"\n\n")
	
	try:
		
		node = getRootNode(fileName)	
		brd=Board(node)	
		brd.write(open(outFileName,"a"))
	
	except Exception as e:
		showerror("Error",str(e)+"\nSee Log.txt for more info")		
		logFile.write("Conversion Failed\n\n")
		logFile.write(traceback.format_exc())
		logFile.write("*******************************************\n\n\n")
		return
	
	logFile.write("Conversion Successfull\n\n")
	logFile.write("*******************************************\n\n\n")	
	showinfo("Board Complete","The Board Has Finished Converting")
Example #4
0
def play():
    board = Board()
    player1 = HumanPlayer('X')
    player2 = AIPlayer('O', 6)

    print "Let's play connect four!\nTo place a move, type a number [1-7]"

    current_player = player1
    other_player = player2

    winner = None
    game_over = False

    while not game_over:
        print board

        move_allowed = False
        while not move_allowed:
            move = current_player.get_move(board, other_player)
            move_allowed = board.try_place_piece(move, current_player.sign)

        game_over, winner = board.is_game_over(board.board, current_player.sign,
                                               other_player.sign)
        current_player, other_player = other_player, current_player

    print board
    if winner:
        print "Computer ", 'won!\nGame over'
    else:
        print 'Tie game!'

    ans = raw_input('Do you want to play again? y/n\n')

    if ans.lower() == 'y':
        play()
Example #5
0
class Game:
	class Player:
		X = 1
		O = -1
		def switch(player):
			return -player
	def __init__(self):
		self.player = Game.Player.X
		self.board  = Board()
		self.finish = False
	def move(self,index):
		# Converts a coordinate in a grid matrix
		# to an index for a flat array representing
		# the same matrix.
		(x,y) = index
		position = x + y*3
		self.board.place(position,self.player)
		if self.board.check(self.player):
			self.finish = True
	def next(self):
		self.player = Game.Player.switch(self.player)
	def current_player(self):
		return 'X' if self.player == Game.Player.X else 'O'
	def current_board(self):
		return self.board
	def finished(self):
		return self.finish
Example #6
0
    def test_legal_moves_combined(self):
        b = Board("""
                    1 W
                    ..k..
                    q..p.
                    .....
                    .P...
                    ....r
                    N...K
                    """)

        # get legal moves for all white pieces
        legal_moves = b.legal_moves()

        expected = []
        # knight
        expected.append(Move.from_string("a1-c2"))
        # king
        expected.append(Move.from_string("e1-e2"))
        expected.append(Move.from_string("e1-d2"))
        expected.append(Move.from_string("e1-d1"))
        # pawn
        expected.append(Move.from_string("b3-b4"))

        self.assertEqual(len(expected), len(legal_moves))
        for move in expected:
            self.assertIn(move, legal_moves)
Example #7
0
def test_endgame_heuristics():
    a = Analyzer()
    b = Board()
    b.board = [[0, 5, 0, 0, 0, 0, 0, 0],
               [0, 0, 0, 0, 999, 0, 0, 0],
               [0, 0, 0, 0, 0, 0, 0, 0],
               [0, 0, 0, 0, 0, 0, 0, 0],
               [0, 0, 0, 0, 0, 0, 0, 0],
               [0, 0, 0, 0, 0, 0, 0, 0],
               [5, 0, 0, 0, 0, 0, 0, 0],
               [0, 0, 0, 0, 0, 0, 0, -999]]

    res = a.minimax(b, 200)
    print_move_chain(a, b, res)

    b = Board()
    b.turn = -1
    b.board = [[0, -5, 0, 0, 0, 0, 0, 0],
               [0, 0, 0, 0, -999, 0, 0, 0],
               [0, 0, 0, 0, 0, 0, 0, 0],
               [0, 0, 0, 0, 0, 0, 0, 0],
               [0, 0, 0, 0, 0, 0, 0, 0],
               [0, 0, 0, 0, 0, 0, 0, 0],
               [-5, 0, 0, 0, 0, 0, 0, 0],
               [0, 0, 0, 0, 0, 0, 0, 999]]

    res = a.minimax(b, 200)
    print_move_chain(a, b, res)
Example #8
0
def main():
	board = Board(10, 10)
	board.makeEmptyBoard()
	print(board)
	board.reviveCell(1, 1)
	board.reviveCell(3, 2)
	print(board)
Example #9
0
class Game:
    def __init__(self):
        self.board = Board()
        self.evaluation = Evaluation(self.board)
        self.view = View(self.board)

    def __finish(self, computerPlayer):
        if self.evaluation.winner() == computerPlayer:
            print "Computer player wins"
        elif self.evaluation.isTie():
            print "Tie game"
        else:
            print "Human player wins"

    def run(self):
        startPlayer = self.view.inputStartPlayer()
        computerPlayer = 'X' if startPlayer == 2 else 'O'
        ai = AI(computerPlayer, self.board)
        while self.evaluation.winner() == None and not self.evaluation.isTie():
            self.view.displayBoard()
            if self.board.getPlayer() == computerPlayer:
                ai.makeMove()
            else:
                move = self.view.inputMove()
                self.board.move(move)
        self.view.displayBoard()
        self.__finish(computerPlayer)
Example #10
0
    def test_legal_moves_rook(self):
        b = Board("""
                    1 W
                    .....
                    .....
                    ..Rr.
                    .....
                    .....
                    .....
                    """)
        
        # get legal moves for white rook 'R'
        legal_moves = b.legal_moves()

        expected = []
        expected.append(Move.from_string("c4-d4"))
        expected.append(Move.from_string("c4-c3"))
        expected.append(Move.from_string("c4-c2"))
        expected.append(Move.from_string("c4-c1"))
        expected.append(Move.from_string("c4-b4"))
        expected.append(Move.from_string("c4-a4"))
        expected.append(Move.from_string("c4-c5"))
        expected.append(Move.from_string("c4-c6"))

        self.assertEqual(len(expected), len(legal_moves))
        for move in expected:
            self.assertIn(move, legal_moves)
Example #11
0
    def test_legal_moves_bishop(self):
        b = Board("""
                    1 W
                    .....
                    .....
                    ...p.
                    .p...
                    .B...
                    .....
                    """)
        
        # get legal moves for white bishop 'B'
        legal_moves = b.legal_moves()

        expected = []
        expected.append(Move.from_string("b2-a1"))
        expected.append(Move.from_string("b2-c3"))
        expected.append(Move.from_string("b2-d4"))
        expected.append(Move.from_string("b2-a3"))
        expected.append(Move.from_string("b2-c1"))
        
        expected.append(Move.from_string("b2-b1"))
        expected.append(Move.from_string("b2-a2"))
        expected.append(Move.from_string("b2-c2"))

        self.assertEqual(len(expected), len(legal_moves))
        for move in expected:
            self.assertIn(move, legal_moves)
Example #12
0
    def test_scan_one_step(self):
        b = Board("""
                    1 W
                    .....
                    .....
                    .....
                    .Kq..
                    .....
                    .....
                    """)
        startpos = (2,3)
        
        # capturing right
        movelist = []
        b.scan(movelist, startpos, 1, 0, one_step=True)
        expected = []
        expected.append(Move.from_string("b3-c3"))
        self.assertEqual(expected, movelist)

        # to the top
        movelist = []
        b.scan(movelist, startpos, 0, 1, one_step=True)
        expected = []
        expected.append(Move.from_string("b3-b4"))
        self.assertEqual(expected, movelist)
Example #13
0
    def test_scan_no_capture(self):
        b = Board("""
                    1 W
                    .....
                    .....
                    ..Qp.
                    .....
                    .....
                    .....
                    """)
        startpos = (3,4)
        
        # not capturing right
        movelist = []
        b.scan(movelist, startpos, 1, 0, no_capture=True)
        expected = []
        self.assertEqual(expected, movelist)

        # to the top
        movelist = []
        b.scan(movelist, startpos, 0, 1, no_capture=True)
        expected = []
        expected.append(Move.from_string("c4-c5"))
        expected.append(Move.from_string("c4-c6"))
        self.assertEqual(expected, movelist)
Example #14
0
def convertBoard(fileName,outFileName):
	logFile.write("*******************************************\n")
	logFile.write("Converting: "+fileName+"\n")
	logFile.write("Outputing: "+outFileName+"\n\n")
	
	try:
		
		node = getRootNode(fileName)	
		brd=Board(node)
		open(outFileName,'w').close()
		outFile=open(outFileName,"a")
		brd.write(outFile)
		outFile.close()
	
	except BaseException as e:	
		logFile.write("Conversion Failed\n\n")
		logFile.write(traceback.format_exc())
		logFile.write("*******************************************\n\n\n")
		return False, "Error Converting Board \n"+str(e)+\
					  "\nSee Log.txt for more info"

	
	logFile.write("Conversion Successfull\n\n")
	logFile.write("*******************************************\n\n\n")	
	return True,"The Board Has Finished Converting"
Example #15
0
    def test_equality(self):
        b = Board()
        b2 = Board()
        self.assertTrue(b == b2)

        b3 = Board("""
            2 W
            kqbnr
            ppppp
            .....
            .....
            PPPPP
            RNBQK
            """)
        self.assertFalse(b == b3)

        b4 = Board("""
            1 W
            kqbnr
            ppppp
            .....
            .....
            PPPPP
            RNBQK
            """)
        b4.cur_score = 123
        self.assertFalse(b == b4)
Example #16
0
def testPosition(FEN, perftdata):
    b1 = Board()
    b1.initFromFEN(FEN)
    print FEN
    print "%3s%12s%24s%24s%24s" % ("", "Nodes", "Captures", "Checks", "Castles")
    have_need = "%12s%12s" % ("Have", "Need")
    have_need *= 4
    print "%4s%1s" % ("", have_need)
    for depth in range(maxdepth):

        nextboards, nextmoves = getBoards(b1, depth + 1)
        Ncaps = len(filter(lambda (i): i == "CAPTURE", nextmoves))
        Ncast = len(filter(lambda (i): i == "CASTLE", nextmoves))
        try:
            checks = [isInCheck(board) for board in nextboards]
            checks = [check for check in checks if len(check)]
            Nchecks = len(checks)
        except:
            Nchecks = "ILLEGAL"
        print "%3s%12s%12s%12s%12s%12s%12s%12s%12s" % (
            depth,
            len(nextboards),
            perftdata[depth].Nodes,
            Ncaps,
            perftdata[depth].Captures,
            Nchecks,
            perftdata[depth].Checks,
            Ncast,
            perftdata[depth].Castles,
        )
    print
Example #17
0
 def getBoard(self,im):
   
   try:
     board = Board()
     y = self.StartY
     for i in range(0,9):
         x = self.StartX
         for j in range(0,9):
             xx = x+35
             yy = y+40
             c=0
             try:
                 pix = im[xx,yy]
                 c += pix[0]
                 c += pix[1]
                 c += pix[2]
             except Exception as e:
                 c=0
             board.getItems()[i][j].setX(x)
             board.getItems()[i][j].setY(y)
             board.getItems()[i][j].setColor(c)
             x += 71
         y+=63
   except Exception as e:
         raise Exception('Error in partionaing image.',e)
   return board
Example #18
0
File: Game.py Project: nbbn/minespy
class Game:
    def __init__(self):
        print('Welcome on my minefield')
        self.width = self.console_input('width:')
        self.height = self.console_input('height:')
        self.probability = self.console_input('chances of mine (in range 0-1, gut result with 0.1):','float')
        self.board = Board(width=self.width, height=self.height)
        self.board.set_bombs(self.probability)
        self.state = 'in_game'

    def check(self, x, y):
        board_check = self.board.check(x, y)
        if board_check == 1:
            self.state = 'game_over'
        elif board_check == 0:
            self.state = 'in_game'
        else:
            self.state = 'win'

    def console_input(self, message, form='int'):
        kontroler = False
        while kontroler == False:
            try:
                if form=='str':
                    var = str(input(message))
                elif form=='float':
                    var = float(input(message))
                else:
                    var = int(input(message))
                kontroler = True
            except ValueError:
                print('Error, not accepted format, try again')
        return var
Example #19
0
def test_capture():
    print("testing simple capture and advance")
    print("\tsimple choice white")
    b = Board()
    b.board = [[0, 0, 0, 0, 0, 0, 0, -999],
               [0, 0, 0, 0, 0, 0, 0, 0],
               [0, 1, 0, 0, 0, 0, 0, 0],
               [-1, 0, -3, 0, 0, 0, 0, 0],
               [0, 0, 0, 0, 0, 0, 0, 0],
               [0, 0, 0, 0, 0, 0, 0, 0],
               [0, 0, 0, 0, 0, 0, 0, 0],
               [0, 0, 0, 0, 0, 0, 0, 999]]
    
    a = Analyzer()
    a.sd_limit = 2
    res = a.minimax(b, 20)
    assert(res.move == ((2, 1), (3, 2)))

    print("\tsimple choice black")
    b = Board()
    b.turn = -1
    b.board = [[0, 0, 0, 0, 0, 0, 0, 999],
               [0, 0, 0, 0, 0, 0, 0, 0],
               [0, 0, 0, 0, 0, 0, 0, 0],
               [1, 0, 3, 0, 0, 0, 0, 0],
               [0, -1, 0, 0, 0, 0, 0, 0],
               [0, 0, 0, 0, 0, 0, 0, 0],
               [0, 0, 0, 0, 0, 0, 0, 0],
               [0, 0, 0, 0, 0, 0, 0, -999]]
    
    # a = Analyzer(20)
    a.sd_limit = 2
    res = a.minimax(b, 20)
    assert(res.move == ((4, 1), (3, 2)))
Example #20
0
	def test_25_board_is_well_formed(self):
	#--------------------------------------------------------------------------------
		for i in range(50):
			test = Board(i)

			# All randomly generated boards should be valid.
			self.assertTrue(test.isValid(), "Randomly generated board with " + str(81 - i) + " clues is invalid.")
Example #21
0
    def get(self):
        try:
            stage = json.loads(self.request.get("stage"))
            aiChar = pieces["aiChar"]
            playerChar = pieces["playerChar"]
            board = Board(stage)

            logging.info("Stage: {}".format(stage))
            logging.info("AIChar: {}".format(aiChar))
            logging.info("Player Char: {}".format(playerChar))
            logging.info("Turn count {}".format(len(board)))
            logging.info("Game Board:\n"+str(board))

            over,winner = board.gameOver()
            output = {"over":over,
                      "winner":winner,
                      "aiMove":-1,}
            if not over:
                aiMove = AI.takeTurn(board, aiChar, playerChar, self.easyMode)
                board.makeMove(*(list(aiMove)+[aiChar]))
                logging.info("\n"+str(board))
                output["over"], output["winner"] = board.gameOver()
                output["aiMove"] = ((aiMove[0]*3)+aiMove[1])

            if output["over"]:
                AI.reshuffle()

            self.write(json.dumps(output))
        except:
            self.render("bad.html")
Example #22
0
def read_board(filename):
    with open(filename) as f:
        data = f.readlines()
        nx = 0
        ny = 0

        first_col = data[1].index('|')
        nx = data[1][first_col:].index('|', 1) -1

        data2 = []
        for line in data:
            data2.append(''.join([x for x in line if x in '1234567890.']))

        data2 = [x for x in data2 if x]
        ny = len(data2) / nx
        # print nx, ny
        # print '\n'.join(data2)

        board = Board(nx, ny)
        for y, line in enumerate(data2):
            for x, value in enumerate(line):
                if value in '123456789':
                    board.set(x, y, int(value)-1)

        return board
Example #23
0
 def test_set_bombs(self):
     b = Board(5, 2)
     b.set_bombs(0)
     assert_equal(b._mapa, [[-2, -2, -2, -2, -2], [-2, -2, -2, -2, -2]])
     assert_equal(b.state, 'armed')
     b.set_bombs(1)
     assert_equal(b._mapa, [[-1, -1, -1, -1, -1], [-1, -1, -1, -1, -1]])
     assert_equal(b.state, 'armed')
Example #24
0
  def test_set_board_black_pawns(self):
    board = Board()
    board.set_board()

    check_sum = 0
    for i in range(8):
      check_sum += board.board[i][6].value
    
    self.assertEqual(check_sum, Square.b_pawn.value * 8)
Example #25
0
def computers_vs_computer_one():

    ships = {'P' : 2, # Patrol Boat
             'D' : 3, # Destroyer
             'S' : 3, # Submarine
             'B' : 4, # Battleship
             'A' : 5  # Aircraft Carrier
             }
    # create tron
    tron = AI_Easy()
    tron_board = Board(10,10)
    tron.place_ships(tron_board, ships)
    original_tron = Board(10,10)
    original_tron.spaces = deepcopy(tron_board.spaces);
    
    # create clu
    clu = AI_Easy()
    clu_board = Board(10,10)
    clu.place_ships(clu_board, ships)
    original_clu = Board(10,10)
    original_clu.spaces = deepcopy(clu_board.spaces);
       
    no_winner = True
    # Let the Games BEGIN!
    while no_winner:
        
        bool_ships = {'P' : True, # Patrol Boat
             'D' : True, # Destroyer
             'S' : True, # Submarine
             'B' : True, # Battleship
             'A' : True  # Aircraft Carrier
            }
        # Tron's Turn
        print "tron's turn..."
        #time.sleep( 2 )
        tron.take_turn(clu_board, original_clu)
        #clu_board.display()
        tron.which_ships_are_sunk(bool_ships, clu_board)
        if is_win(bool_ships):
            print "game over tron wins"
            break
        
        bool_ships = {'P' : True, # Patrol Boat
             'D' : True, # Destroyer
             'S' : True, # Submarine
             'B' : True, # Battleship
             'A' : True  # Aircraft Carrier
            }
        # Clu's turn
        print "Clu's turn..."
        #time.sleep( 2 )
        clu.take_turn(tron_board, original_tron)
        #tron_board.display()
        clu.which_ships_are_sunk(bool_ships, tron_board)
        if is_win(bool_ships):
            print "game over clu wins"
            break
Example #26
0
 def test_is_bomb(self):
     b = Board(5, 2)
     b._mapa = [[100, -2, -2, -2, -2], [-2, -1, 100, -2, -2]]
     c = Cell(column=0, row=0, board=b)
     assert_equal(c.is_bomb(), False)
     c = Cell(column=1, row=0, board=b)
     assert_equal(c.is_bomb(), False)
     c = Cell(column=1, row=1, board=b)
     assert_equal(c.is_bomb(), True)
Example #27
0
 def testIsFinished(self):
     self.board = Board([SimpleHut(Resource.wood,Resource.wood,Resource.clay), 
                         SimpleHut(Resource.wood,Resource.wood,Resource.clay), 
                         SimpleHut(Resource.wood,Resource.wood,Resource.clay), 
                         SimpleHut(Resource.wood,Resource.wood,Resource.clay)])
     self.assertFalse(self.board.isFinished())
     self.board = Board([SimpleHut(Resource.wood,Resource.wood,Resource.clay), 
                         SimpleHut(Resource.wood,Resource.wood,Resource.clay), 
                         SimpleHut(Resource.wood,Resource.wood,Resource.clay)])
     self.assertTrue(self.board.isFinished())
Example #28
0
 def create_Children(self, parentNode, moves):
 	parent = parentNode.access_Board()
 	for item in moves:
 		oldBoard = Board(True,parentNode.get_Board())
 		oldBoard = oldBoard.make_move(self.player_color, item[0], item[1])
 		minmaxvar = self.minmax_Opposite(parentNode.get_minmax())
 		a = random.randint(0,100)
 		newNode = TreeNode(oldBoard, minmaxvar, a)
 		newNode.set_move(item)
 		parentNode.create_Child(newNode)
Example #29
0
    def test_bonus_score(self):
        b = Board()

        # white pawn default position
        bonus = b._bonus_score((1,2), 'P')
        self.assertEqual(10, bonus)

        # black pawn default position
        bonus = b._bonus_score((1,5), 'p')
        self.assertEqual(-10, bonus)
Example #30
0
    def test___init__(self):
        b = Board(1, 2)
        with self.assertRaises(ValueError):
            Cell(column=1, row=1, board=b)
        b = Board(1, 2)
        with self.assertRaises(ValueError):
            Cell(column=1, row=2, board=b)
        b = Board(1, 2)
        with self.assertRaises(ValueError):
            Cell(column=-1, row=-1, board=b)
        b = Board(1, 2)
        c = Cell(column=0, row=1, board=b)
        assert_equal(c.board, b)

        b = Board(1, 2)
        c = Cell(column=0, row=1, board=b)
        assert_equal(c.row, 1)

        b = Board(1, 2)
        c = Cell(column=0, row=1, board=b)
        assert_equal(c.column, 0)

        b = Board(1, 2)
        c = Cell(column=0, row=1, board=b)
        assert_equal(c.state_on_board, -2)

        b = Board(5, 2)
        b._mapa = [[8, -2, -2, -2, -2], [-2, -2, 100, -2, -2]]
        c = Cell(column=0, row=0, board=b)
        assert_equal(c.state_on_board, 8)

        c = Cell(column=2, row=1, board=b)
        assert_equal(c.state_on_board, 100)
Example #31
0
    board.item[5][7] = Pawn(board, "Black", 5, 7)
    board.item[6][7] = Pawn(board, "Black", 6, 7)
    board.item[7][7] = Pawn(board, "Black", 7, 7)
    board.item[8][7] = Pawn(board, "Black", 8, 7)

    board.item[1][1] = Rook(board, "White", 1, 1)
    board.item[2][1] = Knight(board, "White", 2, 1)
    board.item[3][1] = Bishop(board, "White", 3, 1)
    board.item[4][1] = King(board, "White", 4, 1)
    board.item[5][1] = Queen(board, "White", 5, 1)
    board.item[6][1] = Bishop(board, "White", 6, 1)
    board.item[7][1] = Knight(board, "White", 7, 1)
    board.item[8][1] = Rook(board, "White", 8, 1)
    board.item[1][2] = Pawn(board, "White", 1, 2)
    board.item[2][2] = Pawn(board, "White", 2, 2)
    board.item[3][2] = Pawn(board, "White", 3, 2)
    board.item[4][2] = Pawn(board, "White", 4, 2)
    board.item[5][2] = Pawn(board, "White", 5, 2)
    board.item[6][2] = Pawn(board, "White", 6, 2)
    board.item[7][2] = Pawn(board, "White", 7, 2)
    board.item[8][2] = Pawn(board, "White", 8, 2)


board = Board()

initialize_board(board)

for i in board.item:
    print(i)
    print()
Example #32
0
    hm.HookKeyboard()

    #Initialize Bot
    ai = StupidBot()
    bot = StarjeweledBot("Starcraft II")
    resetDelay = buildNumber = buildDelay = 0

    #Main Loop
    while True:

        #Image Analysis Code
        pythoncom.PumpWaitingMessages()
        img = bot.capture()
        board = bot.getBoard(img)
        energy = bot.getEnergy(img)
        move = ai.getMove(Board(board))
        print move

        #Reset Code
        if move==None:
            resetDelay+=1
            buildDelay+=1
            if resetDelay > 10:                    
                print 'board reset!'
                print bot.getBoard(img)
                bot.clickButton('reset')
        else:
            resetDelay = 0
            try:
                bot.swapTile(move)
            except:
Example #33
0
import helpers

from copy import deepcopy
from mpi4py import MPI

from Board import Board, Mover, Winner
from helpers import Message, EVENT

comm = MPI.COMM_WORLD
RANK = comm.Get_rank()
SIZE = comm.Get_size()
MASTER_PID = 0
DEPTH = 4

BOARD = Board()


def CPU_move():
    board = deepcopy(BOARD)  # make copy of original board to simulate plays
    message = Message(EVENT.SEND_BOARD, board)
    comm.bcast(message.to_dict(), root=MASTER_PID)

    tasks = helpers.generate_tasks(BOARD.total_columns, DEPTH)
    results = dict()
    for i in range(1, BOARD.total_columns + 1):
        results[i] = list()

    while len(tasks):
        status = MPI.Status()
        # wait on message from any worker
Example #34
0
from Board import Board

from pynput import keyboard

b = Board()


def main():
    print(b)

    # Collect events until released
    with keyboard.Listener(on_press=on_press,
                           on_release=on_release) as listener:
        listener.join()


def on_press(key):
    try:
        print('alphanumeric key {0} pressed'.format(key.char))
    except AttributeError:
        print('special key {0} pressed'.format(key))


def on_release(key):
    print('{0} released'.format(key))
    if key == keyboard.Key.esc:
        # Stop listener
        return False


if __name__ == "__main__":