예제 #1
0
    def crossover(self, father, mother, name, useCrossover=True):
        # print("Crossing ", father.name, "with", mother.name, end="")
        fatherDNA = father.DNA()
        motherDNA = mother.DNA()

        if useCrossover:
            # generate new DNA based on random crossover point
            crossoverPoint = random.randint(0, fatherDNA.size - 1)
            newDNA = np.concatenate(
                [fatherDNA[:crossoverPoint], motherDNA[crossoverPoint:]])
        else:
            # randomly choose DNA elements from father or mother
            newDNA = np.zeros(fatherDNA.size)
            for i in range(fatherDNA.size):
                if random.random() > 0.5:
                    newDNA[i] = fatherDNA[i]
                else:
                    newDNA[i] = motherDNA[i]

        # create a child with newDNA
        area = pygame.Rect(-BORDER_SIZE, -BORDER_SIZE,
                           SCREEN_WIDTH + 2 * BORDER_SIZE,
                           SCREEN_HEIGHT + 2 * BORDER_SIZE)
        gameModel = GameModel(area, asteroidsNumber=ASTEROID_NUMBER)

        child = AIPlayer(gameModel, name)
        child.setFromDNA(newDNA)
        # print("=> child:", child.name)
        return child
예제 #2
0
def get_newgame():
    scene = Scene()
    model = GameModel()
    controller = GameController(model)
    # view
    hud = HUD()
    view = GameView(model, hud)

    # set controller in model
    model.set_controller(controller)

    # add controller
    scene.add(controller, z=1, name="controller")
    scene.add(hud, z=3, name="hud")
    scene.add(view, z=2, name="view")

    return scene
예제 #3
0
def get_newgame():
    scene = Scene()
    model = GameModel()
    controller = GameController(model)
    # 视图
    hud = HUD()
    view = GameView(model, hud)

    # 模型中的控制器
    model.set_controller(controller)

    # 添加控制器
    scene.add(controller, z=1, name="controller")
    scene.add(hud, z=3, name="hud")
    scene.add(view, z=2, name="view")

    return scene
예제 #4
0
def get_newgame(level=1):
    status.score = 0
    status.level = level

    scene = Scene()
    model = GameModel(hud_offset=director.window.get_size()[0] - 800)  # MAGIC original width
    controller = GameController(model)
    # view
    hud = HUD()
    view = GameView(model, hud)

    # set controller in model
    model.set_controller(controller)

    # add controller
    scene.add(controller, z=1, name="controller")
    scene.add(hud, z=3, name="hud")
    scene.add(view, z=2, name="view")

    return scene
예제 #5
0
def get_newgame(level = 1):
    status.score = 0
    status.level = level

    scene = Scene()
    model = GameModel(hud_offset=director.window.get_size()[0]-800) #MAGIC original width
    controller = GameController(model)
    # view
    hud = HUD()
    view = GameView(model, hud)

    # set controller in model
    model.set_controller(controller)

    # add controller
    scene.add(controller, z=1, name="controller")
    scene.add(hud, z=3, name="hud")
    scene.add(view, z=2, name="view")

    return scene
예제 #6
0
 def __init__(self, nbPlayers):
     self.fitnessDict = {}
     for i in range(nbPlayers):
         area = pygame.Rect(-BORDER_SIZE, -BORDER_SIZE,
                            SCREEN_WIDTH + 2 * BORDER_SIZE,
                            SCREEN_HEIGHT + 2 * BORDER_SIZE)
         gameModel = GameModel(area, asteroidsNumber=ASTEROID_NUMBER)
         player = AIPlayer(gameModel, "g0p" + str(i))
         self.add(player)
     self.generationNumber = 0
     self.display = GameDisplay()
     self.currentGenerationNumber = 0
예제 #7
0
class GameController():
    """
        (MVC) Class that control model and view

    """
    
    def __init__(self):
        self.game = GameModel()
        self.view = GameView(self)
        self.main_loop = None

    def handle_input(self, key):
        if key == 'f12':
            self.confirm_exit()
        else:
            pass

    def confirm_exit(self):
        self.game.exit_request()
        if self.view.confirm_exit():
            raise urwid.ExitMainLoop()

    def refresh(self, _loop, _data):
        self.view.refresh_view()
        self.main_loop.draw_screen()
        self.main_loop.set_alarm_in(1, self.refresh)

    def get_game_mode(self):
        return self.game.get_game_mode()

    def main(self):


        self.main_loop = urwid.MainLoop(self.view.layout, self.view.palette, unhandled_input=self.handle_input)
        self.main_loop.set_alarm_in(0, self.refresh)
        self.main_loop.run()
