示例#1
0
 def base_actions_test(self):
     ''' test to ensure that base actions don't crash '''
     game = GameInstance()
     opening_setup(game,input=randomString)
     for action in BASE_ACTIONS:
         if action=="exit": # skip exit action (or else test breaks)
             continue
         elif action=="help": # ignore help
             continue
         else:
             game.take_action(action,input=randomString)
 def base_actions_test(self):
     ''' test to ensure that base actions don't crash '''
     game = GameInstance(input_func=randomString)
     
     for action in BASE_ACTIONS:
         if action=="exit": # skip exit action (or else test breaks)
             continue
         elif action=="help": # ignore help
             continue
         else:
             command = game.parser.parse(action)
             game.take_action(command,input=randomString)
示例#3
0
 def start_instance(self):
     if self.game_instance:
         self.game_instance.quit()
     if not self.game_instance:
         self.game_instance = GameInstance(self.game_path, self.ini_path,
                                           self.port, self.just_connect)
     else:
         self.game_instance.reconnect(self.game_path, self.ini_path,
                                      self.port, self.just_connect)
     self.game_instance.set_display_mode(self.has_display)
     self.game_instance.set_game_speed(self.tps)
     self.game_instance.set_game_volume(
         self.has_sound[0] if self.has_sound else 0,
         self.has_sound[1] if self.has_sound else 0)
def splash_screen():
    '''
    display a simple splash screen which asks user to load/start game.
    '''
    while True:
        print '"Load" existing game or "start" new game?'
        input_string = raw_input("load/start? ")
        if input_string == 'load' or input_string == 'l':
            player_game = GameInstance(load=DEFAULT_SAVE_FILE)
            upper_main(player_game)
        elif input_string == 'start' or input_string == 's':
            player_game = GameInstance()
            upper_main(player_game)

        # Just so I can test stuff. (Joshua)
        elif input_string == 'debug' or input_string == 'd':
            player_game = GameInstance()
            action_list = ['exit', 'take eggs from fridge', 'look inside fridge', 'go kitchen', 'go hallway']
            # ^ Anyone know how I can have this work without it being backwards? refers to action_list.pop() below
      
            user_input.opening_setup(player_game,lambda (x): 'Joshua')
            counter = 1
            while True:
                command = player_game.parser.parse(action_list.pop()) # next command
                print "%i: %s" % (counter, command.raw)
                player_game.take_action(command)
                player_game.check_events()
                counter += 1

        else:
            invalid_input("Please enter \"load\" or \"start\"",
                input_string=input_string,
                tag='bad load/save choice') 
示例#5
0
async def on_ready():
    print('Logged in as')
    print('Name: ', bot.user.name)
    print('ID: ', bot.user.id)
    print(discord.__version__)
    print('------')
    for member in bot.get_all_members():
        print(member.name, member.id)
    print('------')
    for server in bot.servers:
        print(server.name, server.owner.name)
    print('------')
    for server in bot.servers:
        gameInstances[server.id] = GameInstance(server.id)
示例#6
0
async def on_ready():
    print('Logged in as')
    print('Name: ', bot.user.name)
    print('ID: ', bot.user.id)
    print(discord.__version__)
    print('------')
    for member in bot.get_all_members():
        print(member.name, member.id)
    print('------')
    for server in bot.servers:
        print(server.name, server.owner.name)
    print('------')
    for server in bot.servers:
        gameInstances[server.id] = GameInstance(server.id)
    if(os.path.isfile('highscores.txt')):
        with open('highscores.txt') as highscores:
            data = json.load(highscores)
            print(data)
            for element in data['players']:
                highscoreMap[element['name']] = int(element['score'])
