예제 #1
0
def main():
	print(GREET_STRING)
	gamestate = Gamestate()

	print("You are on page", gamestate.getCurrentPage())
	print("Your goal destination is", gamestate.getTarget(), "\n")
	while True:
		prompt = input('From here you can do the followning: \
			\n Type "where" to look at links you can click \
			\n Type "target" to see your target link again \
			\n Type "exit" to quit the game \
			\n Type "go" or "go "Title"" to follow a link \n \
			\nPlease Enter A Command: ')

		if prompt[0:2] == 'go':
			goToLink(prompt, gamestate)

		elif prompt == 'path':
			print(gamestate.getPath())

		elif prompt == 'target':
			print(gamestate.getTarget(), "\n")

		elif prompt == 'exit':
			quit()

		elif prompt == 'where':
			listAllLinks(gamestate)

		else:
			print('That was not a valid commmand, please try again \n')

		if gamestate.isWin():
			print('You win in ' + str(gamestate.getNumClicks()) + ' clicks')
			break;
예제 #2
0
    def resetGame(self):
        """
		Reset the game to start position
		"""
        print "Game Reset using skill level:" + str(
            self.skillLevel) + " and move time:" + str(self.moveTime)
        self.theGame = None
        self.theGame = Gamestate.GameState(self.skillLevel, self.moveTime)
        self.chessEng.setUpForNewGame(self.theGame.getSkillLevel())
예제 #3
0
 def __init__(self, aSkillLevel, aMoveTime):
     print "Game start"
     #Set skill level and move time to start up values
     self.skillLevel = aSkillLevel
     self.moveTime = aMoveTime
     self.chessEng = StockfishEng.StockFishEng()
     #Setup the game pass skill level and movetime
     self.theGame = Gamestate.GameState(self.skillLevel, self.moveTime)
     self.chessEng.setUpForNewGame(self.theGame.getSkillLevel())
     self.running = True
예제 #4
0
# BLOKUS.PY
# Main file containing setup and gameplay loop

import sys
import numpy as np
import Pieces
import Players
import HumanPlayer
import MaxnPlayers
import MCTSPlayers
import Gamestate

# Initialize current gamestate variable
curr = Gamestate.Gamestate()
referenceHand = Gamestate.initHand()  # for checks, etc.

# Fill list of players with humans and AIs, based on player input
players = dict()
for i in range(1, 5):
    print("Is player %d AI or human?" % i)
    print("(0 for human, 1 for AI)")
    success = False

    while not success:
        try:
            n = int(raw_input())
            if n != 0 and n != 1 and n != 2 and n != 3 and n != 4 and n != 5 and n != 6:
                print("Please enter zero or one only")
            else:
                success = True
        except ValueError as e:
예제 #5
0
 def __init__(self, color):
     self.color = color
     self.referenceHand = Gamestate.initRefHand()
예제 #6
0
파일: Search.py 프로젝트: rishikanthc/AI
def main(args):
    file = args.input

    print "--BFS--"
    tic = time.clock()
    gameBFS = Gamestate.game(file)
    tracing_state=gameBFS
    res = BreadthFirstSearch(gameBFS)
    toc = time.clock()
    timeBFS = toc - tic
    print "Nodes Expanded: ",res.nodesExpanded
    print "Number of Moves:", len(res.trace)/2
    print "Max Depth of Queue", maxqueueSize
    print "Memory:", maxqueueSize*getsizeof(Gamestate), "Bytes"
    print "Solution Path:"
    for i in range(0,len(res.trace),2):
        tracing_state.gameState[res.trace[i+1][0]][res.trace[i+1][1]]=tracing_state.gameState[res.trace[i][0]][res.trace[i][1]]
        tracing_state.gameState[res.trace[i][0]][res.trace[i][1]]=0
        for row in tracing_state.gameState:
            printArray([str(x) for x in row])
        print
    print "Running Time: ", timeBFS
    print

    tic = time.clock()
    gameDFS = Gamestate.game(file)
    tracing_state=gameDFS
    res = DepthFirstSearch(gameDFS,10)
    toc = time.clock()
    timeDFS = toc - tic
    print "--DFS--"
    print "Nodes Expanded: ",res.nodesExpanded
    print "Number of Moves:", len(res.trace)/2
    print "Max Depth of Stack:", maxstackSize
    print "Memory:", maxstackSize*getsizeof(Gamestate), "Bytes"
    print "Solution Path:"
    for i in range(0,len(res.trace),2):
        tracing_state.gameState[res.trace[i+1][0]][res.trace[i+1][1]]=tracing_state.gameState[res.trace[i][0]][res.trace[i][1]]
        tracing_state.gameState[res.trace[i][0]][res.trace[i][1]]=0
        for row in tracing_state.gameState:
            printArray([str(x) for x in row])
        print
    print "Running Time: ", timeDFS
    print

    print "--Astar--"
    tic = time.clock()
    gameAstar = Gamestate.game(file)
    tracing_state=gameAstar
    res = astar(gameAstar)
    toc = time.clock()
    timeAstar = toc - tic
    print "Nodes Expanded: ",res.nodesExpanded
    print "Number of Moves:", len(res.trace)/2
    print "Max Depth of Queue", pqSize
    print "Memory:", pqSize*getsizeof(Gamestate), "Bytes"
    print "Solution Path:"
    for i in range(0,len(res.trace),2):
        tracing_state.gameState[res.trace[i+1][0]][res.trace[i+1][1]]=tracing_state.gameState[res.trace[i][0]][res.trace[i][1]]
        tracing_state.gameState[res.trace[i][0]][res.trace[i][1]]=0
        for row in tracing_state.gameState:
            printArray([str(x) for x in row])
        print
    print "Running Time: ", timeAstar
