Ejemplo n.º 1
0
def play_game():
	while True:
		global name
		global moves
		print("\t ===========================================================================================================")
		print("")
		print("\t /////   /////   ////      //  //////  //////     ////   /////  //     //          /|    ////  ")
		print("\t //     //      //        //|  //  //  //        //      //     //     //         / |      /// ")
		print("\t ////    //     //       // |  /////   ////      //      ////   //     //        /  |      //  ")
		print("\t //        ///  //   /  ////|  //      //        //   /  //     //     //       //////    //   ")
		print("\t /////  /////    ////  //   |  //      //////     ////   /////  /////  /////        |   ////// ")
		print("")
		print("\t ===========================================================================================================")
		print("\t * It's midnight and the prison guards are drunk.")
		print("\t * They start a fight tournament between the inmates.")
		print("\t * The winner of the tournament gets a day out of prison.")
		print("\t * There are three other inmates in the tournament left.")
		print("\t * Your mission is to defeat the other three inmates.")
		print("\t * You will have three lives. Good luck!")
		print("")
		print("\t NOTE: To quit, enter :q at any time.")
		name = input("\t Let's play. What is your name? > ")
		difficulty_var = eval(input("\t This game is hard. How many lives do you want? "))
		if (name == ':q'):
			exit(1)
		os.system("clear")
		a_map = Map('round_1')
		a_game = Engine(a_map)
		a_game.lives = difficulty_var
		moves = a_game.play()
		game_over(a_game.won())
Ejemplo n.º 2
0
 def createEngineandJoin(self):
     self.labelplayer1.setText("PLAYER 1 SCORE : ")
     self.labelplayer2.setText("PLAYER 2 SCORE : ")
     self.isSettlingStart = False
     self.replayN = 0
     self.shouldcreateRoom = False
     self.is2PlayerMode = False
     self.wasFirstSettling = False
     self.replayTimer.stop()
     self.player1score = 0
     self.player2score = 0
     self.btnstart.setText("NEW GAME")
     self.isGame = True
     self.engine = Engine()
     while (not self.wasFirstSettling):
         isSettling, isPlayer1, score = self.engine.game()
         if not isSettling:
             self.wasFirstSettling = True
     self.joinRoom()
     self.isEnemyTurn = False
     self.paint()
     self.canIMove = False
     self.createRoom()
     self.isGameOnline = True
     self.timer.start()
Ejemplo n.º 3
0
def play_game():
    while True:
        global name 
        global moves 
        print ("Welcome to Sophia's game! To quit enter :q at any time. The goal is to escape with the lowest score possible. Each choice you make adds one to your score. Be careful though. The shortest path may not be the safest path. Good luck!") 
        # Explains to the user what you are running and how to exit the program if they need.
        name = input("\nTo start please enter your name(no spaces please!).\nNAME: ") 
        # assigns the name variable to the user's input of their name
        if (name == ':q'):
            exit(1)
        difficulty = input("Choose your difficulty by entering the amount of lives you would like to have. Every life adds 100 points to your score.\n1-2:Pretty Hard\n3-4:Average\n5-6:Easy Peasy\nLives: ")#creating difficulty levels
        #lets the player choose their difficulty level based on the amount of lives they choose. The amount of lives will affect their final score to make the leaderboard more fair.
        if (difficulty == ':q'):
            exit(1)
        difficulty = eval(difficulty)
        while int(difficulty) > 6 or int(difficulty) < 1:
            if int(difficulty) > 6:
                print("I don't want the game to be boring... Input fewer lives.")
            else:
                print("How can you play the game if you aren't alive??? Input more lives please.")
            difficulty = input("Choose your difficulty by entering the amount of lives you would like to have. Every life adds 100 points to your score.\n1-2:Pretty Hard\n3-4:Average\n5-6:Easy Peasy\nLives: ")
            if (difficulty == ':q'):
                exit(1)
            difficulty = eval(difficulty)
        a_map = Map('the_beginning') # Putting the user at the start scene
        a_game = Engine(a_map, difficulty)
        #Sends the amount of lives the player chose as well as the map to the game engine.
        moves = a_game.play()
        moves = moves + (difficulty*100)
        #changes the players score/moves to reflect the amount of lives they chose.
        game_over(a_game.won(), difficulty)
Ejemplo n.º 4
0
def play_game():
    while True:
        global name
        global moves
        print("Welcome to my game! To quit enter :q at any time. Good luck!")
        name = input("\nLet's play. Enter your name. > ")
        if (name == ':q'):
            exit(1)
            #Difficulty---------------------------------------------
        multiplier = eval(
            input(
                "Choose level of difficulty: \n[1] Easy (*1 score multiplier)\n[2] Medium(*.75 score multiplier)\n[3] Hard(*.5 score multiplier)\n >"
            ))
        try:
            multiplier = int(multiplier)
        except:
            raise ValueError("Error: Please enter an integer 1-3")
        if not (multiplier < 4 or multiplier > 0):
            raise ValueError("Error: Incorrect level of difficulty")
        if multiplier == 1:
            lives = 3
            r_multiplier = 1
        if multiplier == 2:
            r_multiplier = .75
            lives = 2
        if multiplier == 3:
            r_multiplier = .5
            lives = 1
            #End of Difficulty Programming----------------------------------
        a_map = Map('den')
        a_game = Engine(a_map, lives)
        moves = a_game.play()
        moves *= r_multiplier
        game_over(a_game.won())
        break