示例#7
0
def initGame(player1, player2):
    global board
    global gameinprogress
    global gameStateVar

    board = chess.Board()
    test_fen = 'bn6/1q6/2r5/8/8/5R2/5NQ1/7B w - - 0 1'
    test_fen = 'nnnnnnnn/bbbbbbbb/nnnnnnnn/bbbbbbbb/BBBBBBBB/NNNNNNNN/BBBBBBBB/NNNNNNNN w - - 0 1'  # lol
    test_fen = 'rnbq1bnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQ1BNR w - - 0 1'
    test_fen = '4k3/8/8/8/8/8/8/2KQR3 w - - 0 1'
    test_fen = 'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1'

    board = GameInstance(starting_fen=test_fen)
    gameinprogress = True
    gameStateVar.set("White to move.")

    if (p1 == "AI" and board.is_whites_turn):
        getAIMove(turn='white')

    elif (p2 == "AI" and not board.is_whites_turn):
        getAIMove(turn='black')
示例#8
0
def main():
    game = GameInstance()
    playerArray = game.createGame()
    game_ = ET.SubElement(timeline_, "Game")
    game.startGame()  #randomizes the bracelets
    startEndGame = False

    while (not game.doorNineOpen):
        game.clearCombi()
        round_ = ET.SubElement(game_, "Round")
        players_ = ET.SubElement(round_, "Players")

        for player in playerArray:
            game.setPlayerCombi(player)

            #game.setDecisionThreshold(player,-5)                 #ANÁLISE DOS RESULTADOS APENAS, COMENTAR ESTA LINHA DEPOIS
            #game.setEmotionalMultiplier(player,2.5)                     #ANÁLISE DOS RESULTADOS APENAS, COMENTAR ESTA LINHA DEPOIS
            game.setHG3Scenario()

            player_ = ET.SubElement(players_, "Player", name=player.getName())
            ET.SubElement(player_, "Points").text = str(player.getPoints())
            ET.SubElement(player_, "Color").text = str(player.getColor())
            ET.SubElement(player_, "Type").text = str(player.getType())
            ET.SubElement(player_,
                          "Typecolor").text = game.getPlayerColorType(player)
            state_ = ET.SubElement(player_, "State")  # definir subStates
            promises_ = ET.SubElement(state_, "PromiseHistory")
            for promise in player.privateState.promiseHistory:
                ET.SubElement(
                    promises_, "Promise").text = promise[1] + " " + promise[
                        2] + " to " + promise[0] + ". Status: " + promise[3]
            ET.SubElement(state_, "DecisionThreshold").text = str(
                player.privateState.decisionThreshold)
            ET.SubElement(state_, "EmotionalMultiplier").text = str(
                player.privateState.emotionalMultiplier)
            ET.SubElement(state_, "HonorFactor").text = str(
                player.privateState.honorFactor)
            for opponent in player.privateState.opponentStateArray:
                opState_ = ET.SubElement(state_,
                                         "Opponent",
                                         name=opponent.opponentName)
                ET.SubElement(opState_, "ConsiderationValue").text = str(
                    opponent.consValue)
                ET.SubElement(opState_, "ConsiderationValuePrev").text = str(
                    opponent.consValuePrev)
                ET.SubElement(opState_,
                              "AllyCounter").text = str(opponent.nAlly)
                ET.SubElement(opState_,
                              "BetrayCounter").text = str(opponent.nBetray)

        combiA = game.combinations["a"]
        combiB = game.combinations["b"]
        combiC = game.combinations["c"]
        combinationsL_ = ET.SubElement(round_, "CombinationLots")
        combA_ = ET.SubElement(combinationsL_, "CombinationA")
        for i in range(0, 3):
            lot_ = ET.SubElement(combA_, "Lot" + str(i + 1))
            ET.SubElement(lot_, "Player", name=combiA[i][0].getName())
            ET.SubElement(lot_, "Player", name=combiA[i][1].getName())
            ET.SubElement(lot_, "Player", name=combiA[i][2].getName())
        combB_ = ET.SubElement(combinationsL_, "CombinationB")
        for i in range(0, 3):
            lot_ = ET.SubElement(combB_, "Lot" + str(i + 1))
            ET.SubElement(lot_, "Player", name=combiB[i][0].getName())
            ET.SubElement(lot_, "Player", name=combiB[i][1].getName())
            ET.SubElement(lot_, "Player", name=combiB[i][2].getName())
        combC_ = ET.SubElement(combinationsL_, "CombinationC")
        for i in range(0, 3):
            lot_ = ET.SubElement(combC_, "Lot" + str(i + 1))
            ET.SubElement(lot_, "Player", name=combiC[i][0].getName())
            ET.SubElement(lot_, "Player", name=combiC[i][1].getName())
            ET.SubElement(lot_, "Player", name=combiC[i][2].getName())
        combinations_ = ET.SubElement(round_, "Combinations")

        chosenCombination = game.calcVoting(
        )  #calculates which door is chosen for the round

        for player in playerArray:
            player_ = ET.SubElement(combinations_, player.getName())
            preferenceArray = game.preferenceDict[player.getName()]
            ET.SubElement(player_, "A").text = str(preferenceArray[0])
            ET.SubElement(player_, "B").text = str(preferenceArray[1])
            ET.SubElement(player_, "C").text = str(preferenceArray[2])

        chosenComb_ = ET.SubElement(
            round_, "ChosenCombination").text = chosenCombination

        game.setPlayerDoors(
            chosenCombination
        )  #locks the players to the respective door according to the chosen combination
        vote_ = ET.SubElement(round_, "Vote")
        voteDict = {}
        if (game.GameIterations % 2 != 0):
            for typecolor in [
                    "RED PAIR", "RED SOLO", "GREEN PAIR", "GREEN SOLO",
                    "BLUE PAIR", "BLUE SOLO"
            ]:
                voteString = game.computeVote(
                    typecolor, 20
                )  #20 is the maximum cap value for which Ally probability is 100%
                voteDict[typecolor] = voteString
        else:
            for typecolor in [
                    "CYAN PAIR", "CYAN SOLO", "MAGENTA PAIR", "MAGENTA SOLO",
                    "YELLOW PAIR", "YELLOW SOLO"
            ]:
                voteString = game.computeVote(typecolor, 20)
                voteDict[typecolor] = voteString

        if (game.GameIterations % 2 != 0):
            for typecolor in [
                    "RED PAIR", "RED SOLO", "GREEN PAIR", "GREEN SOLO",
                    "BLUE PAIR", "BLUE SOLO"
            ]:
                type_ = ET.SubElement(vote_, "Type", name=typecolor)
                type_.text = voteDict[typecolor]
                arrayType = game.getPlayerByTypecolor(typecolor)
                if (len(arrayType) > 0):
                    p1 = arrayType[0]
                    opponent = game.getOpponent(p1)
                    ET.SubElement(type_, "Opponent",
                                  name=opponent).text = voteDict[opponent]
        else:
            for typecolor in [
                    "CYAN PAIR", "CYAN SOLO", "MAGENTA PAIR", "MAGENTA SOLO",
                    "YELLOW PAIR", "YELLOW SOLO"
            ]:
                type_ = ET.SubElement(vote_, "Type", name=typecolor)
                type_.text = voteDict[typecolor]
                arrayType = game.getPlayerByTypecolor(typecolor)
                if (len(arrayType) > 0):
                    p1 = arrayType[0]
                    opponent = game.getOpponent(p1)
                    ET.SubElement(type_, "Opponent",
                                  name=opponent).text = voteDict[opponent]

        print("\nRound " + str(game.GameIterations) + ": ")
        game.computeAmbidexGame()
        print(game.printPlayerPoints())

        for player in playerArray:
            if (player.getPoints() >= 9):
                if (game.willingToLeave(player)):
                    print("Winners: " + game.getWinners())
                    startEndGame = True
                    break

        if (startEndGame):
            ET.SubElement(game_, "Winners").text = game.getWinners()
            final_ = ET.SubElement(game_, "FinalState")
            for player in playerArray:
                player_ = ET.SubElement(final_,
                                        "Player",
                                        name=player.getName())
                ET.SubElement(player_, "Points").text = str(player.getPoints())
                ET.SubElement(player_, "Color").text = str(player.getColor())
                ET.SubElement(player_, "Type").text = str(player.getType())
                state_ = ET.SubElement(player_, "State")  # definir subStates
                promises_ = ET.SubElement(state_, "PromiseHistory")
                for promise in player.privateState.promiseHistory:
                    ET.SubElement(
                        promises_, "Promise"
                    ).text = promise[1] + " " + promise[2] + " to " + promise[
                        0] + ". Status: " + promise[3]
                ET.SubElement(state_, "DecisionThreshold").text = str(
                    player.privateState.decisionThreshold)
                ET.SubElement(state_, "EmotionalMultiplier").text = str(
                    player.privateState.emotionalMultiplier)
                ET.SubElement(state_, "HonorFactor").text = str(
                    player.privateState.honorFactor)
                for opponent in player.privateState.opponentStateArray:
                    opState_ = ET.SubElement(state_,
                                             "Opponent",
                                             name=opponent.opponentName)
                    ET.SubElement(opState_, "ConsiderationValue").text = str(
                        opponent.consValue)
                    ET.SubElement(opState_,
                                  "ConsiderationValuePrev").text = str(
                                      opponent.consValuePrev)
                    ET.SubElement(opState_,
                                  "AllyCounter").text = str(opponent.nAlly)
                    ET.SubElement(opState_,
                                  "BetrayCounter").text = str(opponent.nBetray)
            game.doorNineOpen = True
