Example #1
0
def run_game_with_parameters(weights, display, clock):
    numOfSteps = 2500
    appleScore = 0
    score1 = 0
    score2 = 0
    count_same_direction = 0
    prev_direction = 0
    snakePos,applePos = game.startPositions()

    for _ in range(numOfSteps):
        collisionWithWallOrSelf = 0    
        isFrontBlocked, isRightBlocked, isLeftBlocked = game.blockedDirections(snakePos)
        snakeDirectionVecNormalized ,appleDirectionVecNormalized = game.directionVectors(snakePos, applePos)
        # print("snakeDirection", snakeDirectionVecNormalized, "appleDirection", appleDirectionVecNormalized)
        
        predictedDirection = np.argmax(np.array(neuralNet.forwardPropagation(np.array([isFrontBlocked,
        isRightBlocked, isLeftBlocked, snakeDirectionVecNormalized[0], snakeDirectionVecNormalized[1],
        appleDirectionVecNormalized[0], appleDirectionVecNormalized[1]]),weights)))
        
        # print(neuralNet.forwardPropagation(np.array([isFrontBlocked,
        # isRightBlocked, isLeftBlocked, snakeDirectionVecNormalized[0], snakeDirectionVecNormalized[1],
        # appleDirectionVecNormalized[0], appleDirectionVecNormalized[1]]),weights))
        # print("predictedDirection",predictedDirection)

        # print("snakePos",snakePos)
        # print("applePos",applePos)
        # print("isLeftBlocked",isLeftBlocked)
        # print("isRightBlocked",isRightBlocked)
        # print("isFrontBlocked",isFrontBlocked)
        # print("snakeDirection",snakeDirectionVecNormalized)
        # print("applePos",appleDirectionVecNormalized)

        applePos, snakePos, appleScore = game.playGame(snakePos, applePos, appleScore, predictedDirection,display, clock)

        if predictedDirection == prev_direction:
            count_same_direction += 1
        else:
            count_same_direction = 0
            prev_direction = predictedDirection

        if game.collisionWithWall(snakePos):
                collisionWithWallOrSelf = 1

        if game.collisionWithSelf(snakePos):
                collisionWithWallOrSelf = 1 

        if collisionWithWallOrSelf == 1:
                print("colision")
                score1 = -150
                break
        if count_same_direction > 8 and predictedDirection != 0:
            score2 -= 1 
        else:
            score2 += 2          
        # score2 += -1
    print("score1",score1)
    print("score2",score2)
    print("appleScore",appleScore)    
    return score1 + score2 + 5000*appleScore                     # return 1
Example #2
0
def aiGame(heuristic1, heuristic2):
    bd = Board(playerTurn=1)
    aiplayer1 = player.aiPlayer(1, bd, heuristic1)
    aiplayer2 = player.aiPlayer(2, bd, heuristic2)
    g = playGame(aiplayer1, aiplayer2, bd)
    start = datetime.datetime.now()
    g.runGame()
    end = datetime.datetime.now()
    time = str((end - start).total_seconds())
    return time
Example #3
0
def heuristicTimeForFirstMove(heuristic):
    bd = Board(playerTurn=1)
    aiplayer1 = player.aiPlayer(1, bd, heuristic)
    manualPlayer = player.manualPlayer(2, bd)
    g = playGame(aiplayer1, manualPlayer, bd)
    start = datetime.datetime.now()
    g.p1.makeMove()
    end = datetime.datetime.now()
    time = str((end - start).total_seconds())
    return time