Ejemplo n.º 5
0
def play_game():
	while True:
		global name 
		global moves
		print ("Beware \n"
		"\n"
		" ██▓ ███▄    █   ██████  ▄▄▄       ███▄    █  ██▓▄▄▄█████▓▓██   ██▓\n"
		"▓██▒ ██ ▀█   █ ▒██    ▒ ▒████▄     ██ ▀█   █ ▓██▒▓  ██▒ ▓▒ ▒██  ██▒\n"
		"▒██▒▓██  ▀█ ██▒░ ▓██▄   ▒██  ▀█▄  ▓██  ▀█ ██▒▒██▒▒ ▓██░ ▒░  ▒██ ██░\n"
		"░██░▓██▒  ▐▌██▒  ▒   ██▒░██▄▄▄▄██ ▓██▒  ▐▌██▒░██░░ ▓██▓ ░   ░ ▐██▓░\n"
		"░██░▒██░   ▓██░▒██████▒▒ ▓█   ▓██▒▒██░   ▓██░░██░  ▒██▒ ░   ░ ██▒▓░\n"
		"░▓  ░ ▒░   ▒ ▒ ▒ ▒▓▒ ▒ ░ ▒▒   ▓▒█░░ ▒░   ▒ ▒ ░▓    ▒ ░░      ██▒▒▒ \n"
		" ▒ ░░ ░░   ░ ▒░░ ░▒  ░ ░  ▒   ▒▒ ░░ ░░   ░ ▒░ ▒ ░    ░     ▓██ ░▒░ \n"
		" ▒ ░   ░   ░ ░ ░  ░  ░    ░   ▒      ░   ░ ░  ▒ ░  ░       ▒ ▒ ░░  \n" 
		" ░           ░       ░        ░  ░         ░  ░            ░ ░     \n"    
		"											   ░ ░                  \n" 
		"														    The Game\n")
		time.sleep (4)
		print ("Welcome to The Game! To quit enter :q at any time. Be careful to not lose your mind...")
		time.sleep (3)
		name = input("\n Who is so unlucky to end up traped in Radcliffe Asylym. Enter your name. > ")
		if (name == ':q'):
			exit(1)
		difficultyl = str(input ("How much do you wish to suffer? (Difficulty Level) (easy, hard): "))
		if difficultyl == "easy" or difficultyl == "hard":
			break
		else: 
			print ("Incorrect Input, Please Choose a Provided Level.")
	a_map = Map('lobby') 
	a_game = Engine(a_map, difficultyl)
	moves = a_game.play()
	game_over(a_game.won())
Ejemplo n.º 6
0
def play_game():
    while True:
        global name
        global moves
        print(
            "Welcome to The Program.  This Program is running from an AI chip that was inserted\ninto your arm by the Hostile Political Party as a means of maintaining control."
        )
        print(" ")
        print(
            "Because you committed a small infraction, this Program was initiated\nas a way to eliminate you.  In the Program, you'll be transported through a series of scenarios."
        )
        print(" ")
        print(
            "In each of the scenarios, you will be faced with a series of tasks which you will have to complete.\nYour goal is to complete all the tasks so that you can terminate the Program and reclaim your livelihood!\nTo quit enter :q at any time. You will have 5 lives.\nHope you will make it!"
        )
        print(
            "*****************************************************************"
        )
        name = input("\nLet's play. Enter your name. > ")
        if (name == ':q'):
            exit(1)
        a_map = Map('treehouse_jungle')
        a_game = Engine(a_map)
        moves = a_game.play()
        game_over(a_game.won())
Ejemplo n.º 7
0
 def playReplay(self):
     if os.path.exists("history.xml"):
         self.shouldCloseSocket = True
         self.isEnemyTurn = False
         self.isGameOnline = False
         self.timer.stop()
         self.engine = Engine()
         self.replayActualN = 0
         self.isGame = True
         self.replayN = len(ET.parse('history.xml').getroot().getchildren())
         self.replayTimer.start()
Ejemplo n.º 8
0
def play_game():
	while True:
		global name 
		global moves 
		print ("Welcome to my game! To quit enter :q at any time. You will have three lives. Good luck!") # raise ValueError ('todo')
		name = input("\nLet's play. Enter your name. > ") # raise ValueError ('todo')
		if (name == ':q'):
			exit(1)
		a_map = Map('central_corridor') # raise ValueError ('todo')
		a_game = Engine(a_map)
		moves = raise ValueError ('todo')
		game_over(a_game.won())