示例#9
0
async def on_server_join(server):
    if(server.id not in gameInstances.keys):
        gameInstances[server.id] = GameInstance(server.id)
示例#10
0
def mainFunc():
    myGame = GameInstance()
    print('Welcome to Crafters Castle!')
    print('To play, please type in an activity. \n')
    myGame.startGame()
示例#11
0
from Map import Map
from Input import Input
from InterruptEventSystem import InterruptEventSystem
from MenuBox import MenuBox
from TextBox import TextBox
from NotificationBox import NotificationBox
from GameInstance import GameInstance
import gameMenu

# game dependencies initiation

fpsClock = pygame.time.Clock()
pygame.display.set_caption('Shooter 1, II')
background_color = pygame.Color(0, 0, 0)

game = GameInstance()

game.interruptEventSystem.Add(
    MenuBox(game, 100, 200, ["one", "two", "three"],
            [gameMenu.option1, gameMenu.option2, gameMenu.option3]))

# level setup
pygame.mixer.music.load("../music/sledpuller.it")
pygame.mixer.music.play(-1)
game.mapSystem.Update(
)  # fixes the jump at the beginning. would be best to fix the source of the problem tho.

while True:  # primary game loop
    ##### LOGIC UPDATES #####
    game.interruptEventSystem.Update()
    if not game.interruptEventSystem.HasActiveEvent(
示例#12
0
class GameManager:
    game_instance: GameInstance = None
    left_ai: BaseAI.BaseAI = None
    right_ai: BaseAI.BaseAI = None

    def __init__(self,
                 game_path,
                 port,
                 ais,
                 tps=60,
                 has_display=True,
                 has_sound=False,
                 ini_path=None,
                 just_connect=False):
        self.game_path = game_path
        self.has_display = has_display
        self.has_sound = has_sound
        self.ini_path = ini_path
        self.tps = tps
        self.port = port
        self.just_connect = just_connect
        self.game_instance = None
        self.left_ai = ais[0]
        self.right_ai = ais[1]
        self.start_instance()

    def start_game_sequence(self, stage, music, left_params, right_params):
        while True:
            try:
                return self.game_instance.start_game({
                    "stage": stage,
                    "music": music,
                    "left": left_params,
                    "right": right_params,
                })
            except ProtocolError:
                if sys.exc_info()[1].code != 12:
                    raise
                time.sleep(0.1)

    def start_instance(self):
        if self.game_instance:
            self.game_instance.quit()
        if not self.game_instance:
            self.game_instance = GameInstance(self.game_path, self.ini_path,
                                              self.port, self.just_connect)
        else:
            self.game_instance.reconnect(self.game_path, self.ini_path,
                                         self.port, self.just_connect)
        self.game_instance.set_display_mode(self.has_display)
        self.game_instance.set_game_speed(self.tps)
        self.game_instance.set_game_volume(
            self.has_sound[0] if self.has_sound else 0,
            self.has_sound[1] if self.has_sound else 0)

    def run_once(self,
                 stage,
                 music,
                 left_params,
                 right_params,
                 frame_timout,
                 input_delay,
                 max_crashes=5):
        try:
            if not self.left_ai.can_play_matchup(left_params["character"],
                                                 right_params["character"]):
                raise Exception("LeftAI cannot play as {} against {}".format(
                    chr_names[left_params["character"]],
                    chr_names[right_params["character"]]))
            if not self.right_ai.can_play_matchup(right_params["character"],
                                                  left_params["character"]):
                raise Exception("RightAI cannot play as {} against {}".format(
                    chr_names[right_params["character"]],
                    chr_names[left_params["character"]]))

            state = self.start_game_sequence(stage, music, left_params,
                                             right_params)
            left_inputs = [BaseAI.BaseAI.EMPTY] * input_delay
            right_inputs = [BaseAI.BaseAI.EMPTY] * input_delay
            self.left_ai.on_game_start(left_params["character"],
                                       right_params["character"], input_delay)
            self.right_ai.on_game_start(right_params["character"],
                                        left_params["character"], input_delay)
            while True:
                try:
                    frame_timout -= 1

                    #if frame_timout == 17500:
                    #    self.game_instance.set_health(500, 500)
                    #    self.game_instance.set_weather(13, 999, False)
                    #    self.game_instance.set_positions({"x": 40, "y": 0}, {"x": 1240, "y": 0})

                    if frame_timout <= 0:
                        self.game_instance.end_game()

                    left_inputs.append(
                        self.left_ai.get_inputs(state["left"], state["right"],
                                                state["left_objs"],
                                                state["right_objs"],
                                                state["weather"]))
                    right_inputs.append(
                        self.right_ai.get_inputs(state["right"], state["left"],
                                                 state["right_objs"],
                                                 state["left_objs"],
                                                 state["weather"]))

                    state = self.game_instance.tick({
                        "left":
                        left_inputs.pop(0),
                        "right":
                        right_inputs.pop(0),
                    })
                except GameEndedException as exc:
                    winner = exc.winner
                    if winner == 1:
                        self.left_ai.on_win(exc.left_score, exc.right_score)
                        self.right_ai.on_lose(exc.right_score, exc.left_score)
                    elif winner == 2:
                        self.right_ai.on_win(exc.left_score, exc.right_score)
                        self.left_ai.on_lose(exc.right_score, exc.left_score)
                    else:
                        self.left_ai.on_timeout(exc.left_score,
                                                exc.right_score)
                        self.right_ai.on_timeout(exc.right_score,
                                                 exc.left_score)
                    return winner, (exc.left_score,
                                    state["left"][14]), (exc.right_score,
                                                         state["right"][14])
        except ConnectionResetError:
            print("Our list of allies grows thin !")
            code = self.game_instance.fd.wait()
            print("Exit code {}".format(hex(code)))
            print("Restarting game instance...")
            self.start_instance()
            if max_crashes == 0:
                print("Too many crashes, aborting the game")
                raise
            else:
                print("Restarting game from beginning...")
                return self.run_once(stage, music, left_params, right_params,
                                     frame_timout, input_delay,
                                     max_crashes - 1)

    def run(self,
            left_params,
            right_params,
            stage=0,
            music=0,
            nb=1,
            frame_timout=float("inf"),
            input_delay=0,
            swap=False):
        result = []
        for i in range(nb):
            result.append(
                self.run_once(stage, music, left_params, right_params,
                              frame_timout, input_delay))
            if swap:
                self.left_ai, self.right_ai = self.right_ai, self.left_ai
                left_params, right_params = right_params, left_params
        return result
示例#13
0
    async def init_game(self, player1: Player, player2: Player):
        game = GameInstance(player1, player2)
        self.gamehub[player1] = game
        self.gamehub[player2] = game

        await game.action()
示例#14
0
def reset():
    clientAddr = request.environ["REMOTE_ADDR"]
    games[clientAddr] = GameInstance()
    print("Клиент ",clientAddr, " получил город: ", games[clientAddr].chosenCity)
    return redirect('/game')
示例#15
0
文件: GameTheory.py 项目: Wutus/GameT
 def get_instance(self, start_state):
     return GameInstance(self.terminuses, self.start_state,
                         self.get_legal_moves_from, self.terminus_win)