예제 #7
0
def load_game():
    player = Gamestate.load("gamestate.json")
예제 #8
0
    def getMove(self, update):
        """Prompted with gamestate, return move chosen by MCTS with tree loaded from file."""

        # If this is the first time getMove is called, either read root from file
        # or initialize new one. Then set 'current' to last known gamestate
        if not hasattr(self, 'root'):
            if persistentMCPlayer.shouldReadTree:
                self.root = self.readTree()
            else:
                self.root = MCTree.MCNode(Gamestate.Gamestate())
            self.current = self.root

        # Determine which moves have been made by each player in order to
        # move 'current' down the tree to the node corresponding to update
        if not self.current.gamestate.equals(update):
            colorToCheck = self.color + 1
            if colorToCheck == 5:
                colorToCheck = 1
            while True:

                # Find move made by player, then move down tree to corresponding
                # node, or create it if necessary
                moveMade = self.findMoveMade(self.current.gamestate, update,
                                             colorToCheck)

                if moveMade in self.current.children:
                    self.current = self.current.children[moveMade]
                else:
                    new_gamestate = self.current.gamestate.duplicate()
                    new_gamestate.update(moveMade)
                    self.current.children[moveMade] = MCTree.MCNode(
                        new_gamestate, parent=self.current)
                    self.current = self.current.children[moveMade]

                # Go to next player in order
                colorToCheck = colorToCheck + 1
                if colorToCheck == 5:
                    colorToCheck = 1
                if colorToCheck == self.color:
                    break

        # Then repeat Monte Carlo iterations until you run out of time

        start_time = time.time()
        while (time.time() - start_time < 30):
            self.mcIteration()

        self.current.printTree()

        # And pick best move

        move = self.highestAvgPlayoutMove(self.current)

        # Update tree to reflect path taken
        if move in self.current.children:
            self.current = self.current.children[move]
        else:
            new_gamestate = self.current.duplicate()
            new_gamestate.update(move)
            self.current.children[move] = MCNode(new_gamestate,
                                                 parent=self.current)
            self.current = self.current.children[move]

        # Then return the move to make
        print("MAKING MOVE:")
        print(move)
        print("self.current.gamestate.board:")
        print(self.current.gamestate.board)
        return (move)
예제 #9
0
    if (first_move):                                                        # If it's the first move ...                                                          
        if (not zeros_move):                                                    # ... and it's the TTF's move ...
            i = int(raw_input("Enter X in row __: "))                               # ... prompt the TTF for the coordinates of their move.
            j = int(raw_input("Enter X in col __: "))
            while (i < 0 or i > 2):                                                 # If the row number is not in {0, 1, 2} ...
                i = int(raw_input("Row should be between 0 and 2: "))               # ... prompt them again.
            while (j < 0 or j > 2):                                                 # Do the same for column number.
                j = int(raw_input("Col should be between 0 and 2: "))
            Grid[i][j] = 'X'                                                        # Put an 'X' on the grid, once you have valid coordinates.
            print("\nYou: ")                                                        # Tell the TicTacFoe that the next grid they see will show their move.
        else:                                                                       # ... otherwise if it's our (Zeros') move ...
            Grid[0][0] = '0'                                                        # ... play a default move of putting a '0' in the first row, first column.
            print("\nEarth's Mightiest Zeros: ")                                    # This default move is a significant optimization, will be covered in the document.

        state = Gamestate(Grid, not zeros_move)                                 # Now, make a Gamestate object that represents the current grid, and call it 'state'.
        
        state.make_states()                                                     # Generate the game's tree.
        state.calculate_value()                                                 # Compute each state's value.
        first_move = False                                                      # And it's no longer the first move, hence.
        
    else:                                                                   # For every move after the first one ...
        if (not zeros_move):                                                    # ... if it's the TTF's move ...
            i = int(raw_input("Enter X in row __: "))                               # ... prompt the TTF for the coordinates of their move.
            j = int(raw_input("Enter X in col __: "))
            while (i < 0 or i > 2):                                                 # If the row number is not in {0, 1, 2} ...
                i = int(raw_input("Row should be between 0 and 2: "))               # ... prompt them again.
            while (j < 0 or j > 2):                                                 # Do the same for column number.
                j = int(raw_input("Col should be between 0 and 2: "))
            while (isCross(state.grid, i, j) or isZero(state.grid, i, j)):          # Now since this is not the first move, the board may not be empty, and ...
                print "Please enter unoccupied coordinates"                         # ... we need to check that the coordinates TTF is trying to play on are empty.