Ejemplo n.º 9
0
def play_game():
	while True:
		global name 
		global moves 
		print ("Welcome to my game! To quit enter :q at any time.") # raise ValueError ('todo')
		name = input("\nOkay Let's play. Enter your name. > ") # raise ValueError ('todo')
		if (name == ':q'):
			exit(1)
		a_map = Map('round_one') # raise ValueError ('todo')
		a_game = Engine(a_map)
		moves = a_game.play()
		game_over(a_game.won())
Ejemplo n.º 10
0
def play_game():
    while True:
        global name
        global moves
        print(
            " Let's say you're going out with a Russian girl.\n Over the span of some years, you two have gotten pretty serious.\n Your Russian princess decides it's time for you to meet her family.\n So, you two go over to her mom's house for dinner.To quit enter 'quit' at any time.\n The score operates as it does in golf. You want the least amount of points.\n Each time you advance and each time you die will result in an extra point.\n The lower the score the closer you are to acceptance/tolerance from the Russian girl's mother.\n Good luck!"
        )
        name = input("\nLet's play. Enter your name. > ")
        if (name == 'quit'):
            exit(1)
        a_map = Map("doorway")  ##raise ValueError ('todo')
        a_game = Engine(a_map)  #a_game = Engine(Map(doorway))
        moves = a_game.play()
        game_over(a_game.won())
Ejemplo n.º 11
0
def play_game():
    while True:
        global name
        global moves
        print(
            "Welcome to The Mystery of Campus North! To quit enter :q at any time. You will have three lives. Good luck!"
        )  # raise ValueError ('todo')
        name = input("\nLet's play. Please enter your name. > "
                     )  # raise ValueError ('todo')
        if (name == ':q'):
            exit(1)
        a_map = Map('dorm')  # raise ValueError ('todo')
        a_game = Engine(a_map)
        moves = a_game.play()
        game_over(a_game.won())
Ejemplo n.º 12
0
def play_game():
    while True:
        global name
        global moves
        print(
            "Welcome to CTA Adventure! To quit enter ':q' at any time. You will have three lives. Good luck!"
        )
        name = input("\nEnter your name. > ")
        if (name == ':q'):
            exit(1)
        a_map = Map(
            'difficulty'
        )  #create a map object, starting at scene to select difficulty
        a_game = Engine(a_map)  #pass the map into the engine
        moves = a_game.play(
        )  #begin play and return the number of moves into moves variable
        game_over(a_game.won())  #pass
Ejemplo n.º 13
0
def play_game():
    while True:
        global name
        global moves
        global difficulty
        print(
            "Welcome to my game! To quit enter :q at any time. You will have three lives. Good luck!"
        )  # raise ValueError ('todo')
        name = input(
            "\nLet's play. Enter your name. > ")  # raise ValueError ('todo')
        if (name == ':q'):
            exit(1)
        difficulty = eval(input("Enter the amount of lives you want"))
        a_map = Map('Room')  # raise ValueError ('todo') [this is a map object]
        a_game = Engine(a_map, difficulty)
        moves = a_game.play()
        game_over(a_game.won())
Ejemplo n.º 14
0
 def player2StartGame(self):
     self.labelplayer1.setText("PLAYER 1 SCORE : ")
     self.labelplayer2.setText("PLAYER 2 SCORE : ")
     self.shouldCloseSocket = True
     self.replayTimer.stop()
     self.isSettlingStart = False
     self.replayN = 0
     self.shouldcreateRoom = False
     self.isGameOnline = False
     self.canIMove = True
     self.is2PlayerMode = True
     self.wasFirstSettling = False
     self.player1score = 0
     self.player2score = 0
     self.repaint()
     self.btnstart.setText("NEW GAME")
     self.isGame = True
     self.engine = Engine()
     self.timer.start()
Ejemplo n.º 15
0
def play_game():
    while True:
        global name
        global moves
        print(
            "This game is a challenge! To quit enter :q at any time. Good luck!"
        )
        name = input("\n Player name. > ")
        if (name == ':q'):
            exit(1)
        else:
            print(
                "Choose your difficulty level: 1-3. 1 is easiest, 3 is hardest.:"
            )
            diff = input("\n Difficulty. > ")
            a_map = Map(
                'central_corridor')  # This calls the starting location.
            a_game = Engine(a_map, diff)
            moves = a_game.play()
            game_over(a_game.won())
Ejemplo n.º 16
0
def play_game():
    while True:
        global name
        global moves
        print(
            "Welcome to my game! To quit enter :q at any time. You will have three lives. Good luck!"
        )  # raise ValueError ('todo')
        lives = input(
            "\nPlease select a difficulty\n\n1) Hard\n2) Medium\n3) Easy\n > ")
        if int(lives) > 3:
            print(
                "\nOkay, it's clear you meant to select easy. Please read the directions."
            )
            lives = 3
        name = input(
            "\nLet's play. Enter your name. > ")  # raise ValueError ('todo')
        if (name == ':q'):
            exit(1)
        a_map = Map('wake_up')  # raise ValueError ('todo')
        a_game = Engine(a_map, lives)
        moves = a_game.play()
        game_over(a_game.won())
