Tic tac toe python class

Tic Tac Toe GUI In Python using PyGame

This article will guide you and give you a basic idea of designing a game Tic Tac Toe using pygame library of Python. Pygame is a cross-platform set of Python modules designed for writing video games. It includes computer graphics and sound libraries designed to be used with the Python programming language. Let’s break the task in five parts:

  1. Importing the required libraries and setting up the required global variables.
  2. Designing the game display function, that will set a platform for other components to be displayed on the screen.
  3. Main algorithm of win and draw
  4. Getting the user input and displaying the “X” or “O” at the proper position where the user has clicked his mouse.
  5. Running an infinite loop, and including the defined methods in it.

Note: The required PNG files can be downloaded below as follows:

Importing the required libraries and setting up the required global variables

We are going to use the pygame, time, and the sys library of Python. time library is used to keep track of time and sleep() method that we are going to use inside our code. Have a look at the code below.

Python3

Designing the game display

This is the trickier part, that makes the utmost importance in game development. We can use the display.set_mode() method to set up our display window. This takes three arguments, first one being a tuple having (width, height) of the display that we want it to be, the other two arguments are depth and fps respectively.display.set_caption(), sets a caption on the name tag of our display. pg.image.load() is an useful method to load the background images to customize the display. This method takes the file name as an argument along with the extension. There is a small problem with image.load(), it loads the image as a Python object in its native size, which may not be optimized along with the display. So we use another method in pygame known as pg.transform.scale(). This method takes two arguments, one being the name of the image object and the other is a tuple having (width, height), that we want our image to scale to. Finally we head to the first function, game_initiating_window(). On the very first line there is a screen.blit() function. The screen is the Python function and blit is the method that enables pygame to display something over another thing. Here out image object has been displayed over the screen, which was set white initially. pg.display.update() is another important function in game development. It updates the display of our window when called. Pygame also enables us to draw geometric objects like line, circle, etc. In this project we have used pg.draw.line() method that takes five arguments, namely – (display, line color, starting point, ending point, width). This involves a little bit of coordinate geometry to draw the lines properly. This is not sufficient. At each update of the display we need to know the game status, Whether it is win or lose.draw_status() helps us in displaying another 100pc window at the bottom of the main window, that updates the status at each click of the user.

Читайте также:  Php код для генерации числа

Источник

Python3 OOP Tic-Tac-Toe

I’m studying Object-oriented Programming and decided to apply some things doing an Object-oriented Tic-Tac-Toe.
I wanted to know if you have some hints of what to improve and why!

class Board: """Represents one board to a Tic-Tac-Toe game.""" def __init__(self): """Initializes a new board. A board is a dictionary which the key is the position in the board and the value can be 'X', 'O' or ' ' (representing an empty position in the board.)""" self.board = < "TL": " ", "TM": " ", "TR": " ", "ML": " ", "MM": " ", "MR": " ", "BL": " ", "BM": " ", "BR": " ">def print_board(self): """Prints the board.""" print(self.board["TL"] + "|" + self.board["TM"] \ + "|" + self.board["TR"] + "|") print("-+" * 3) print(self.board["ML"] + "|" + self.board["MM"] \ + "|" + self.board["MR"] + "|") print("-+" * 3) print(self.board["BL"] + "|" + self.board["BM"] \ + "|" + self.board["BR"] + "|") def _is_valid_move(self, position): if self.board[position] is " ": return True return False def change_board(self, position, type): """Receive a position and if the player is 'X' or 'O'. Checks if the position is valid, modifies the board and returns the modified board. Returns None if the move is not valid.""" if self._is_valid_move(position): self.board[position] = type return self.board return None def is_winner(self, player): """Returns True if the player won and False otherwise.""" if self.board["TL"] == player.type and self.board["TM"] == player.type and self.board["TR"] == player.type or \ self.board["ML"] == player.type and self.board["MM"] == player.type and self.board["MR"] == player.type or \ self.board["BL"] == player.type and self.board["BM"] == player.type and self.board["BR"] == player.type or \ self.board["TL"] == player.type and self.board["ML"] == player.type and self.board["BL"] == player.type or \ self.board["TM"] == player.type and self.board["MM"] == player.type and self.board["BM"] == player.type or \ self.board["TR"] == player.type and self.board["MR"] == player.type and self.board["BR"] == player.type or \ self.board["TL"] == player.type and self.board["MM"] == player.type and self.board["BR"] == player.type or \ self.board["BL"] == player.type and self.board["MM"] == player.type and self.board["TR"] == player.type: return True return False class Player: """Represents one player.""" def __init__(self, type): """Initializes a player with type 'X' or 'O'.""" self.type = type def __str__(self): return "Player <>".format(self.type) class Game: """Represents a Tic-Tac-Toe game. The game defines player 1 always playing with 'X'.""" def __init__(self): """Initilize 2 Players and one Board.""" self.player1 = Player("X") self.player2 = Player("O") self.board = Board() def print_valid_entries(self): """Prints the valid inputs to play the game.""" print(""" TL - top left | TM - top middle | TR - top right ML - middle left | MM - center | MR - middle right BL - bottom left | BM - bottom middle | BR - bottom right""") def printing_board(self): """Prints the board.""" self.board.print_board() def change_turn(self, player): """Changes the player turn. Receives a player and returns the other.""" if player is self.player1: return self.player2 else: return self.player1 def won_game(self, player): """Returns True if the player won the game, False otherwise.""" return self.board.is_winner(player) def modify_board(self, position, type): """Receives position and player type ('X' or 'O'). Returns modified board if position was valid. Asks to player try a different position otherwise.""" if self.board.change_board(position, type) is not None: return self.board.change_board(position, type) else: position = input("Not available position. Please, try again: ") return self.board.change_board(position, type) def play(): game = Game() game.print_valid_entries() player = game.player1 num = 9 while num > 0: num -= 1 game.printing_board() position = input("<> turn, what's your move? ".format(player)) game.modify_board(position, player.type) if game.won_game(player): print("<> is the Winner!".format(player)) break else: player = game.change_turn(player) if num == 0: print("Game over! It's a tie!") if __name__ == "__main__": play() 

Источник

Оцените статью