def main(args):
    print("Santa Paravia and Fiumaccio")
    print('---------')
    doInstructions = input('Do you want instructions (Y/N)\n')

    if doInstructions == 'y' or doInstructions == 'Y':
        print('---------')
        instructions()
    print('---------')

    numOfPlayers = int(input('How many players are there?\n'))
    if numOfPlayers < 1:
        numOfPlayers = 1
        print('1 player, GREAT!')
    if numOfPlayers > len(places):
        print('[!]: Sorry too many players (Max is %s)!' % len(places))
        print('Try again with less players please. (Maybe split into groups).')
        return
    print('---------')

    for player in range(numOfPlayers):
        name = input('You, player %s, what is your name?\n' % (player + 1))
        name = name.rstrip()
        print('Great, %s, you are owner of' % name, places[player] + '!')

        gender = input('So, %s, are you a Man or a WowMan! (M/F)\n' % name)
        if gender == 'M':
            gender = 'm'
        if gender == 'F':
            gender = 'f'

        dyfficulty = selectDifficulty(-1, name)
        print('---------')

        players.append(player.Player(player, dyfficulty, gender))

    game.playGame()
Example #5
0
import game
# 시작 파일
# 설명 및 게임 실행 코드
print("Welcome to Mafia AI\nmade by cheese98\nPress Enter to start")

input()
game.playGame(12)

print("Thank you!")
Example #6
0
#! /usr/bin/env python

import rospy
import sensor_msgs.msg
from agent import qAgent
from geometry_msgs.msg import Twist

from environment import turtleBotEnv
from qTable import qTable
from game import playGame

rospy.init_node('gameMode', log_level=rospy.DEBUG, anonymous=True)
rospy.loginfo("node Created")
env = turtleBotEnv()
qA1 = qAgent(env)
rospy.Subscriber("scan", sensor_msgs.msg.LaserScan, qA1.LaserScanProcess)
qt = qTable(env.numActions)
game = playGame(env, qA1, qt)
rospy.loginfo("Variables Initialized")

qt.epsilon = 1
qt.loadQt()
print(qt.qTable)
game.learning = False

for i in range(3000):
    rospy.loginfo("Game number= " + str(i))
    game.runGame()

    pass
Example #7
0
	def play(self,userName):
		self.cur.execute("create table if not exists rps(name varchar2(10),yscore varchar2(5),cscore varchar2(5))")
		self.con.commit()
		self.wipe()
		gameObject = playGame(userName, self.con, self.root)
		temp_scores= gameObject.myGame(self.game)