Ejemplo n.º 17
0
def play_game():
    while True:
        global name
        global moves
        print(
            "Welcome to my How to survive college game! To quit enter :q at any time. You will have three lives. Good luck!"
        )
        name = input("\nLet's play. Enter your name. > ")
        if (name == ':q'):
            exit(1)
        dificulty_level = ""
        while True:
            dificulty_level = str(
                input("Which dificulty do you want: Easy, Medium or hard?"))
            if dificulty_level == "easy" or dificulty_level == "medium" or dificulty_level == "hard":
                break
            else:
                print("Not one of the levels")
        a_map = Map('oweek-scene')
        a_game = Engine(a_map, dificulty_level)
        moves = a_game.play()
        game_over(a_game.won())
Ejemplo n.º 18
0
def play_game():  #this is where you go to make the leaderboard permanent
    while True:
        global name
        global moves
        print(
            "\nWelcome to FOOT CHASE! To quit enter :q at any time. Good luck!"
        )  # raise ValueError ('todo')
        difficulty = input(
            "\nEnter the number of lives that you want to have, be a man or a chicken.\n(1-2 Hard / 3-5 Medium / 5+ Too easy): "
        )
        if (difficulty == ':q'):
            exit(1)
        try:
            difficulty = int(difficulty)
        except ValueError:
            exit(1)
        name = input("\nLet's play. Enter your name. > ")
        if (name == ':q'):
            exit(1)
        a_map = Map('the_forest')
        a_game = Engine(a_map, difficulty)
        moves = a_game.play()
        game_over(a_game.won())
Ejemplo n.º 19
0
def play_game():
    while True:
        global name
        global moves
        global difficulty
        print(
            "Welcome to Lost at Sea! To quit, enter :q at any time. Good luck!"
        )  # raise ValueError ('todo')
        print(
            "What difficulty do you want to set the game to have? " +
            " \nSelect a difficulty level\n Enter 1 for 'easy', enter 2 for 'medium', and enter 3 for 'hard': > "
        )
        difficulty = int(input("Difficulty level: "))
        lives = 4 - difficulty
        print("You will have", lives, "lives")
        name = input("\nLet's begin! To begin, please input your name: > "
                     )  # raise ValueError ('todo')
        if (name == ':q'):
            exit(1)
        a_map = Map('starting_out')
        a_game = Engine(a_map)
        moves = a_game.play()
        game_over(a_game.won())
Ejemplo n.º 20
0
def play_game():
    while True:
        global name
        global moves
        print(
            "Welcome to \n                      .----------------.  .----------------.  .----------------.  .----------------.  .-----------------. .----------------.                     \n                     | .--------------. || .--------------. || .--------------. || .--------------. || .--------------. || .--------------. |                    \n                     | | ____    ____ | || | _____  _____ | || |  _________   | || |      __      | || | ____  _____  | || |  _________   | |                    \n                     | ||_   \  /   _|| || ||_   _||_   _|| || | |  _   _  |  | || |     /  \     | || ||_   \|_   _| | || | |  _   _  |  | |                    \n                     | |  |   \/   |  | || |  | |    | |  | || | |_/ | | \_|  | || |    / /\ \    | || |  |   \ | |   | || | |_/ | | \_|  | |                    \n                     | |  | |\  /| |  | || |  | '    ' |  | || |     | |      | || |   / ____ \   | || |  | |\ \| |   | || |     | |      | |                    \n                     | | _| |_\/_| |_ | || |   \ `--' /   | || |    _| |_     | || | _/ /    \ \_ | || | _| |_\   |_  | || |    _| |_     | |                    \n                     | ||_____||_____|| || |    `.__.'    | || |   |_____|    | || ||____|  |____|| || ||_____|\____| | || |   |_____|    | |                    \n                     | |              | || |              | || |              | || |              | || |              | || |              | |                    \n                     | '--------------' || '--------------' || '--------------' || '--------------' || '--------------' || '--------------' |                    \n                      '----------------'  '----------------'  '----------------'  '----------------'  '----------------'  '----------------'                     \n  .----------------.  .----------------.  .----------------.  .----------------.  .----------------.  .----------------.  .----------------.  .----------------.\n | .--------------. || .--------------. || .--------------. || .--------------. || .--------------. || .--------------. || .--------------. || .--------------. |\n | |  _________   | || |     ____     | || |  ________    | || |  ________    | || |   _____      | || |  _________   | || |  _______     | || |    _______   | |\n | | |  _   _  |  | || |   .'    `.   | || | |_   ___ `.  | || | |_   ___ `.  | || |  |_   _|     | || | |_   ___  |  | || | |_   __ \    | || |   /  ___  |  | |\n | | |_/ | | \_|  | || |  /  .--.  \  | || |   | |   `. \ | || |   | |   `. \ | || |    | |       | || |   | |_  \_|  | || |   | |__) |   | || |  |  (__ \_|  | |\n | |     | |      | || |  | |    | |  | || |   | |    | | | || |   | |    | | | || |    | |   _   | || |   |  _|  _   | || |   |  __ /    | || |   '.___`-.   | |\n | |    _| |_     | || |  \  `--'  /  | || |  _| |___.' / | || |  _| |___.' / | || |   _| |__/ |  | || |  _| |___/ |  | || |  _| |  \ \_  | || |  |`\____) |  | |\n | |   |_____|    | || |   `.____.'   | || | |________.'  | || | |________.'  | || |  |________|  | || | |_________|  | || | |____| |___| | || |  |_______.'  | |\n | |              | || |              | || |              | || |              | || |              | || |              | || |              | || |              | |\n | '--------------' || '--------------' || '--------------' || '--------------' || '--------------' || '--------------' || '--------------' || '--------------' |\n  '----------------'  '----------------'  '----------------'  '----------------'  '----------------'  '----------------'  '----------------'  '----------------' \n To quit enter :q at any time. Good luck!"
        )  # raise ValueError ('')
        name = input(
            "\nLet's play. Enter your name. > ")  # raise ValueError ('todo')
        if (name == ':q'):
            exit(1)
        difficulty_level = ""
        while True:
            difficulty_level = str(
                input("Choose a difficulty level: easy, medium, or hard: "))
            if difficulty_level == "easy" or difficulty_level == "medium" or difficulty_level == "hard":
                break
            else:
                print("Error. Please choose 'easy', 'medium', or 'hard'.")
        a_map = Map('center_alley')
        a_game = Engine(a_map, difficulty_level)
        moves = a_game.play()
        game_over(a_game.won())