예제 #8
0
    def __init__(self, app):
        self.restart_pressed = False
        self.already_won = False
        self.total_cur_words_n = 0
        self.app = app
        self.game_model = GameModel()

        self.player_views = []
        for i, cards in enumerate(self.game_model.cards):
            name = "player {}".format(i + 1)
            self.player_views.append(PackView(name, cards))

        self.open_view = PackView("open", self.game_model.cards_open)
        self.open_view.switch_to_open_view()
        self.hidden_view = PackView("hidden", self.game_model.cards_hidden)
        self.hidden_view.switch_to_hidden_view()

        self.question_view = QuestionView(
            self.game_model.questions_in_hand_number,
            self.game_model.players_number)
        self.question_view.set_questions(self.game_model.players_questions[0])

        self.board_view = BoardView(self.player_views, self.open_view,
                                    self.hidden_view, self.question_view)

        self.question_view.question_clicked.connect(
            self.question_button_clicked)
        self.board_view.next_turn_button.clicked.connect(
            self.nex_player_button_clicked)
        self.board_view.restart_button.clicked.connect(self.restart_clicked)

        self.update_tables_for_cur_player()
        self.update_tips()
        self.update_views()

        self.board_view.next_turn_button.setDisabled(True)
예제 #9
0
    def __init__(self):

        #create main window
        self.root = Tk()
        self.root.title("Natnicha's Minesweeper")
        self.root.resizable(False, False)
        while (True):
            self.mainmenu = MainMenu(self.root)
            self.root.mainloop()
            self.height = self.mainmenu.height
            self.width = self.mainmenu.width
            self.mines = self.mainmenu.mines
            self.model = GameModel(self.height, self.width, self.mines)
            self.controller = BoardController(self.model)
            self.view = Square(self.root, self.controller, self.model,
                               self.height, self.width)
            self.root.mainloop()
예제 #10
0
 def __init__(self):
     self.game = GameModel()
     self.view = GameView(self)
     self.main_loop = None
예제 #11
0
class GameController():
    def __init__(self, app):
        self.restart_pressed = False
        self.already_won = False
        self.total_cur_words_n = 0
        self.app = app
        self.game_model = GameModel()

        self.player_views = []
        for i, cards in enumerate(self.game_model.cards):
            name = "player {}".format(i + 1)
            self.player_views.append(PackView(name, cards))

        self.open_view = PackView("open", self.game_model.cards_open)
        self.open_view.switch_to_open_view()
        self.hidden_view = PackView("hidden", self.game_model.cards_hidden)
        self.hidden_view.switch_to_hidden_view()

        self.question_view = QuestionView(
            self.game_model.questions_in_hand_number,
            self.game_model.players_number)
        self.question_view.set_questions(self.game_model.players_questions[0])

        self.board_view = BoardView(self.player_views, self.open_view,
                                    self.hidden_view, self.question_view)

        self.question_view.question_clicked.connect(
            self.question_button_clicked)
        self.board_view.next_turn_button.clicked.connect(
            self.nex_player_button_clicked)
        self.board_view.restart_button.clicked.connect(self.restart_clicked)

        self.update_tables_for_cur_player()
        self.update_tips()
        self.update_views()

        self.board_view.next_turn_button.setDisabled(True)

    def start(self):
        self.board_view.showMaximized()
        self.app.exec_()
        return self.restart_pressed

    def question_button_clicked(self, str):
        if str.lower().startswith("player"):
            self.game_model.player_to_ask_choosen(str)
            self.update_tables_for_cur_player()
            self.question_view.disable_all()
            self.update_views()
            self.update_tips()
            self.board_view.next_turn_button.setEnabled(True)
        else:
            question = str.split(" ")
            self.game_model.question_chosen(question)
            self.question_view.change_player_question_mode(False)
            #self.update_views()
            #self.update_tips()

    def update_views(self):
        if not self.already_won:
            self.question_view.set_questions(
                self.game_model.get_cuurent_player_questions())
            info_text = ""
            answer_text = " "
            if self.game_model.game_state == GameState.PLAYER_TO_ASK_CHOOSING:
                question = ''.join(s + " "
                                   for s in self.game_model.question_gonna_ask)
                info_text = "Question is {}. Choose the player to ask".format(
                    question)
            elif self.game_model.game_state == GameState.QUESTION_CHOOSING:
                self.question_view.hide_player_button_but_show_others(
                    self.game_model.current_turn_player)
                info_text = "Choose the question to ask"
            elif self.game_model.game_state == GameState.CURRENT_PLAYER_FINISHED:
                info_text = "click 'Next player' when you finished"
                answer_text = "Answer: " + self.game_model.last_answer

            self.board_view.info_label.setText("Player {} turn. ".format(
                self.game_model.current_turn_player + 1) + info_text)
            self.board_view.answer_label.setText(answer_text)

            self.update_hide_show_views()
            self.update_tables_for_cur_player()

    def update_hide_show_views(self):
        for i, view in enumerate(self.player_views):
            if (i == self.game_model.current_turn_player):
                view.switch_to_open_view()
            else:
                view.switch_to_hidden_view()

    def update_tables_for_cur_player(self):
        possible_variant, varian_numbers, total_number = self.game_model.get_possible_states_for_cur_player(
        )
        self.total_cur_words_n = total_number
        self.hidden_view.update_tables(possible_variant[0], varian_numbers[0],
                                       total_number)
        for i, view in enumerate(self.player_views):
            if i != self.game_model.current_turn_player:
                view.update_tables(possible_variant[i + 1],
                                   varian_numbers[i + 1], total_number)

        if (len(possible_variant[0]) == 1) and not self.already_won:
            self.already_won = True
            self.hidden_view.show_both()
            self.board_view.restart_button.show()
            self.board_view.next_turn_button.hide()
            self.board_view.answer_label.hide()
            self.board_view.info_label.setText(
                "Player {} won, congratulation!!!. To play again press 'Restart' button"
                .format(self.game_model.current_turn_player + 1))

    def update_tips(self):
        tips = self.game_model.get_tips_for_cur_player()

        players = [1, 2, 3]
        players.remove(self.game_model.current_turn_player + 1)

        self.question_view.setTips(tips, players, self.total_cur_words_n)

    def nex_player_button_clicked(self):
        self.game_model.next_turn()
        self.game_model.start_turn()
        self.update_views()
        self.update_tips()
        self.question_view.change_player_question_mode(True)
        self.board_view.next_turn_button.setDisabled(True)

    def restart_clicked(self):
        self.restart_pressed = True
        self.app.quit()