예제 #10
0
파일: Search.py 프로젝트: rishikanthc/AI
def main(args):
    file = args.input

    print "--BFS--"
    tic = time.clock()
    gameBFS = Gamestate.game(file)
    tracing_state = gameBFS
    res = BreadthFirstSearch(gameBFS)
    toc = time.clock()
    timeBFS = toc - tic
    print "Nodes Expanded: ", res.nodesExpanded
    print "Number of Moves:", len(res.trace) / 2
    print "Max Depth of Queue", maxqueueSize
    print "Memory:", maxqueueSize * getsizeof(Gamestate), "Bytes"
    print "Solution Path:"
    for i in range(0, len(res.trace), 2):
        tracing_state.gameState[res.trace[i + 1][0]][res.trace[
            i +
            1][1]] = tracing_state.gameState[res.trace[i][0]][res.trace[i][1]]
        tracing_state.gameState[res.trace[i][0]][res.trace[i][1]] = 0
        for row in tracing_state.gameState:
            printArray([str(x) for x in row])
        print
    print "Running Time: ", timeBFS
    print

    tic = time.clock()
    gameDFS = Gamestate.game(file)
    tracing_state = gameDFS
    res = DepthFirstSearch(gameDFS, 10)
    toc = time.clock()
    timeDFS = toc - tic
    print "--DFS--"
    print "Nodes Expanded: ", res.nodesExpanded
    print "Number of Moves:", len(res.trace) / 2
    print "Max Depth of Stack:", maxstackSize
    print "Memory:", maxstackSize * getsizeof(Gamestate), "Bytes"
    print "Solution Path:"
    for i in range(0, len(res.trace), 2):
        tracing_state.gameState[res.trace[i + 1][0]][res.trace[
            i +
            1][1]] = tracing_state.gameState[res.trace[i][0]][res.trace[i][1]]
        tracing_state.gameState[res.trace[i][0]][res.trace[i][1]] = 0
        for row in tracing_state.gameState:
            printArray([str(x) for x in row])
        print
    print "Running Time: ", timeDFS
    print

    print "--Astar--"
    tic = time.clock()
    gameAstar = Gamestate.game(file)
    tracing_state = gameAstar
    res = astar(gameAstar)
    toc = time.clock()
    timeAstar = toc - tic
    print "Nodes Expanded: ", res.nodesExpanded
    print "Number of Moves:", len(res.trace) / 2
    print "Max Depth of Queue", pqSize
    print "Memory:", pqSize * getsizeof(Gamestate), "Bytes"
    print "Solution Path:"
    for i in range(0, len(res.trace), 2):
        tracing_state.gameState[res.trace[i + 1][0]][res.trace[
            i +
            1][1]] = tracing_state.gameState[res.trace[i][0]][res.trace[i][1]]
        tracing_state.gameState[res.trace[i][0]][res.trace[i][1]] = 0
        for row in tracing_state.gameState:
            printArray([str(x) for x in row])
        print
    print "Running Time: ", timeAstar
예제 #11
0
w = 320
h = 200
screen = pygame.display.set_mode((int(w * size_mult), int(h * size_mult)))
pygame.display.update()

images = {}
image_classes = ["misc_graphic", "cockpit", "fighter", "capship", "cutscene"]
for c in image_classes:
    for key, value in data_groups[c].items():
        images[key] = []
        for i in value.data.blocks:
            images[key].append([])
            for j in i.blocks:
                test_image = GameImage.GameImage(j)
                images[key][-1].append(test_image)

saves = {}
for key, value in data_groups["savegame"].items():
    saves[key] = []
    for i in value.data.blocks:
        saves[key].append(Gamestate.Gamestate(i))

test_image = images["recroom.vga"][0][0]

#test_image = GameImage.GameImage(data_groups["misc_graphic"]["briefing.vga"].data.blocks[7].blocks[3])
test_image.Draw(screen)
pygame.display.update()

while (1):
    if pygame.event.poll().type == pygame.KEYDOWN:
        break
예제 #12
0
from Gamestate import *

Grid = [[' ', ' ', ' '],
        [' ', ' ', ' '],
        [' ', ' ', ' ']]

state = Gamestate(Grid, True, 1)

state.make_states()

state.calculate_value()

for st in state.states:
    printToConsole(st.grid),
    print("Value: "),
    print(st.value)