Ejemplo n.º 21
0
class PongGame(Widget):
    ball = ObjectProperty(None)
    player1 = ObjectProperty(None)
    player2 = ObjectProperty(None)
    game_engine = Engine()

    def open_main(self):
        self.game_engine.stop()
        self.player1.score = 0
        self.player2.score = 0
        self.serve_ball()
        sm.current = 'MainScreen'

    def start_game(self):
        self.game_engine.start(self.update)

    def stop_game(self):
        self.game_engine.stop()

    def restart_game(self):
        self.player1.score = 0
        self.player2.score = 0
        self.serve_ball()
        self.start_game()

    def serve_ball(self, vel=(4, 0)):
        self.ball.center = self.center
        self.ball.velocity = vel

    def update(self, dt):
        self.ball.move()

        self.player1.bounce_ball(self.ball)
        self.player2.bounce_ball(self.ball)

        if (self.ball.y < self.y) or (self.ball.top > self.top):
            self.ball.velocity_y *= -1

        if self.ball.x < self.x:
            self.player2.score += 1
            self.serve_ball(vel=(4, 0))

        if self.ball.x > self.width:
            self.player1.score += 1
            self.serve_ball(vel=(-4, 0))

        if self.player1.score == 1:
            self.stop_game()
            content = WinAlarm()
            content.bind(on_answer=self.alarm_answer)
            self.popup = Popup(title="Player 1 Win the game", content=content, size_hint=(None, None), size=(300, 200),
                               auto_dismiss=False)
            self.popup.open()
        elif self.player2.score == 1:
            self.stop_game()
            content = WinAlarm()
            content.bind(on_answer=self.alarm_answer)
            self.popup = Popup(title="Player 2 Win the game", content=content, size_hint=(None, None), size=(300, 200),
                               auto_dismiss=False)
            self.popup.open()

    def on_touch_move(self, touch):
        if touch.x < self.width /3:
            self.player1.center_y = touch.y
        if touch.x > self.width - self.width / 3:
            self.player2.center_y = touch.y

    def alarm_answer(self, instance, play_again):
        if play_again == "yes":
            self.popup.dismiss()
            self.restart_game()
        elif play_again == "no":
            self.popup.dismiss()
            sm.current = 'MainScreen'
