You are on page 1of 17

MANAV SCHOOL OF POLYTECHNIC VYALA,

AKOLA

DEPARTMENT OF COMPUTER ENGINEERING

Academic Year 2023-24

Semester VI

Programming with Python [22616]


Submitted To M.S.B.T.E. In Partial Fulfilment of the Requirement forthe
Diploma in Computer Engineering.

Project on: - “ Tic-Tac-Toe Game”

Submitted By

Mr. Mohammad umair abdul aziz


Mr. Shivam Pandhari Jawarkar
Mr. Mohammed jawwad baig

Project Guide- Pooja.p.wa kod e

1
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
CERTIFICATE

This is to certify that Mr./Ms. …………………………………………................


Roll No………, of six Semester of Diploma in …………......………………….

………………………………….of Institute, ……………………………………………..…….

………………………… (Code:1668) has completed the Micro-Project satisfactorily


in Programming with Python (22616) for the academic year2023 to 2024 as
prescribed in the curriculum.

Place:……………………………… Enrolment No:…………………………….

Date:………………………………. Exam Seat No:……………………………..

Subject Teacher Head of the Department Principal

2
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION

CERTIFICATE

This is to certify that Mr./Ms. …………………………………………................


Roll No………, of six Semester of Diploma in …………......………………….

………………………………….of Institute, ……………………………………………..…….

………………………… (Code:1668) has completed the Micro-Project satisfactorily


in Programming with Python (22616) for the academic year2023 to 2024 as
prescribed in the curriculum.

Place:……………………………… Enrolment No:…………………………….

Date:………………………………. Exam Seat No:……………………………..

Subject Teacher Head of the Department Principal

3
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
CERTIFICATE

This is to certify that Mr./Ms. …………………………………………................


Roll No………, of six Semester of Diploma in …………......………………….

………………………………….of Institute, ……………………………………………..…….

………………………… (Code:1668) has completed the Micro-Project satisfactorily


in Programming with Python (22616) for the academic year2023 to 2024 as
prescribed in the curriculum.

Place:……………………………… Enrolment No:…………………………….

Date:………………………………. Exam Seat No:……………………………..

Subject Teacher Head of the Department Principal

4
INDEX
Sr. Topic page
NO No
1 6
Introduction To
Tic-Tac-Toe
Game

2 7
Abstract

3 Rationale 8

4 8
Aim of the project

5 Course Outcomes Achieved 8

6 Program code 9

7 Output 14

8 Skill Developed 16

9 Applications of the Project 16

10 Conclusion 17

11 References 17

5
Introduction To Tic-Tac-Toe Game

Tic tac toe Python, also known as Noughts and Crosses or Xs and Os, is
a very simple two-player game where both the player get to choose any of the
symbols between X and O. This game is played on a 3X3 grid board and one by
one each player gets a chance to mark its respective symbol on the empty
spaces of the grid.

Once a player is successful in marking a strike of the same symbol either


in the horizontal, vertical or diagonal way as shown in the picture below is
created that player wins the game else the game goes on a draw if all the spots
are filled.

In the tic tac toe Python game that we shall be building, we require two
players. These two players will be selecting their respective two signs which
are generally used in the game that is, X and O. The two players draw
the X and O on an alternative basis on the 3x3 grid having 9 empty boxes.

6
Abstract

This paper describes the main features and application of python


programming. This book contains a complete learning of python programming.
This book covers game programming in three different scripting language i.e
python. Lua and ruby.

7
Rationale
The objective of this project is to develop the well-known
board game Tic-Tac- Toe for two players.
Generally, this is a two-player strategy board game. The Tic-
Tac-Toe game is based on having a game board (2D array) of size 3 x
3. The players alternate placing Xs and Os on the board until either
one has placed three Xs or Os in a row horizontally, vertically, or
diagonally; or all nine board squares are filled. The player wins if
s/he draws three Xs or three Os in a row. Otherwise, the game is
draw.
Initially the board grid squares are initialized to zeros. Xs and
Os might be denoted by numbers inside the board grid by ones and
twos respectively. I.e. if player one chooses X, the location of that
choice is registered as 1 and when player two chooses O the location
of that choice in your array is registered as 2. At the end if a row of 1s
is registered then player one won the game. Or if a row of 2s is
registered thus player two won the game. If not, the game is draw.
The game ends when there is no more empty fields in the array
(board) to fill or if one of the players wins the game.

1.0 Aim of the project


1. To develop an interesting game for children to pass their free time.
2. To develop the well-known board game Tic-Tac-Toe for two players.
3. To be one of the players to get three same symbols in a row –
horizontally, vertically or diagonally on a 3 x 3 grid.

2.0 Course Outcomes Achieved


1. Display message on screen using Python script on IDE.
2. Develop python program to demonstrate use of Operators.
3. Perform operations on data structures in Python.
4. Develop functions for given problems.

8
Program

"""A tic-tac-toe game built with Python and Tkinter."""

import tkinter as tk
from itertools import cycle
from tkinter import font
from typing import NamedTuple

class Player(NamedTuple):
label: str
color: str

class Move(NamedTuple):
row: int
col: int
label: str = ""

BOARD_SIZE = 3
DEFAULT_PLAYERS = (
Player(label="X", color="blue"),
Player(label="O", color="green"),
)

class TicTacToeGame:
def __init__(self, players=DEFAULT_PLAYERS, board_size=BOARD_SIZE):
self._players = cycle(players)
self.board_size = board_size
self.current_player = next(self._players)
self.winner_combo = []
self._current_moves = []
self._has_winner = False
self._winning_combos = []
self._setup_board()