Example #8
0
def runGame(game_data, input_data, game_num):


    global PERCENT_SEASON_COMPLETED

    game_num = game_num + 1 # remove 0 game

    data = input_data[game_num]
    index_data = dict(data) # copying data so you have input csv
    if data['lineup_h_stats'] == '[]' or data['lineup_a_stats'] == '[]':
        index_data['home_sim_win'] = 'no stats'
        game_data[game_num] = index_data
        return
    home_batting = json.loads(data['lineup_h_stats'])
    away_batting = json.loads(data['lineup_a_stats'])
    stadium = json.loads(data['stadium_stats'])

    home_extra_info = {}
    away_extra_info = {}
    home_extra_info['fielding_mult_2013'] = data['fielding_mult_2013_home']
    home_extra_info['fielding_mult_2014'] = data['fielding_mult_2014_home']
    away_extra_info['fielding_mult_2013'] = data['fielding_mult_2013_away']
    away_extra_info['fielding_mult_2014'] = data['fielding_mult_2014_away']

    home_extra_info['percent_season_completed'] = PERCENT_SEASON_COMPLETED
    away_extra_info['percent_season_completed'] = PERCENT_SEASON_COMPLETED
    home_extra_info['home_away'] = 'Home'
    away_extra_info['home_away'] = 'Away'
    home_extra_info['pitcher_handedness'] = data['pitcher_a_handedness_i']
    away_extra_info['pitcher_handedness'] = data['pitcher_h_handedness_i']
    home_extra_info['pitcher_band_2013'] = data['pitcher_a_2013_era_bucket_i']
    away_extra_info['pitcher_band_2013'] = data['pitcher_h_2013_era_bucket_i']
    home_extra_info['pitcher_band_2014'] = data['pitcher_a_2014_era_bucket_i']
    away_extra_info['pitcher_band_2014'] = data['pitcher_h_2014_era_bucket_i']
    home_extra_info['stadium'] = stadium
    away_extra_info['stadium'] = stadium

    print data['home_i']
    home_results, home_details = game.playGame(home_batting, home_extra_info, ANALYSIS_RUNS)
    away_results, away_details = game.playGame(away_batting, away_extra_info, ANALYSIS_RUNS)

    if home_results == 'incomplete data' or away_results == 'incomplete data':
        index_data['home_sim_win'] = 'incomplete data'
        game_data[game_num] = index_data
        return
    home_games_won = 0
    away_games_won = 0
    total_home_runs = 0
    total_away_runs = 0
    # this needs to be # of analysis runs
    for i in range(ANALYSIS_RUNS):
        home_runs = home_results[i]
        away_runs = away_results[i]
        total_home_runs += home_runs
        total_away_runs += away_runs
        if home_runs > away_runs:
            home_games_won += 1
        elif away_runs > home_runs:
            away_games_won += 1

    index_data['home_avg_runs'] = float(total_home_runs) / float(ANALYSIS_RUNS)
    index_data['away_avg_runs'] = float(total_away_runs) / float(ANALYSIS_RUNS)
    index_data['home_avg_singles'] = sum(home_details['singles']) / float(len(home_details['singles']))
    index_data['away_avg_singles'] = sum(away_details['singles']) / float(len(away_details['singles']))
    index_data['home_avg_doubles'] = sum(home_details['doubles']) / float(len(home_details['doubles']))
    index_data['away_avg_doubles'] = sum(away_details['doubles']) / float(len(away_details['doubles']))
    index_data['home_avg_triples'] = sum(home_details['triples']) / float(len(home_details['triples']))
    index_data['away_avg_triples'] = sum(away_details['triples']) / float(len(away_details['triples']))
    index_data['home_avg_homeruns'] = sum(home_details['homeruns']) / float(len(home_details['homeruns']))
    index_data['away_avg_homeruns'] = sum(away_details['homeruns']) / float(len(away_details['homeruns']))
    index_data['home_avg_walks'] = sum(home_details['walks']) / float(len(home_details['walks']))
    index_data['away_avg_walks'] = sum(away_details['walks']) / float(len(away_details['walks']))
    index_data['home_avg_strikeouts'] = sum(home_details['strikeouts']) /float(len(home_details['strikeouts']))
    index_data['away_avg_strikeouts'] = sum(away_details['strikeouts']) /float(len(away_details['strikeouts']))
    index_data['home_avg_groundouts'] = sum(home_details['groundouts']) /float(len(home_details['groundouts']))
    index_data['away_avg_groundouts'] = sum(away_details['groundouts']) / float(len(away_details['groundouts']))
    index_data['home_avg_flyouts'] = sum(home_details['flyouts']) / float(len(home_details['flyouts']))
    index_data['away_avg_flyouts'] = sum(away_details['flyouts']) / float(len(away_details['flyouts']))
    index_data['home_avg_doubleplays'] = sum(home_details['doubleplays'])/ float(len(home_details['doubleplays']))
    index_data['away_avg_doubleplays'] = sum(away_details['doubleplays'])/ float(len(away_details['doubleplays']))
    index_data['home_avg_errors'] = sum(home_details['errors'])/float(len(home_details['errors']))
    index_data['away_avg_errors'] = sum(away_details['errors'])/float(len(away_details['errors']))

    # add percent win data to game_data
    if home_games_won != 0 or away_games_won != 0:
        home_sim_win = float(home_games_won) / (float)(home_games_won + away_games_won)
        index_data['home_sim_win'] = home_sim_win
    else:
        index_data['home_sim_win'] = 'Tried to divide by zero'
    game_data[game_num] = index_data

    return
Example #9
0
 def test_play_game(self, mock_inputs):
     guess = game.playGame()
     self.assertEqual(guess, "Tomato")  #Fails unless it guesses a Tomato
Example #10
0
#Main loop