Ejemplo n.º 22
0
class Window(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Candy Crush")
        self.setGeometry(300, 300, 900, 600)
        self.canIMove = True
        self.setMinimumHeight(600)
        self.setMinimumWidth(600)
        self.scene = QGraphicsScene()
        self.view = QGraphicsView(self.scene, self)
        self.view.setGeometry(130, 10, 700, 400)
        self.isGame = False
        self.isGameOnline = False
        self.isSettlingStart = False
        self.shouldcreateRoom = False
        self.is2PlayerMode = False
        self.wasFirstSettling = False
        self.replayN = 0
        self.replayActualN = 0
        self.shouldCloseSocket = False
        self.player1score = 0
        self.player2score = 0
        self.IteratorTimer = 0
        self.timer = QTimer(self)
        self.timer.timeout.connect(self.gameLoop)
        self.timer.setInterval(50)
        self.replayTimer = QTimer(self)
        self.replayTimer.timeout.connect(self.replayLoop)
        self.replayTimer.setInterval(200)
        self.setTextBox()
        self.setLabel()
        self.setButtons()
        self.isEnemyTurn = False

        self.enemyIP = 0

    def setLabel(self):
        self.label = QLabel(self)
        self.label.move(20, 450)
        self.label.setText("STEERING WITH ARROW KEYS \n SELECT WITH ENTER KEY")
        self.labelplayer1 = QLabel(self)
        self.labelplayer1.move(300, 450)
        self.labelplayer1.setText("PLAYER 1 SCORE :              ")
        self.labelplayer2 = QLabel(self)
        self.labelplayer2.move(500, 450)
        self.labelplayer2.setText("PLAYER 2 SCORE :              ")

    def setTextBox(self):
        self.textbox = QLineEdit(self)
        self.textbox.move(20, 200)
        self.textbox.resize(100, 40)
        self.textbox.setPlaceholderText(" IP ADDRESS")

    def createXML(self):
        # create the file structure
        if self.replayN == 0:
            data = ET.Element('data')
            item0 = ET.SubElement(data, 'data')
            item1 = ET.SubElement(data, 'item')
            item1.set('object', str(self.replayN))
            item1.text = codecs.encode(
                pickle.dumps(self.engine.board.hexagonslist),
                "base64").decode()

            item2 = ET.SubElement(data, 'item1')
            item2.set('score1', str(self.replayN))
            item2.text = codecs.encode(pickle.dumps(self.player1score),
                                       "base64").decode()

            item3 = ET.SubElement(data, 'item2')
            item3.set('score2', str(self.replayN))
            item3.text = codecs.encode(pickle.dumps(self.player2score),
                                       "base64").decode()

            # create a new XML file with the results
            mydata = ET.tostring(item0)
            myfile = open("history.xml", "wb")
            myfile.write(mydata)
            self.replayN += 1
        else:
            tree = ET.parse('history.xml')
            root = tree.getroot()

            data = ET.Element('data')

            item1 = ET.SubElement(data, 'item')
            item1.set('object', str(self.replayN))
            item1.text = codecs.encode(
                pickle.dumps(self.engine.board.hexagonslist),
                "base64").decode()

            item2 = ET.SubElement(data, 'item1')
            item2.set('score1', str(self.replayN))
            item2.text = codecs.encode(pickle.dumps(self.player1score),
                                       "base64").decode()

            item3 = ET.SubElement(data, 'item2')
            item3.set('score2', str(self.replayN))
            item3.text = codecs.encode(pickle.dumps(self.player2score),
                                       "base64").decode()

            root.append(data)

            tree.write('history.xml')
            self.replayN += 1

    def setButtons(self):
        #button for 2 player mode
        self.btn2player = QPushButton("2 PLAYER MODE", self)
        self.btn2player.setAutoDefault(False)
        self.btn2player.setStyleSheet("background-color: #66ffff")
        self.btn2player.move(20, 100)
        self.btn2player.clicked.connect(self.player2StartGame)

        #button for one player mode
        self.btnstart = QPushButton("START", self)
        self.btnstart.move(20, 50)
        self.btnstart.setAutoDefault(False)
        self.btnstart.setStyleSheet("background-color: #66ffff")
        self.btnstart.clicked.connect(self.StartGame)

        #button to exit program
        self.btnstop = QPushButton("EXIT", self)
        self.btnstop.setAutoDefault(False)
        self.btnstop.setStyleSheet("background-color: #66ffff")
        self.btnstop.move(20, 150)
        self.btnstop.clicked.connect(self.quitApp)

        # button to get last ip addres
        self.btnjoin = QPushButton("GET LAST IP ADDRESS", self)
        self.btnjoin.setAutoDefault(False)
        self.btnjoin.setStyleSheet("background-color: #66ffff")
        self.btnjoin.move(20, 250)
        self.btnjoin.clicked.connect(self.getIPaddr)

        #button to join online player
        self.btnjoin = QPushButton("JOIN PLAYER", self)
        self.btnjoin.setAutoDefault(False)
        self.btnjoin.setStyleSheet("background-color: #66ffff")
        self.btnjoin.move(20, 300)
        self.btnjoin.clicked.connect(self.createEngineandJoin)

        # button to create room for online player
        self.btnjoin = QPushButton("CREATE ROOM", self)
        self.btnjoin.setAutoDefault(False)
        self.btnjoin.setStyleSheet("background-color: #66ffff")
        self.btnjoin.move(20, 350)
        self.btnjoin.clicked.connect(self.createEngineAndMap)

        # button to play replay
        self.btnjoin = QPushButton("PLAY REPLAY", self)
        self.btnjoin.setAutoDefault(False)
        self.btnjoin.setStyleSheet("background-color: #66ffff")
        self.btnjoin.move(20, 400)
        self.btnjoin.clicked.connect(self.playReplay)

    def getIPaddr(self):
        if os.path.exists("data.json"):
            with open("data.json", "r") as read_file:
                json_object = json.load(read_file)
                self.textbox.setText(json_object["ip"])
                return

    def playReplay(self):
        if os.path.exists("history.xml"):
            self.shouldCloseSocket = True
            self.isEnemyTurn = False
            self.isGameOnline = False
            self.timer.stop()
            self.engine = Engine()
            self.replayActualN = 0
            self.isGame = True
            self.replayN = len(ET.parse('history.xml').getroot().getchildren())
            self.replayTimer.start()

    def replayLoop(self):
        if self.replayActualN >= self.replayN - 1:
            print("koniec")
            self.replayTimer.stop()
            return
        else:
            #self.engine.board.hexagonlist = XXX
            tree = ET.parse('history.xml')
            root = tree.getroot()
            n = root[self.replayActualN][0].text
            score1 = root[self.replayActualN][1].text
            score2 = root[self.replayActualN][2].text
            n = pickle.loads(codecs.decode(n.encode(), "base64"))
            score1 = pickle.loads(codecs.decode(score1.encode(), "base64"))
            score2 = pickle.loads(codecs.decode(score2.encode(), "base64"))
            print("pokazuje klatke nr" + str(self.replayActualN))
            self.engine.board.hexagonslist = n
            self.replayActualN += 1
            self.labelplayer1.setText(f"PLAYER 1 SCORE : {score1}   ")
            self.labelplayer2.setText(f"PlAYER 2 SCORE : {score2}    ")
            self.paint()

    def createRoom(self):
        self.isEnemyTurn = True
        self.t = threading.Thread(target=self.recieveBoard,
                                  args=(
                                      self.isEnemyTurn,
                                      self.engine.board.hexagonslist,
                                  ))
        self.t.start()
        #t.join()

    def joinRoom(self):
        self.sendBoard()

    def sendBoard(self):
        # Create a TCP/IP socket
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        server_address = (self.textbox.text(), 10061)
        x = {
            "ip": server_address[0],
            "port": server_address[1],
        }
        with open('data.json', 'w') as outfile:
            outfile.write(json.dumps(x))

        sock.connect(server_address)

        try:
            n = self.engine.board.hexagonslist
            message = pickle.dumps([n, self.player1score])
            # print('sending {!r}'.format(message))
            sock.send(message)
            self.canIMove = False

        finally:
            print('closing socket')
            sock.close()

    def recieveBoard(self, isEnemy, board):
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

        server_address = ("0.0.0.0", 10061)

        sock.settimeout(0.5)
        sock.bind(server_address)
        print("waiting for connection")
        while True:

            sock.listen(1)
            if self.shouldCloseSocket:
                self.shouldCloseSocket = False
                self.isEnemyTurn = False
                self.canIMove = True
                break
            try:
                connection, client_address = sock.accept()
            except:
                pass
            else:
                break

        try:
            print("connection from", client_address)

            while True:

                data = connection.recv(100000)

                if data:
                    self.engine.board.hexagonslist, self.player2score = pickle.loads(
                        data)
                    print("odebrano mape")
                else:
                    print("skonczono odbierac mape", client_address)
                    self.isEnemyTurn = False
                    break

        finally:

            print("Closing current connectoin")
            connection.close()
            self.isEnemyTurn = False
            self.canIMove = True

    def quitApp(self):
        self.shouldCloseSocket = True
        myApp.quit()

    def StartGame(self):
        self.canIMove = True
        self.shouldCloseSocket = True
        self.replayTimer.stop()

        self.replayN = 0
        self.labelplayer1.setText("PLAYER 1 SCORE : ")
        self.labelplayer2.setText("PLAYER 2 SCORE : ")
        self.isSettlingStart = False
        self.is2PlayerMode = False
        self.wasFirstSettling = False
        self.shouldcreateRoom = False
        self.player1score = 0
        self.player2score = 0
        #self.repaint()
        #self.show()
        self.btnstart.setText("NEW GAME")
        self.isGame = True
        self.isGameOnline = False
        self.engine = Engine()
        self.timer.start()

    def player2StartGame(self):
        self.labelplayer1.setText("PLAYER 1 SCORE : ")
        self.labelplayer2.setText("PLAYER 2 SCORE : ")
        self.shouldCloseSocket = True
        self.replayTimer.stop()
        self.isSettlingStart = False
        self.replayN = 0
        self.shouldcreateRoom = False
        self.isGameOnline = False
        self.canIMove = True
        self.is2PlayerMode = True
        self.wasFirstSettling = False
        self.player1score = 0
        self.player2score = 0
        self.repaint()
        self.btnstart.setText("NEW GAME")
        self.isGame = True
        self.engine = Engine()
        self.timer.start()

    def createEngineAndMap(self):
        self.labelplayer1.setText("PLAYER 1 SCORE : ")
        self.labelplayer2.setText("PLAYER 2 SCORE : ")
        self.is2PlayerMode = False
        self.replayTimer.stop()
        self.replayN = 0
        self.shouldcreateRoom = False
        self.wasFirstSettling = False
        self.isSettlingStart = False
        self.player1score = 0
        self.player2score = 0
        self.btnstart.setText("NEW GAME")
        self.isGame = True
        self.engine = Engine()
        while not self.wasFirstSettling:
            isSettling, isPlayer1, score = self.engine.game()
            if not isSettling:
                self.wasFirstSettling = True
        self.isGameOnline = True
        self.createRoom()
        self.timer.start()

    def createEngineandJoin(self):
        self.labelplayer1.setText("PLAYER 1 SCORE : ")
        self.labelplayer2.setText("PLAYER 2 SCORE : ")
        self.isSettlingStart = False
        self.replayN = 0
        self.shouldcreateRoom = False
        self.is2PlayerMode = False
        self.wasFirstSettling = False
        self.replayTimer.stop()
        self.player1score = 0
        self.player2score = 0
        self.btnstart.setText("NEW GAME")
        self.isGame = True
        self.engine = Engine()
        while (not self.wasFirstSettling):
            isSettling, isPlayer1, score = self.engine.game()
            if not isSettling:
                self.wasFirstSettling = True
        self.joinRoom()
        self.isEnemyTurn = False
        self.paint()
        self.canIMove = False
        self.createRoom()
        self.isGameOnline = True
        self.timer.start()

    def paint(self):
        if not self.isEnemyTurn:
            self.scene.clear()
            if self.isGame:
                for indi, i in enumerate(self.engine.board.hexagonslist):
                    for ind, j in enumerate(i):
                        xpom = j.x * 8
                        ypom = j.y * 8
                        points = QPolygonF([
                            QPoint(xpom + 16, ypom),
                            QPoint(xpom + 32, ypom + 10),
                            QPoint(xpom + 32, ypom + 22),
                            QPoint(xpom + 16, ypom + 32),
                            QPoint(xpom, ypom + 22),
                            QPoint(xpom, ypom + 10)
                        ])
                        self.scene.addPolygon(
                            points, QPen(Qt.white, 3, Qt.SolidLine),
                            QBrush(self.getColour(j), Qt.SolidPattern))
            #Draw player handles on board
                x = self.engine.board.hexagonslist[self.engine.setPy][
                    self.engine.setPx].x
                y = self.engine.board.hexagonslist[self.engine.setPy][
                    self.engine.setPx].y
                xpom = x * 8
                ypom = y * 8
                points = QPolygonF([
                    QPoint(xpom + 16, ypom),
                    QPoint(xpom + 32, ypom + 10),
                    QPoint(xpom + 32, ypom + 22),
                    QPoint(xpom + 16, ypom + 32),
                    QPoint(xpom, ypom + 22),
                    QPoint(xpom, ypom + 10)
                ])
                self.scene.addPolygon(points, QPen(Qt.black, 4, Qt.SolidLine),
                                      QBrush())
                if self.engine.isSet:
                    x = self.engine.board.hexagonslist[self.engine.setsetPy][
                        self.engine.setsetPx].x
                    y = self.engine.board.hexagonslist[self.engine.setsetPy][
                        self.engine.setsetPx].y
                    xpom = x * 8
                    ypom = y * 8
                    points = QPolygonF([
                        QPoint(xpom + 16, ypom),
                        QPoint(xpom + 32, ypom + 10),
                        QPoint(xpom + 32, ypom + 22),
                        QPoint(xpom + 16, ypom + 32),
                        QPoint(xpom, ypom + 22),
                        QPoint(xpom, ypom + 10)
                    ])
                    self.scene.addPolygon(points,
                                          QPen(Qt.black, 4, Qt.SolidLine),
                                          QBrush())

    def getColour(self, j):
        if j.type == Hexagon.colours[0]:
            return Qt.green
        if j.type == Hexagon.colours[1]:
            return Qt.blue
        if j.type == Hexagon.colours[2]:
            return Qt.cyan
        if j.type == Hexagon.colours[3]:
            return Qt.red
        if j.type == Hexagon.colours[4]:
            return Qt.yellow
        if j.type == Hexagon.colours[5]:
            return Qt.magenta
        if j.type == Hexagon.colours[6]:
            return Qt.lightGray
        if j.type == Hexagon.colours[7]:
            return Qt.black

    def gameLoop(self):

        if self.IteratorTimer >= 4 and not self.isEnemyTurn:
            self.createXML()
            self.IteratorTimer = 0
        else:
            self.IteratorTimer += 1
        if self.isGameOnline and self.shouldcreateRoom:
            self.shouldcreateRoom = False
            self.createRoom()
        if not self.isEnemyTurn and self.canIMove:
            isSettling, isPlayer1, score = self.engine.game()

            if isSettling:
                self.timer.setInterval(600)
                if self.isGameOnline:
                    self.isSettlingStart = True
            else:
                if self.isSettlingStart and self.isGameOnline:
                    self.isSettlingStart = False
                    self.joinRoom()
                    self.shouldcreateRoom = True
                self.timer.setInterval(50)
                self.wasFirstSettling = True
            if self.wasFirstSettling:
                if self.is2PlayerMode:
                    if isPlayer1: self.player1score += score
                    else: self.player2score += score
                else: self.player1score += score
                self.labelplayer1.setText(
                    f"PLAYER 1 SCORE : {self.player1score}   ")
                self.labelplayer2.setText(
                    f"PlAYER 2 SCORE : {self.player2score}    ")
                if self.is2PlayerMode:
                    if isPlayer1:
                        self.labelplayer2.setStyleSheet('color: red')
                        self.labelplayer1.setStyleSheet('color: black')
                    else:
                        self.labelplayer1.setStyleSheet('color: red')
                        self.labelplayer2.setStyleSheet('color: black')
                self.labelplayer1.update()
                self.labelplayer2.update()
        self.paint()