def _setup_board(self):
self._current_moves = [
[Move(row, col) for col in range(self.board_size)]

9
for row in range(self.board_size)
]
self._winning_combos = self._get_winning_combos()

def _get_winning_combos(self):
rows = [
[(move.row, move.col) for move in row]
for row in self._current_moves
]
columns = [list(col) for col in zip(*rows)]
first_diagonal = [row[i] for i, row in enumerate(rows)]
second_diagonal = [col[j] for j, col in enumerate(reversed(columns))]
return rows + columns + [first_diagonal, second_diagonal]

def toggle_player(self):
"""Return a toggled player."""
self.current_player = next(self._players)

def is_valid_move(self, move):


"""Return True if move is valid, and False otherwise."""
row, col = move.row, move.col
move_was_not_played = self._current_moves[row][col].label == ""
no_winner = not self._has_winner
return no_winner and move_was_not_played

def process_move(self, move):


"""Process the current move and check if it's a win."""
row, col = move.row, move.col
self._current_moves[row][col] = move
for combo in self._winning_combos:
results = set(self._current_moves[n][m].label for n, m in combo)
is_win = (len(results) == 1) and ("" not in results)
if is_win:
self._has_winner = True
self.winner_combo = combo
break

def has_winner(self):
"""Return True if the game has a winner, and False otherwise."""

10
return self._has_winner

def is_tied(self):
"""Return True if the game is tied, and False otherwise."""
no_winner = not self._has_winner
played_moves = (
move.label for row in self._current_moves for move in row
)
return no_winner and all(played_moves)

def reset_game(self):
"""Reset the game state to play again."""
for row, row_content in enumerate(self._current_moves):
for col, _ in enumerate(row_content):
row_content[col] = Move(row, col)
self._has_winner = False
self.winner_combo = []

class TicTacToeBoard(tk.Tk):
def __init__(self, game):
super().__init__()
self.title("Tic-Tac-Toe Game")
self._cells = {}
self._game = game
self._create_menu()
self._create_board_display()
self._create_board_grid()

def _create_menu(self):
menu_bar = tk.Menu(master=self)
self.config(menu=menu_bar)
file_menu = tk.Menu(master=menu_bar)
file_menu.add_command(label="Play Again", command=self.reset_board)
file_menu.add_separator()
file_menu.add_command(label="Exit", command=quit)
menu_bar.add_cascade(label="File", menu=file_menu)

def _create_board_display(self):
display_frame = tk.Frame(master=self)

11
display_frame.pack(fill=tk.X)
self.display = tk.Label(
master=display_frame,
text="Ready?",
font=font.Font(size=28, weight="bold"),
)
self.display.pack()

def _create_board_grid(self):
grid_frame = tk.Frame(master=self)
grid_frame.pack()
for row in range(self._game.board_size):
self.rowconfigure(row, weight=1, minsize=50)
self.columnconfigure(row, weight=1, minsize=75)
for col in range(self._game.board_size):
button = tk.Button(
master=grid_frame,
text="",
font=font.Font(size=36, weight="bold"),
fg="black",
width=3,
height=2,
highlightbackground="lightblue",
)
self._cells[button] = (row, col)
button.bind("<ButtonPress-1>", self.play)
button.grid(row=row, column=col, padx=5, pady=5, sticky="nsew")

def play(self, event):


"""Handle a player's move."""
clicked_btn = event.widget
row, col = self._cells[clicked_btn]
move = Move(row, col, self._game.current_player.label)
if self._game.is_valid_move(move):
self._update_button(clicked_btn)
self._game.process_move(move)
if self._game.is_tied():
self._update_display(msg="Tied game!", color="red")
elif self._game.has_winner():

12
self._highlight_cells()
msg = f'Player "{self._game.current_player.label}" won!'
color = self._game.current_player.color
self._update_display(msg, color)
else:
self._game.toggle_player()
msg = f"{self._game.current_player.label}'s turn"
self._update_display(msg)

def _update_button(self, clicked_btn):


clicked_btn.config(text=self._game.current_player.label)
clicked_btn.config(fg=self._game.current_player.color)

def _update_display(self, msg, color="black"):


self.display["text"] = msg
self.display["fg"] = color

def _highlight_cells(self):
for button, coordinates in self._cells.items():
if coordinates in self._game.winner_combo:
button.config(highlightbackground="red")

def reset_board(self):
"""Reset the game's board to play again."""
self._game.reset_game()
self._update_display(msg="Ready?")
for button in self._cells.keys():
button.config(highlightbackground="lightblue")
button.config(text="")
button.config(fg="black")

def main():
"""Create the game's board and run its main loop."""
game = TicTacToeGame()
board = TicTacToeBoard(game)
board.mainloop()

if __name__ == "__main__":
main()

13
14
15
Skill Developed/ learning out of this Micro-Project We learnt,

1. To demonstrate the use of Operators.


2. To perform operations on data structures in Python.
3. To develop functions for given problems.
4. Efficient communication skills.
5. Working as a team member for developing c program.
6. Developing leadership qualities.

9.0 Applications of the Project

1. This project can be used as an interesting game for children to pass their free
time.
2. The project can be also used to understand the.
3. The project can be used in learning the

16
Conclusion :-

We used this paper to learn different features available in python and its
applications. We used this book to learn the basic concepts of python
programming. We used this book to learn how to builds efficient, flexible and well
integrated programs and system.

References :-

Google

YouTube

i.

17

You might also like