예제 #12
0
def printPocket(game: GameModel):
    print("Money in pocket:")
    printScores(game.getActivePlayers(), game.getPocket())
예제 #13
0
def printBank(game: GameModel):
    print("Money in the bank:")
    printScores(game.getPlayers(), game.getBank())
예제 #14
0
def main():
    printBanner()

    # ==============================<Game Setup>============================== #
    # Player name entry
    name = input("Please enter your name: ").strip()
    while not name:
        name = input("Please enter your name: ").strip()

    players = list()
    players.append(name)
    players += getPlayerNames(
        "Please enter opponent names, followed by a blank line: ")

    if len(players) == 1:
        print("No opponents entered, exiting out")
        exit(1)

    print("\nCreating a game with players: ", end='')
    for i in range(0, len(players)):
        if i != 0:
            print(', ', end='')

        print(players[i], end='')
        if players[i] == name:
            print(' (You)', end='')
    print('\n')

    game = GameModel(players)

    # =============================<Game Rounds>============================== #
    gameRound = 1
    while gameRound <= 5:
        printRoundBanner(gameRound)
        game.startRound()

        turnCounter = 1
        wasBust = False
        while not wasBust:
            printTurnBanner(turnCounter)

            bustChance = simplifyFraction(game.chanceBust())

            printBank(game)
            print()
            printPocket(game)

            print()
            print("Chance of a bust this round is " + str(bustChance[0]) +
                  "/" + str(bustChance[1]) + " (" +
                  str(round(float(bustChance[0]) / bustChance[1], 2)) + ")")
            print("Expected payout this round is " +
                  str(round(game.expectedPayout())))
            print("Leftover treasure on retreat is " + str(game.getLeftover()))
            if game.artifact:
                print("This round's artifact is available")
            elif game.artifactShown:
                print("This round's artifact has been claimed")
            else:
                print("This round's artifact is still hidden")

            print()

            # ===================<Gather Round Information>=================== #
            players = getPlayerNames(
                "Enter the names of all players who retreated: ")
            game.playersRetreat(players)
            if len(game.getActivePlayers()) == 0:
                print("All explorers have retreated")
                break  # Break when there are no more active players

            choice = input(
                "What was the last turn? Artifact (a), Treasure (t), or Hazard (h): "
            ).strip()
            while len(choice) == 0 or (choice[0].upper()
                                       not in ['A', 'T', 'H']):
                choice = input(
                    "What was the last turn? Artifact (a), Treasure (t), or Hazard (h): "
                ).strip()

            if choice[0].upper() == 'A':
                game.gotArtifact()
            elif choice[0].upper() == 'T':
                choice = input(
                    "What is the value of the treasure card: ").strip()
                while len(choice) == 0 or not choice.isnumeric():
                    choice = input(
                        "What is the value of the treasure card: ").strip()
                game.gotTreasure(int(choice))
            elif choice[0].upper() == 'H':
                choice = input("What was the type of the hazard" +
                               str(game.hazardTypes) + ": ").strip()
                while choice not in game.hazardTypes:
                    choice = input("What was the type of the hazard" +
                                   str(game.hazardTypes) + ": ").strip()
                wasBust = game.isBust(choice)

            turnCounter += 1

        print("===<ROUND END>===")
        gameRound += 1
예제 #15
0
import pygame

from GameModel import GameModel
from GeneticAlgorithm import GeneticAlgorithm
from Parameters import *

area = pygame.Rect(-BORDER_SIZE, -BORDER_SIZE, SCREEN_WIDTH + 2 * BORDER_SIZE, SCREEN_HEIGHT + 2 * BORDER_SIZE)
game = GameModel(area, asteroidsNumber=ASTEROID_NUMBER)
ga = GeneticAlgorithm(100, 100)