Tic Tac Toe Documentation in Python 3 PDF
Tic Tac Toe Documentation in Python 3 PDF
in python 3
Name - Divyanshu
Class - 12th
Roll No. -
Subject - Computer Science
Subject Code - 083
Submitted to - Mr. Manmohan Jatav
(PGT Computer Science)
ACKNOWLEDGEMENTS
Our due thanks to our Principal Mam, Mrs. Sameena Hasan (M.Ed) ,
for her support throughout the course.
Signature Signature
(PGT Computer Science) (External Examinar)
4
TABLE OF CONTENTS
1 ABSTRACT 4
2 INTRODUCTION 5
2.1 Objective 5
3 SYSTEM ANALYSIS 6
3.1 Existing System 3.2
Proposed System 3.3 7
Feasibility Study 7
4 SYSTEM SPECIFICATION 8
5 SOFTWARE DESCRIPTION 9
7 SYSTEM TESTING 22
7.1 Introduction 22
7.2 Testing Methodologies 22
8 SYETEM IMPLEMENTATION 24
8.1 Purpose 24
CONCLUSIONS AND 25
9
FUTURE ENHANCEMENT
9.1 Conclusion
25
9.2 Scopes for Future Enhancement
25
APPENDICES
10 26
10.1 Program Listing
26
10.2 Screen Shots
30
BIBLIOGRAPHIES
11 33
6
1. ABSTRACT
The game TIC TAC TOE had an early variant which began in the first century in the Roman
Empire. During that time, it was called Terni Lapilli where the players only had three pieces
and had to move around the empty spaces to play. The actual game of TIC TAC TOE could
be traced back to ancient Egypt. The game was also known during that time as ʖThree
Men's Morrisʗ. The first reference to Noughts and crosses was made in 1864 in a British
novel called Can You Forgive Her. For many years the game was referred to as noughts and
crosses but was changed in the 20th century by the United States to TIC TAC TOE.
`
7
2. INTRODUCTION
2.1 OBJECTIVE:
One of the most universally played childhood games is TIC TAC TOE. An interactive TIC TAC
TOE game is developed where two players will be able to play against each other in a suitable
GUI by using proper mouse movements. This game will start by showing a simple display,
prompt the user for a move and then prints the new board. The board looks like a large hash
symbol (#) with nine slots that can each contain an X, an O, or a blank. There are two players,
the X player and the O player. By default, player1 (the O player) takes the initiative. The game
will end in two situations: a win, when one player gets three in a row, horizontally, vertically or
diagonally. A draw, when there are no remaining places to choose and neither of them has
won. Here are some rules for the game:
If all nine squares are filled and none of the players have three in a row,
the game is a draw.
8
3. SYSTEM ANALYSIS
INTRODUCTION:
Analysis can be defined by breaking up of any whole so as to find out their nature, working
functionalities etc. It defines design as to make preliminary sketches of; to sketch a pattern
or outline for planning. To plan and carry out especially by artistic arrangement or in a skilful
wall. System analysis and design can be characterized as a set of techniques and
processes, a community of interests, a culture and intellectual orientation.
This system allows the user to feel the taste of playing the game endlessly. First design the
class which will keeps track various functions like board structure, pixel selection, grid
selection, canvas structure, click recognition, gameplay, game over screen etc. And
according to the moves played by the players this project will display the result in very
attractive format.
The Existing system is a simple game to play with paper and pencil between two people.
Here the whole process will be carried out in the hand-written format making nine square
grids, placing X’s and O’s and checking for the winner. This process will repeat every time.
So, it will be a tedious job to draw a nine square grid every time with paper and pencil. The
human effort is more here. Along with that the retrieval of the information is not easy as the
records are maintained in the hand-written papers. This application requires correct feed on
input into the respective field. Suppose the wrong inputs are entered, then the whole process
is to be done again. So, the users find it difficult to use.
9
To overcome the drawbacks of the existing system, the proposed system has been evolved.
This project aims to reduce the paper work and saving time to generate accurate results
from the player’s perspective. The system provides with the best Graphical User Interface.
The efficient reports can be generated by using this proposed system.
The game has been made user friendly with proper use of graphical
interface.
The user can play as many games without any interpretation.
It is highly reliable, approximate result from user.
The game has been made as a thorough expert system.
The players can win the game, draw the game or will lose the game.
It is a good brain exercise for all age group people.
Feasibility study begins once the goals are defined. It starts by generating board possible
solutions, which are possible to give an indication of what is new system should look like.
That is where creativity and imagination are used. Analysts must think up the new ways of
doing things generating new ideas. There is no need to go into the detailed system operation
yet. The solution should provide enough information to make reasonable estimates about
project cost and give user an indication of how the new system will fit into the organization.
Feasibility of a new system means ensuring that the new system, which we’re going to
implement is efficient and affordable. There are various types of feasibility that should be
taken into consideration:
The technical requirement for the system is economic and it doesn’t use any
other hardware or software. Technical evaluation must also assess whether
the Existing System can be upgraded to use the new technology and whether
the organization has the expertise to use it. Install all the upgrades
frameworks into the Python IDLE package supported Linux based application.
This application mostly depends two packages namely tkinter package and
pygame package provided by Python 3.6.0.
4. SYSTEM SPECIFICATION
5. SOFTWARE DESCRIPTION
5.2.1 PYTHON 3:
Our goal in this article is to provide you with an introductory of GUI programming. In
order to learn the GUI programming, you must first understand a few core aspects of
GUI. So let’s begin the discussion. The primary GUI toolkit will be using Tk, Python’s
default GUI. We’ll access Tk from its python interface called Tkinter. It is not the
latest and greatest nor does it have the most robust set of GUI building blocks, but it
is fairly simple to use and using it, you can build GUI’s that run on most platforms.
Setting up GUI application is similar to how an artist produces a painting. Conventio-
nally there is a single canvas onto which the artist must put all the work. In GUI
programming a toplevel root windowing object contains all of the little windowing
objects that will be a part of your GUI application. These can be text labels, buttons,
list boxes etc. These individual little GUI components are known as widgets. Top
level windows are those that show up stand alone as part of your application.
Interestingly, you can have more than one top level window for your GUI, but only
one of them should be your root window.
import tkinter
top=tkinter.Tk()
The object returned by )tkinter.Tk(
is usually referred to as the root window.
Within this window you can place multiple component pieces together to form your
GUI. Tk has three geometry managers that help with positioning your widget set.
13
Placer: You provide the size of the widgets and locations to place them,
this manager then places them for you.
Packer: It packs widgets into the correct places.
Grid: It is used to specify GUI widget placement based on grid
coordinates.
Now once the packer has determined the sizes and alignments of your widgets, it will
then place them on the screen for you. When all the widgets are in place we instruct
the application to infinite main loop. In Tkinter the code that does it is:
Tkinter.mainloop()
This is normally the last piece of sequential code your program runs.
14
6. PROJECT DESCRIPTION
This project is divided into several modules and all the modules are appearing in one class.
These modules are called from the main module located at the root of the project. All the
modules have different as well as vital functionalities in order to develop the right product.
These modules are designed in such a way that they reflect a highly cohesiveness.
INITIALIZATION:
In the main class we’ve created a constructor which will hold all the tkinter widgets that we
are using in our program. First of all, we’ve used a highly versatile widget called canvas to
draw graphs and plots on our root window. We set the background colour as white. Now we
want to realize the effects that we are made in our root window. For that we have to use the
pack geometry manager. Then we’ve called the bind function, which is actually used to
interact the GUI widget with our computer program. In the bind function we’ve passed two
objects namely '< x >', self.exit. The later one is used to exit from the root window.
In the root window there should be three options displaying at the top level. The minimize
button ( ), the maximize button ( ) and the close button ( X ) . Now whenever the user
clicks on the X button the bind function should capture that and accordingly the root window
will destroy that means it could not be displayed any more. Then we set our game state to
zero ( 0 ) and call the title_screen module. After that we create a list with nine strings and
initiate each of them with a value zero ( 0 ) and store it in a variable called board.
15
TITLE SCREEN:
In this module, what we’ve done is we use the delete method to clear the canvas. We use
the special tag “all” to delete all the items on the canvas. Then we create three rectangles on
our root window. We create these rectangles by using canvas supported standard item call
create_rectangle. For drawing the first rectangle we’ve passed the rectangle bounding size
which is nothing but the original window size and the rectangle options which includes fill
and outline as an object. We choose the white colour as the rectangle boundary colour.
Applying the same procedure, we have created the second rectangle. The only additional
thing that is done here is regardless of sending the original window size we’ll send the
adjusted window size as an object. That means we’ll just modify the X and Y axis is such a
way that the beauty of the window is preserved. Now, for the third rectangle we’ve applied
the same procedure and we select appropriate colour for displaying all the texts that will be
appeared in this rectangle. Now we want to display the title of the game and besides that,
because we also would like to increase the usability of the software that we are developing
so we also have to create another text that will increase the usability of the software. For that
we are using canvas supported standard item called create_text that will enable us to create
informative text on the screen. Intuitively, the title of the game should be TIC TAC TOE and
just below to that another text that will be appearing is Click to play.
NEW BOARD:
The main objective of this module is to create a new board that consists of three rows and
the columns. The board is nothing but a 2 Dimensional three by three matrix and we’ll
create the matrix by using list of strings. So, to do that first we clear all the widgets that is
appearing in the window by using the delete method and passing a special parameter “all”
to it. Then we reset the board by assigning 0 value to all the nine locations in the board.
Now we’ve to draw two lines vertically and horizontally. To achieve this, we have to use
canvas supported another standard item called create_line. To use the create_line function
we should have to pass the line co-ordinates and the line options as a parameter. Thus, we
create a loop which will repeat two times and inside the loop we declare two create_line
functions with appropriate X co-ordinates, Y co-ordinates, grid / line width and grid colour.
Insides the loop we use the create_line function twice because one is for drawing the lines
vertically and the other one does the desired job for us by creating the lines horizontally. By
this we’ve completed our board structure.
16
GAMEOVER SCREEN:
This module is concerned with displaying the result according to the outcome on the screen.
It takes outcome as an object and displays the appropriate result. If the outcome is in favour
of player 1, “O Wins” appears on the screen in the form of a text. Similarly, if the outcome is
in favour of player2, “X Wins” should appear on the screen and if the outcome is a draw,
then both the players will see the text “Draw” on the screen. We add one extra feature in the
game over module by introducing a text called “Click to play again” and we’re very
optimistic that it should increase the usability of the developed software. For displaying the
texts, we’ve used the canvas supported standard item call create_text function. In the game
over screen firstly we create a rectangle on the canvas and fills it with appropriate colour and
inside that rectangle all the texts will appear. We’ve created the texts by adjusting the text
size, font style, text height, text width and text colour.
CLICK:
This module handles most of the game logic. A tkinter application runs most of its time inside
an event loop, which is entered via the main loop method. It waits for an event to happen.
Events are generally key pressed or mouse operations by the users. We’ve already set the
game states globally by assigning the values STATE_TITLE_SCREEN to 0, STATE_X _TURN
to 1, STATE_O_TURN to 2 and STATE_GAME_OVER to 3. In the click method we’ve passed
the first argument implicitly (called ‘self’) which is the reference to our main class itself and it
should have the ‘event’ object that merely describes what is actually happened. We begin our
task by converting the pixels into gird coordinates and then we have to check for the current
game state condition and accordingly the game will continue. Now if game state is 0, then it
will draw a new board on the screen and sets the game states as the value of the first player.
If the game state is 1 i.e. X’s turn and the cell is empty then the control goes to new move
module (where we’ve to mandatorily pass the current player and the board coordinates as
arguments) and the appropriate cell is filled up with symbol X. Now it checks all the possible
conditions (i.e. whether player X has won or it is a draw) one by one. So, at first the control
moves to has won module and if the result is true then it sets the game state to 3 and calls the
game over module by passing the parameter ‘X wins’. If it is false then the control goes to is a
draw module and if the result is true then again it will set the game state to 3 and calls the
game over module with the parameter ‘Draw’. If the result of both the cases is false then only
it will set the game state as 2 which is nothing but player O can now take its turn. Now If the
game state is 2 i.e. O’s turn and the cell is empty then the control goes to new move module
and the appropriate cell is filled up
17
with symbol O. Now, it checks all the possible conditions (i.e. whether player O has won or it is
a draw) one by one. So, at first the control moves to has won module and if the result is true
then it sets the game state to 3 and calls the game over module by passing the parameter ‘O
wins’. If it is false then the control goes to is a draw module and if the result is true then again
it will set the game state to 3 and calls the game over module with the parameter ‘Draw’. If the
result of both the cases is false then only it will set the game state as 1 which is nothing but
player 1 can now again take its turn. Finally, it checks for if the game state is being at 3 or not.
If it is 3, then it will reset the board by calling the module new board and sets the game state
according to the first player. With this we’re completing most of the work that is behind our
game logic.
NEW MOVE:
This module is concerned with pacing the X’s and O’s in the selected cells on the board. It
receives the current player and the grid coordinates from the click module as an argument
and places the symbol of the player in the desired cell. Now let us consider our board
structure:
Here X and Y are 0 based grid coordinates. If the current player is X then it will call the draw
X module (discussed later) with the grid coordinates and places the X symbol with
appropriate size and colour into that grid. Now if the current player is O then it will call the
draw O module with the 0 based grid coordinates and places the O symbol into that cell.
DRAW X:
This module deals with drawing X on the canvas. So, for that what we’ve to do is, first of all
we’ve to convert the grid into pixels and then we can start our drawing using canvas
supported standard packages namely create_line. For that reason, we’ve called the
grid_to_pixel module twice and we get the converted pixels. Now we must have to adjust
18
the width and height of the X so that no extra outline would appear in the right-hand side and
left-hand side. We divide he cell size by 2 and multiplied it with the symbol size and store it
in a variable called delta. By adjusting the delta, choosing the colour and selecting the width
in the create_line function we’ve completed our task.
DRAW O:
This module is concerned with drawing an O on the canvas. Like the previous module, here
also we’ve to convert the grid coordinates into pixels and then we’ve to adjust the O’s in the
board. Again, we divided the cell size by 2 and multiplied it with the symbol size and
assigned it in a variable called delta. For drawing an O we’ve to use the canvas supported
standard package called create_oval function. In create_oval function, pixel coordinates are
adjusted in such a way that the O’s have no odd lines on the left-hand side as well as right-
hand side. Then we select the appropriate width and the colour for O’s so that it looks better.
HAS WON:
This module is concerned with checking for the winner and returns the result to an
appropriate calling function. In the click module, we’ve already converted the grids into
pixels and store them into some variables. Now the has_won function takes those pixels as
an argument and accordingly the board will fill up with the winning symbols. The checking for
the winner is quite simple. If any of the players can able to fill all the cells in a row vertically
or horizontally or diagonally, he /she will consider to be the clear winner. So, in the first for
loop, we basically check that whether all the cells of a row (vertically or horizontally or
diagonally) are filled with the same symbol or not. Now if this condition satisfies, then the
player with that symbol is the winner. In the second for loop we need to check those
positions that are conventionally reserved for the winning position. So, we need to check the
positions ([0][0],[0][1],[0][2]) or ([1][0],[1][1],[1][2]) or ([2][0],[2][1],[2][2]) or ([0][0],[1][0],[2][0])
or ([0][1],[1][1],[2][1]) or ([0][2],[1][2],[2][2]) or ([0][0],[1][1],[2][2]) or ([0][2],[1][1],[2][0]) and by
checking these positions we will certainly get the winner.
IS A DRAW:
In this module, we’re just checking the result is a tie or not. The result is a tie when all the
boxes/cells are filled. Checking whether it is a draw is fairly straightforward. All we’ve to do is
check whether all the board boxes are filled. We can do this by iterating through the board
array.
19
GRID TO PIXELS:
The main objective of this module is to transform the grid coordinate into pixels. Intuitively
weʓve passed the grid coordinate as an argument and this module returns accurate pixel
coordinate of the centre. The pixel coordinate should be calculated with the help of grid
coordinate and the cell size. Thus, we add the original cell size with the half of it and multiplied
it with the gird coordinate and stored the result in a variable called pixel_coord. By doing this,
the grid to pixel transformation is mostly done.
PIXELS TO GRID:
It is just the reverse of the previous module. This module performs exactly the opposite task,
taking a pixel coordinate as an argument and converting this into its equivalent grid coordinate.
Somehow the canvas has a few extra pixels on the right and bottom side so weʓve to fix this.
For clipping the extra pixels, we must check the condition that if the pixel coordinate is
somehow greater than the original window size then weʓve to reduce the window size. The
transformation can be achieved by dividing the pixel coordinates by the cell size. The resultant
grid can now be stored into a variable say grid_coord.
EXIT:
This module is used for closing the root window permanently. In this module weʓve
passed event as an argument based upon this event the window can be
closed. We want the access from the current instance in our exit () method which is
done through self.
self.destroy()
However, this only destroys the frame and its child windows, like the canvas,
not the top-level window.
20
Start Game
Player 1
moves
Player 2
moves
Check the
result
Player 1 Player 2
Play again
23
Input design is part of overall system design that requires special attention designing input data
is to make the data entered easy and free from errors. The input forms are designed using the
controls available in PYTHON INTERPRETER. Validation is made for each and every event
that is happened. Help (how to play the game) information is provided for the users during
when the players feels difficult.
Input design is the process of converting the user originated inputs to a computer-based
format. A system user interacting through a workstation must be able to tell the system
whether to accept the input to produce reports. The collection of input data is considered to
be most expensive part of the system design. Since the input has to be planned in such a
manner so as to get relevant information, extreme care is taken to obtain pertinent
information.
Output design this application ʖTIC TAC TOE” generally refers to the results and information
that are generated by the system for many end-users; output is the main reason for developing
the system and the basis on which they evaluate the usefulness of the application.
The output is designed in such a way that it is attractive, convenient and informative. Board
is designed with various features, which make the console output more pleasing. As the
outputs are the most important sources of information to the users, better design should
improve the systemʓs relationships with us and also will help in decision making. Form
design elaborates the way output is presented and the layout available for capturing
information.
One of the most important factors of the system is the output it produces.
This system refers to the results and information generated. Basically, the
output from a computer system is used to communicate the result of processing
to the user.
24
7. SYSTEM TESTING
7.1 INTRODUCTION
Once source code has been generated, software must be tested to uncover and correct as
many errors as possible before delivery to customer. Our goal is to design a series of test
cases that have a high likelihood of finding errors. To uncover the residual errors software
techniques are used. These techniques provide systematic guidance for designing test that
Exercise the internal logic of software components, and
Exercise the input and output domains of the program to uncover errors in program
function, behaviour and performance.
7.1.1 STEPS:
Since this is a game which may have various forms of user input, it would be nearly
impossible to test every possible user combination. However, testing functionality
and likely user scenarios should be our overall goal of testing Tic-Tac-Toe. Unit
testing focuses verification effort on the smallest unit of software design- the software
component or module. The unit test is white-box oriented. The unit testing is
25
implemented in every module of this project by giving correct manual input to the
system, the inputted data are stored in database and can be retrieved. If you want
required module to access input or get the output from the End user, any error will
accrue that time will provide handler to show what type of error will accrued.
First and most importantly we will ensure the tkinter builds and runs
without errors. Also make sure it still works while embedded. GUI should
display correctly on the root window. There should be no states which
freeze the game. Switching between the players should update seamlessly
and no logical errors should occur. All warnings (highlights) should be
identified by the game state and displayed correctly by the GUI. All in all,
a full game should be playable without programming or logical errors.
System testing is actually a series of different tests whose primary purpose is to fully
exercise the computer-based system. Below we have described the two types of
testing which have been taken for this project. it is to check all modules worked on
input basis. If you want change any values or inputs, it will change all information, so
specified input is must. System testing can be stated as the process of validating and
verifying that a computer program / application / product:
8. SYSTEM IMPLEMENTATION
8.1 PURPOSE
System implementation is the important stage of project when the theoretical design is tuned
into practical system. The main stages in the implementation are as follows:
Planning
Training
System testing and
Changeover Planning
Planning is the first task in the system implementation. At the time of implementation of
any system people from different departments and system analysts involve. They are
confirmed to practical problem of controlling various activities of people outside their own
data processing departments.
Software maintenance is far more than finding mistakes. Provision must be made for
environment changes, which may affect either the computer, or other parts of the computer-
based systems. Such activity is normally called maintenance. It includes both the improvement
of the system functions and the corrections of faults, which arise during the operation of a new
system. It may involve the continuing involvement of a large proportion of computer
department recourses. The main task may be to adapt existing systems in a changing
environment. Back up for the entire database files are taken and stored in storage devices like
flash drives, pen drives and disks so that it is possible to restore the system at the earliest. If
there is a breakdown or collapse, then the system gives provision to restore from database
files. We focus on four types of maintenance:
Adaptive Maintenance
Perfective Maintenance
Corrective Maintenance
Preventive Maintenance
27
An option to increase the board to size to n x n, where n can be any positive number (>0).
This will increase the complexity of the code and when added with artificial intelligence will
greatly make the game robust. Also, we can add a feature where k(< n) consecutive
marks/dots (filled by the user) is a point/score. Or we can go even further and use a range of
number n.
An option of playing against the computer (machine) can be added too. An algorithm can be
implemented for the machine based on actual rules a player uses to fill the Tic-Tac-Toe
board. This can pose a challenge to the user when playing.
One option to select the difficulty levels of the game can be added. We would also like to
create a computer AI that offered increasing resistance as the difficulty level increase
One of the other enhancements could be that users can create their profiles and save their
scores.
IN-GAME ASSISTANT:
An option to include an Assistant which will provide hints and suggestions to the user when
playing against a bot.
28
10. APPENDICES
def __init__(self):
Tk.__init__(self)
self.canvas = Canvas(height=WINDOW_SIZE,
width=WINDOW_SIZE, bg='white')
26 self.canvas.pack()
27 self.bind('<x>', self.exit)
28 self.canvas.bind('<Button-1>', self.click)
29 self.gamestate = STATE_TITLE_SCREEN
30 self.title_screen()
31 self.board = [
32 [EMPTY, EMPTY, EMPTY],
33 [EMPTY, EMPTY, EMPTY],
34 [EMPTY, EMPTY, EMPTY]]
35
36 def title_screen(self):
37 self.canvas.delete('all')
38 self.canvas.create_rectangle(0, 0,WINDOW_SIZE,
39
WINDOW_SIZE,fill='white',outline='')
40
41 self.canvas.create_rectangle( int(WINDOW_SIZE/15),
42 int(WINDOW_SIZE/15),
43 int(WINDOW_SIZE*14/15),
44 int(WINDOW_SIZE*14/15),
outline='')
self.canvas.create_rectangle( int(WINDOW_SIZE/10),
int(WINDOW_SIZE/10),
int(WINDOW_SIZE*9/10),
int(WINDOW_SIZE*9/10),
fill='light blue', outline='')
29
45 self.canvas.create_text(WINDOW_SIZE/2, WINDOW_SIZE/3,
46 text='TIC TAC TOE', fill='black',
47 font=('Calibri', int(-WINDOW_SIZE/12),
48 'bold underline'))
49 self.canvas.create_text(int(WINDOW_SIZE/2),
50 int(WINDOW_SIZE/2.5), text='[click to play]',
51 fill='purple', font=('Arial', int(-
52 WINDOW_SIZE/25)) )
53
54 def new_board(self):
55 self.canvas.delete('all')
56 self.board = [
57 [EMPTY, EMPTY, EMPTY],
58 [EMPTY, EMPTY, EMPTY],
59 [EMPTY, EMPTY, EMPTY] ]
60 for n in range(1, 3):
61
self.canvas.create_line(CELL_SIZE*n, 0,
CELL_SIZE*n, WINDOW_SIZE,
width=GRID_LINE_WIDTH,
fill=GRID_COLOR)
62 self.canvas.create_line(0, CELL_SIZE*n,
63 WINDOW_SIZE, CELL_SIZE*n,
64 width=GRID_LINE_WIDTH,fill=GRID_COLOR )
65
66 def gameover_screen(self, outcome):
67 self.canvas.delete('all')
68 if outcome == 'X WINS':
69 wintext = 'X wins'
70 wincolor = 'light green'
71 elif outcome == 'O WINS':
72 wintext = 'O wins'
73 wincolor = 'gold2'
74 elif outcome == 'DRAW':
75
wintext = 'Draw'
76
wincolor = DRAW_SCREEN_COLOR
77
78 self.canvas.create_rectangle( 0, 0,
WINDOW_SIZE, WINDOW_SIZE,
79
80 fill=wincolor, outline='')
81 self.canvas.create_text(int(WINDOW_SIZE/2), int(WINDOW_SIZE/2),
82 text=wintext, fill='black',
font=('Calibri',int(-WINDOW_SIZE/6),
'bold'))
83 self.canvas.create_text( int(WINDOW_SIZE/2),int(WINDOW_SIZE/1.65),
84 text='[Click to play again]',
85 fill='purple', font=('Arial',
86 int(-WINDOW_SIZE/25)) )
87
88 def click(self, event):
89
x = self.pixel_to_grid(event.x)
90
91 y = self.pixel_to_grid(event.y)
if self.gamestate == STATE_TITLE_SCREEN:
92
93 self.new_board()
94 self.gamestate = FIRST_PLAYER
95 elif(self.gamestate==STATE_X_TURN and self.board[y][x]==EMPTY):
96 self.new_move(X, x, y)
97 if self.has_won(X):
98 self.gamestate = STATE_GAME_OVER
99 self.gameover_screen('X WINS')
100 elif self.is_a_draw():
self.gamestate = STATE_GAME_OVER
self.gameover_screen('DRAW')
30
101 else:
102 self.gamestate = STATE_O_TURN
103 elif(self.gamestate==STATE_O_TURN and self.board[y][x]==EMPTY):
104 self.new_move(O, x, y)
105 if self.has_won(O):
106 self.gamestate = STATE_GAME_OVER
107 self.gameover_screen('O WINS')
108 elif self.is_a_draw():
109 self.gamestate = STATE_GAME_OVER
110 self.gameover_screen('DRAW')
111 else: self.gamestate = STATE_X_TURN
112
113 elif self.gamestate == STATE_GAME_OVER:
114 self.new_board()
115 self.gamestate = FIRST_PLAYER
116
117
118 def new_move(self, player, grid_x, grid_y):
119 if player == X:
120 self.draw_X(grid_x, grid_y)
121 self.board[grid_y][grid_x] = X
122 elif player == O:
123 self.draw_O(grid_x, grid_y)
124 self.board[grid_y][grid_x] = O
125
126 def draw_X(self, grid_x, grid_y):
127 x = self.grid_to_pixel(grid_x)
128 y = self.grid_to_pixel(grid_y)
129 delta = CELL_SIZE/2*SYMBOL_SIZE
130 self.canvas.create_line( x-delta, y-delta,
131 x+delta, y+delta,
132 width=SYMBOL_WIDTH, fill=X_COLOR)
133 self.canvas.create_line( x+delta, y-delta,
134 x-delta, y+delta,
135 width=SYMBOL_WIDTH, fill=X_COLOR )
136
137 def draw_O(self, grid_x, grid_y):
138 x = self.grid_to_pixel(grid_x)
139 y = self.grid_to_pixel(grid_y)
140 delta = CELL_SIZE/2*SYMBOL_SIZE
141 self.canvas.create_oval( x-delta, y-delta,
142 x+delta, y+delta,
143 width=SYMBOL_WIDTH, outline=O_COLOR )
144
145
146 def has_won(self, symbol):
147 for y in range(3):
148 if self.board[y] == [symbol, symbol, symbol]:
149 return True
150 for x in range(3):
151 if self.board[0][x]==self.board[1][x]==self.board[2][x]==symbol:
152 return True
153 if self.board[0][0]==self.board[1][1]==self.board[2][2]==symbol:
154 return True
155 elif self.board[0][2]==self.board[1][1]==self.board[2][0]==symbol:
156 return True
157 return False
158
159 def is_a_draw(self):
160 for row in self.board:
161 if EMPTY in row:
return False
return True
31
11. BIBLIOGRAPHY
BOOKS REFERENCES:
1. Python and
Without FearProgramming
Tkinter BRIAN OVERLAND.
JOHN E. GRAYSON.
2. P
3. A Practical Introduction to python Programming BRIAN HEINHOLD.
4. I nvent Your Own Computer Games with Python 3rd Edition AL SWEIGART.
5. T he Coder’s Apprentice Learning Programming with Python 3 PIETER SPRONCK.
OTHER REFERENCES:
1 Tic Tac Toe Documentation Release 0.1 by Deterralba December 18, 2015.
. International Journal of Computer Trends and Technology (IJCTT) – volume 12
2 number2– Jun 2014 ISSN: 2231-2803 http://www.ijcttjournal.org/ Page71
. Implementation of Tic-Tac-Toe Game in LabVIEW. Interactive tic tac toe Stefan Bennie
3. Botha.
WEBSITES:
1 https://effbot.org/
. http://codeproject.com/
2 http://stackoverflow.com/
.
3
.