choice = 0
while choice != 5:
    os.system('clear')
    ui.printMenu()
    
    try: # did user enter a number? 
        choice = int(input("Enter your choice: "))
    except ValueError: # i guess not :(
        print("Not a valid choice.")
        input("Press enter to continue... ")
        
    if choice == 1:
        result = game.playGame()
        processGameResult(result)                 
    elif choice == 2:
        saveData = loadsave.loadFromFile("game_data.json")
        
        if len(saveData) > 0: #is there save data?  
            result = game.playGame(saveData, True)
            processGameResult(result)
        else:
            print("No saved game.")
            input("Press enter to continue...")
    elif choice == 3:
        os.system("clear")
        highScores = loadsave.loadFromFile("high_scores.json")
        ui.printHighScores(highScores)
        input("Press enter to return to main menu... ")
Example #11
0
def showMenu():
    """
    Display the start screen
    """
    # create light theme button
    light_theme = Button(tuple(c["colour"]["light"]["2048"]), 200 - 70, 275,
                         45, 45, "light")
    # create dark theme button
    dark_theme = Button(tuple(c["colour"]["dark"]["2048"]), 270 - 70, 275, 45,
                        45, "dark")

    # initialise theme
    theme = ""
    theme_selected = False

    # create difficulty buttons
    _2048 = Button(tuple(c["colour"]["light"]["64"]), 130, 330, 45, 45, "2048")
    _1024 = Button(tuple(c["colour"]["light"]["2048"]), 200, 330, 45, 45,
                   "1024")
    _512 = Button(tuple(c["colour"]["light"]["2048"]), 270, 330, 45, 45, "512")
    _256 = Button(tuple(c["colour"]["light"]["2048"]), 340, 330, 45, 45, "256")

    # default difficulty
    difficulty = 0
    diff_selected = False

    # create play button
    play = Button(tuple(c["colour"]["light"]["2048"]), 235, 400, 45, 45,
                  "play")

    # pygame loop for start screen
    while True:
        screen.fill(BLACK)

        screen.blit(
            pygame.transform.scale(pygame.image.load("images/icon.ico"),
                                   (200, 200)), (155, 50))

        font = pygame.font.SysFont(c["font"], 15, bold=True)

        theme_text = font.render("Theme: ", 1, WHITE)
        screen.blit(theme_text, (55, 285))

        diff_text = font.render("Difficulty: ", 1, WHITE)
        screen.blit(diff_text, (40, 345))

        # set fonts for buttons
        font1 = pygame.font.SysFont(c["font"], 15, bold=True)
        font2 = pygame.font.SysFont(c["font"], 14, bold=True)

        # draw all buttons on the screen
        light_theme.draw(screen, BLACK, font1)
        dark_theme.draw(screen, (197, 255, 215), font1)
        _2048.draw(screen, BLACK, font2)
        _1024.draw(screen, BLACK, font2)
        _512.draw(screen, BLACK, font2)
        _256.draw(screen, BLACK, font2)
        play.draw(screen, BLACK, font1)

        pygame.display.update()

        for event in pygame.event.get():
            # store mouse position (coordinates)
            pos = pygame.mouse.get_pos()

            if event.type == QUIT or \
                    (event.type == pygame.KEYDOWN and event.key == K_q):
                # exit if q is pressed
                pygame.quit()
                sys.exit()

            # check if a button is clicked
            if event.type == pygame.MOUSEBUTTONDOWN:
                # select light theme
                if light_theme.isOver(pos):
                    dark_theme.colour = tuple(c["colour"]["dark"]["2048"])
                    light_theme.colour = tuple(c["colour"]["light"]["64"])
                    theme = "light"
                    theme_selected = True

                # select dark theme
                if dark_theme.isOver(pos):
                    dark_theme.colour = tuple(
                        c["colour"]["dark"]["background"])
                    light_theme.colour = tuple(c["colour"]["light"]["2048"])
                    theme = "dark"
                    theme_selected = True

                if _2048.isOver(pos):
                    _2048.colour = tuple(c["colour"]["light"]["64"])
                    _1024.colour = tuple(c["colour"]["light"]["2048"])
                    _512.colour = tuple(c["colour"]["light"]["2048"])
                    _256.colour = tuple(c["colour"]["light"]["2048"])
                    difficulty = 2048
                    diff_selected = True

                if _1024.isOver(pos):
                    _1024.colour = tuple(c["colour"]["light"]["64"])
                    _2048.colour = tuple(c["colour"]["light"]["2048"])
                    _512.colour = tuple(c["colour"]["light"]["2048"])
                    _256.colour = tuple(c["colour"]["light"]["2048"])
                    difficulty = 1024
                    diff_selected = True

                if _512.isOver(pos):
                    _512.colour = tuple(c["colour"]["light"]["64"])
                    _1024.colour = tuple(c["colour"]["light"]["2048"])
                    _2048.colour = tuple(c["colour"]["light"]["2048"])
                    _256.colour = tuple(c["colour"]["light"]["2048"])
                    difficulty = 512
                    diff_selected = True

                if _256.isOver(pos):
                    _256.colour = tuple(c["colour"]["light"]["64"])
                    _1024.colour = tuple(c["colour"]["light"]["2048"])
                    _512.colour = tuple(c["colour"]["light"]["2048"])
                    _2048.colour = tuple(c["colour"]["light"]["2048"])
                    difficulty = 256
                    diff_selected = True

                # play game with selected theme
                if play.isOver(pos):
                    if theme != "" and difficulty != 0:
                        playGame(theme, difficulty)

                # reset theme & diff choice if area outside buttons is clicked
                if not play.isOver(pos) and \
                    not dark_theme.isOver(pos) and \
                    not light_theme.isOver(pos) and \
                    not _2048.isOver(pos) and \
                    not _1024.isOver(pos) and \
                    not _512.isOver(pos) and \
                    not _256.isOver(pos):

                    theme = ""
                    theme_selected = False
                    diff_selected = False

                    light_theme.colour = tuple(c["colour"]["light"]["2048"])
                    dark_theme.colour = tuple(c["colour"]["dark"]["2048"])
                    _2048.colour = tuple(c["colour"]["light"]["2048"])
                    _1024.colour = tuple(c["colour"]["light"]["2048"])
                    _512.colour = tuple(c["colour"]["light"]["2048"])
                    _256.colour = tuple(c["colour"]["light"]["2048"])

            # change colour on hovering over buttons
            if event.type == pygame.MOUSEMOTION:
                if not theme_selected:
                    if light_theme.isOver(pos):
                        light_theme.colour = tuple(c["colour"]["light"]["64"])
                    else:
                        light_theme.colour = tuple(
                            c["colour"]["light"]["2048"])

                    if dark_theme.isOver(pos):
                        dark_theme.colour = tuple(
                            c["colour"]["dark"]["background"])
                    else:
                        dark_theme.colour = tuple(c["colour"]["dark"]["2048"])

                if not diff_selected:
                    if _2048.isOver(pos):
                        _2048.colour = tuple(c["colour"]["light"]["64"])
                    else:
                        _2048.colour = tuple(c["colour"]["light"]["2048"])

                    if _1024.isOver(pos):
                        _1024.colour = tuple(c["colour"]["light"]["64"])
                    else:
                        _1024.colour = tuple(c["colour"]["light"]["2048"])

                    if _512.isOver(pos):
                        _512.colour = tuple(c["colour"]["light"]["64"])
                    else:
                        _512.colour = tuple(c["colour"]["light"]["2048"])

                    if _256.isOver(pos):
                        _256.colour = tuple(c["colour"]["light"]["64"])
                    else:
                        _256.colour = tuple(c["colour"]["light"]["2048"])

                if play.isOver(pos):
                    play.colour = tuple(c["colour"]["light"]["64"])
                else:
                    play.colour = tuple(c["colour"]["light"]["2048"])