Files
004_comission/jktjoeaj703/task1/_from_client/reports/document.md
louiscklaw 0c89a0db81 update,
2025-01-31 21:31:32 +08:00

55 KiB
Raw Blame History

SBA Tic Tac Toe

Name: Joe, Anthony Kar Tong

Class: 6D

Class number: 9

Teacher: Mr Lee

Deadline: 12/12/2024

Google link:

Content

1. Pre work1

1.1 Problem analysis 3

1.2 Selection of programming language2

1.3 Selection of Python IDE2

1.4 CLI vs GUI3

1.5 Tkinter vs Pygame vs PyQt3

2. Programming (Tic Tac Toe)4

2.1 Flowchart (PPT)5

2.2 Program (explanation + Variable/constant declaration)(PPT)6

2.3 Game logic6

2.4 Modular approach3

2.5 Scope of Variables and Parameter Passing3

2.6 Program Interface Design3

2.7 Data collections and, input and validation3

2.8 Sorting and searching algorithms3

2.9 Programing output3

2.10 Error handling3

2.11 Reusability and portability3

3. Testing & Evaluation4

3.1 Test data 3

3.2 Test cases 3

3.3 Debugging Process3

3.4 Unit Testing and System Testing3

3.5 User Acceptance Testing (survey)3

3.6 Pros and Cons of the Program (by survey)3

3.7 Modifications (during programming)3

4. Further modifications4

4.1 Numpy3

4.2 AI implement3

4.3 User Experience Enhancement3

5. Conclusion4

5.1 Summary of the program3

5.2 Learning outcomes 3

    1. Problem analysis

Before the start of the programming, brainstorming and define the workflow of the project is of importance to reduce error.

      1. Understanding the problem
  • Create a tic tac toe game includes two players
  • Create a tic tac toe game includes players vs computer
  • Including login functions (create player, change password and delete player)
  • Including record results function
  • Including display results function

Key aspects:

  • How do user input?
  • Game logic? (Computer part)
  • Operating methods?
  • Result display
      1. Game rules

*Break down the rules into program elements

  • Win = forming a row/column/diagonal
  • Tie = board full but no row/column/diagonals is formed
  • Player alternate turn
      1. System of tic tac toe

A Standalone system should be used. That means the game does not require an internet connection after owning the program as long as database

      1. Target audience

As tic tac toe is just a easy game with simple rules, target audience is supposed to be above 5 years old.

      1. Functional requirements
  • Allow players to input moves
  • Refresh the game board after each move
  • Check for the game condition
      1. Non-functional requirements
  • User-friendly
    1. Outline drafts

Display record

Game over

username

login

password

Display name

Player 1 / Player 2 login

  1. Xxx win: 10 lose:1
  2. Yyy win:10 lose:2
  3. Zzz win:9 lose:1
  4. Aaa win:8 lose:2
  5. Bbb win:7 lose:6

Change password

New password

username

Change password

exit

Ranking list

    1. Selection of programming language

With the meteoric advancement of technology, some parents would even like the first language of their children to be Java. Programming serves as a dominant role in the development of the world and already permeates into our daily life, it is ubiquitous anywhere, leading to the emergence of various programming languages over the past fifty years. Which is the best? Is there a big difference among those languages? Each programming language has its advantages and disadvantages. Each program is created to solve a specific problem and they all shine in different ways. But which one should be used? To answer the above queries, I am going to shed some light on several different programming languages and why I pick up “Python”.

      1. C++

It evolved from C, it provides features like object-oriented programming capabilities without sacrificing speed or efficiency.

: Object-oriented features

: High performance

: Not beginner-friendly

: complex syntax

      1. JavaScript

It is a versatile and high-level language primarily used for web development

: High flexible

: Flexible syntax can lead to inconsistencies

      1. Java

It is a high-level object-oriented language designed to be cross platform.

: Strongly typed

: platform independent

: Flexible syntax confusing for beginners

      1. Python

It is a high-level programming language known for its readability and simplicity

: Beginner-friendly and Easy to learn

: Extensive built-in functions and libraries

: poor web development

      1. Why python?
  1. Beginner-Friendly

With simpler syntax, its easier to read and write and debugging.

  1. Rich libraries

There are lots of built-in functions. While making the game, I may try to use libraries like Tkinter for GUI or Pygame for game development. I may also use NumPy for sorting and searching.

  1. Strong Community support

There are extensive resources and abundant tutorials helping while programming.

  1. Cross platform

It allows running the program anywhere. Its compatible with multiple operating systems.

    1. Selection of Python IDE
      1. IDLE

: beginner friendly with a distraction-free environment

: lightweight and fast, ideal for small projects

: limited debugging tools

: less customization

: lack advanced features for scaling projects

      1. Jupyter

: Simple interface with markdown integration for documentation

: large community support

: Poor support for Tkinter GUIs; rendering often fails

: Minimal debugging tools, unsuitable for GUI development

      1. PyCharm

: Contain advanced debugging tools

: Highly customizable

: Resource-intensive, heavy for small projects

: Steep learning curve for beginners

      1. Thonny

: Designed for beginners and educators with a simple interface

: Lightweight and efficient for small projects

: Limited customization options

      1. Visual studio Code

: Lightweight, fast, and easy to set up

: Excellent built-in debugging tools with breakpoints

: Highly customizable with a large library of extensions

: Suitable for developers of all skill levels

: Lacks advanced features of a full-fledged IDE like PyCharm

      1. Summary
IDLE Jupyter PyCharm Thonny VS code
Best for Beginners Data science Professionals Beginners All skill level
Ease of use ✓✓✓ ✕✕ ✓✓✓ ✓✓✓
Resource Usage ✓✓✓ ✓✓
Debugging ✓✓✓ ✓✓
GUI support ✓✓✓ ✓✓✓ ✓✓✓ ✓✓✓

To sum up, VS Code offers advantages like easy setup, syntax highlighting, debugging, modular organization, and broad extension support, making it ideal for GUI Tic Tac Toe. While PyCharm has stronger debugging tools, VS Code is more than sufficient for this project.

    1. CLI vs GUI

For a game, theres usually a lot of input and output, and monitor I/O is involved. Thus, there is command line interface and Graphical user interface.

So, CLI vs GUI, which is better?

CLI: x 23 x 89 Please enter your option: 1 2 3 4 O Display the board: Assign X: Assign O: Check winner: Exit : Player A wins Please enter your option: 1 2 3 4 O Display the board: Assign X: Assign O: Check winner: Exit : GUI:

After making both cli and gui type tic tac toe, here comes a conclusion

Summary:

CLI GUI
Interface Text-based. Requires players type grid positions Graphical board with clickable buttons and canvas
Libraries/Tools Core Python or libraries like argparse Libraries like Tkinter, Pyqt or Pygame and numpy
User Interaction Input though text Input though click buttons or cells to make moves
Development Complexity Simple and minimal coding required More complex as involved GUI layout design and event handling
Visual Appeal Minimal and relies on formatted text like ASCII Attractive and direct with graphical elements on the board
Feedback Mechanism Displays updated board and messages in the terminal moves visually and combine with colors or animations for feedback
Performance Lightweight and fast execution in any terminal. Slightly heavier due to graphical rendering
Storage size Smaller as only text involved Larger due to graphical handling and canvas
Learning Curve Beginner-friendly; focuses on game logic Steeper; involves learning a GUI library in addition to game logic
Deployment Single script that is easy to run on any terminal Requires additional dependencies and cross-platform testing
Audience Suited for developers or technical users Suited for general users including kids or non-technical people
Time to Build Short and focus only on game logic. Longer as it includes layout design and event handling
    1. Tkinter vs Pygame vs PyQt
Tkinter Pygame PyQt
Ease to use Easy to use Moderate as it involves managing game loops Difficult and requires the knowledge of Qt framework
Built-in Widgets Yes (buttons, labels, frames, etc) None, manual creation is required Yes, advanced widgets for complex GUIs
Setup and Dependencies Comes preinstalled with Python Requires installation and additional setup Requires installation and heavier dependencies
Performance Lightweight and efficient for tic tac toe Optimized for games with better graphic Heavy due to advanced features
Cross-Platform Support Yes Yes Yes
Learning Curve Low Moderate High
Customization Moderate High, support pixel-level control Very high, support extensive styling
Animation Support Limited but sufficient for tic tac toe Good for animations and games Yes, but requires implement
Resource Intensity Low Moderate High
Community Support Large and beginner-friendly Large and focused on game development Large, professional-focused
Use Case Suitability Ideal for small to medium-scale applications Best for game development with rich visuals Best for large-scale and professional GUIs
Code Complexity Simpler Moderate, involves game-specific design Complex and require structured programming
Deployment Easy, no extra dependencies required Moderate, requires bundling assets Complex, needs Qt runtime and packaging
Target Audience Beginners and general-purpose developers Game developers Professional developers and advanced users
      1. Why tkinter?
  1. Minimal Setup

It is pre-installed, unlike Pygame and PyQt, which require additional dependencies.

  1. Ease of Use

Friendly for beginners, making it suitable for projects like a Tic Tac Toe game.

  1. Lightweight

Consumes fewer system resources, ensuring smooth performance on various devices.

  1. Versatile Widgets

Offers built-in tools like button, frame or messagebox and so on for quick GUI construction without extensive coding.

Tkinter stands out for its simplicity and efficiency in developing small-to-medium applications, balancing functionality and ease of development effectively.

2.3 Game Logic

Both PvPEngine(Player vs player) and PvCEngine(Player vs Computer) share the same basic logic, in this chapter, I would like to shed more light on PvCEngine, explaining the logic and how the whole engine works.

      1. Canvas

![一張含有 文字, 螢幕擷取畫面, 軟體 的圖片

自動產生的描述](data:image/png;base64...)

^Canvas drawing of player vs computer

![一張含有 文字, 行, 螢幕擷取畫面, 圖表 的圖片

自動產生的描述](data:image/png;base64...)

  • Used create_line() combine with coordinates and input fill=colour, width=the thickness of the line to draw vertical and horizontal board lines.
  • Used create_oval() to draw the circle
      1. Array

In order to control the game board, I created a 3x3 2D array with function name array.

Same as all 2d arrays, the corresponding board is equal to array[y][x]

e.g. if assign array[2][1] = 2

result: ![一張含有 螢幕擷取畫面, 字型, 數字, 設計 的圖片

自動產生的描述](data:image/png;base64...)

  • Refer to my program:

![一張含有 文字, 螢幕擷取畫面, 字型 的圖片

自動產生的描述](data:image/png;base64...)

The outer for-loop stands for y value will be 0 -> 1 -> 2 and so do the value of x in the inner for-loop. In this for loop, 9 blocks inside the array will all be searched.

As we already assigned player1=1 and player2=2, i.e. oval stands for player1 and X-shape stands for player2 or computer.

      1. Player Input

By using bind(), a method in tkinter to handle the function with mouse click.

  • Refer to my program:

This line means when Button is clicked, the function click will run.

Besides using bind(), I use e, stands for event, to get the coordinate of the mouse when clicking.

  • Refer to my program:

![一張含有 文字, 螢幕擷取畫面, 字型, 數字 的圖片

自動產生的描述](data:image/png;base64...)

e.x and e.y stands for the coordinate(x,y) of the clicked point.

As each block of the game board is 200x200 pixels, by dividing 200 combine with using int() to give up the decimal points, and can get the normal mx and my that used in normal 2D-array.

![一張含有 文字, 螢幕擷取畫面, 字型, 行 的圖片

自動產生的描述](data:image/png;base64...)

Due to e.x and e.y may exist 600 and contribute to 3 as a result, so when the result is larger than 2, it is count as 2.

      1. Computer input logic*** Simple AI

In order to prevent computers input is too fast that player may not notice which is the computers current step, adding 0.5 seconds in between the players input and the computers input using library time.

  • Refer to my program:

+

Besides using library time, there is intelligence and thinking progress for the computer to put the next step instead of random input.

Thinking progress:

  1. Win in this step
  2. Block the player
  3. Random Input
  4. Search all cells and find the positions of X that would allow the computer to win in this step
  5. If such a position exists, place X there to allow the computer to win immediately
  6. If no winning position exists, check all the cells again to find positions where two O is placed, and where the player would win in next step.
  7. If such a position exists, place X there to block the player from winning.
  8. If neither of the above two conditions exist, make a random move.

This is a strategy designed to make the computer play intelligently without needing the complexity of advanced algorithms or import ai. It focuses on winning and blocking.

  • *****Refer to my program:*

Random assign x and y

  1. Use double for-loop find empty space and place O
  2. If O form a line, put X on that block
  3. If no, delete the O
  4. Use double for-loop search empty space
  5. Use check_win_pvc() check whether a line is formed
  6. If yes, count + 1
  7. If no, delete the X
      1. Check win

As this is a 3x3 game board, we just need to determine whether vertical, horizontal and diagonals formed a line or not.

  • Refer to my program:
一張含有 文字, 螢幕擷取畫面, 軟體, 陳列 的圖片 自動產生的描述**^** Check win function of player vs player mode 一張含有 文字, 螢幕擷取畫面 的圖片 自動產生的描述**^** check win function of player vs computer

**![一張含有 文字, 螢幕擷取畫面, 字型 的圖片

自動產生的描述](data:image/png;base64...)**Logic:

    1. Modular approach

The goal of modular approach is to divide the program into smaller, manageable sections so it will be simpler to debug, do tests and ensure the code is organized and reusable. The more modular approach, the more neat and tidy.

While my program is highly modular approach and there are various classes and functions. They are well divided into different parts for corresponding use.

      1. PvPEngine and PvCEngine Classes
  • PvPEngine and PvCEngine are classes for managing the rules and outcomes in Player vs Player (PvP) and Player vs Computer (PvC) modes.
  • Functions like check_win_pvp and check_win_pvc check game conditions by scanning the array for in rows, columns or diagonals.
  • The reset and replay function resets the array matrix to 0,0,0],[0,0,0],[0,0,0 and clears variables such as count and winner.
  • Computer function contains a simple ai with logic :
        1. Win immediately if possible.
        2. Block the opponents winning move.
        3. Make a random move if no critical action is required.

This logic is managed in the PvCEngine class using function check_win_pvc

      1. GUI
  • OXApp is the central controller for the GUI, managing transitions between frames like StartPage, PlayerVsPlayerPage, and GameOverPage.

  • Function matrix is used for drawing the game board, including lines, circles, and crosses, using Tkinters Canvas widget.

      1. Player interaction
      2. Classes like PlayerVsPlayerPage and PlayerVsComputerPage contains click method that capture the mouse click events via Tkinters built in bind() function.
  • PlayerVsPlayerPage class contain current_player variable that allow player1 and player2 input in different turn.
      1. Data management
  • The class RankingPage can use CSV files to store and sort player rankings based on wins, losses, and ties and display the data though on_showframe function. It displays sorted rankings on the RankingPage frame, providing players with a clear view of their performance.

  • Functions such as read_ranking can use the CSV file to maintain up-to-date information.

  • The class SettingPage includes functions like create_player, delete_player and check_playername_and_passwords for creating, deleting, and checking player accounts. It also ensures secure storage of player credentials in an external file.
    1. Scope of Variables and Parameter Passing
      1. Global Variables

My global variables are shared across the entire program to manage overall game state and data consistency. There are game_mode, pvc_cvs, pvp_cvs, array, count, check_win, player1, player2, current_player, winner, player_1_name, player_2_name, ranking.

      1. Local Variables

Local variables are used within specific functions or methods for temporary tasks. Ther are x, y, X, Y, mx, my. These variables are for specific tasks like drawing the game board or detecting mouse clicks.

      1. Global variables vs Local variable
Global variables Advantage Easy to make and manage, reduce the complicity of the program
Disadvantage Over-reliance on global variables can make debugging and testing more challenging. If there is an incorrect update to array may affect multiple functions relying on it
Local variables Advantage Keeps functions modular and reduces side effects
disadvantage It will make the program more complicated
      1. Pass by value

If a parameter is passed by value, the caller and callee have two independent variables with the same value. If the callee modifies the parameter variables, the effect is not visible to the caller. In my program, variables like player_1_name and player_2_name are passed as arguments to functions like display_win() for showing the winners name without altering the global variables. And also for the count variable, which tracks the number of moves, is incremented locally but reset globally when the game state is reset.

      1. Pass by reference

If a parameter is passed by reference, the caller and the callee use the same variable. If the callee modifies the variable, this act will change the callees variable. For example, array is passed by reference, check_win_pvp or check_win_pvc directly modify it without needing to return updated values.

    1. ![一張含有 圖表, 行, 方案, 工程製圖 的圖片

      自動產生的描述](data:image/png;base64...)Programming interface design

The program interface is GUI(Graphic User Interface),

Start Page Setting Page
Player 1 Login Player 2 Login
PvP Game Board PvC Game Board
Game Over Page Ranking Page
    1. Data collection, input and validation

Data are collected in two ways, they are mouse click and also typing though keyboard. For validation, there is just presence check and there is no verification for the player.

      1. Mouse click input

As this game is a GUI system, players interact with the game board using mouse clicks to place “X” or “O” and take the value of the coordinate of the mouse click to determine the corresponding place of array.

Some details of input may refer to 2.3.1 and 2.3.3

      1. Keyboard input

As my program contains registration system, I need to collect players usernames an passwords though text input though tkinter Entry widget.

  • Refer to my program:

![一張含有 文字, 螢幕擷取畫面, 字型 的圖片

自動產生的描述](data:image/png;base64...)

![一張含有 文字, 螢幕擷取畫面, 字型 的圖片

自動產生的描述](data:image/png;base64...)

These Entry widgets allow players to type their names, which are later validated and stored.

      1. Validation for mouse click

My program will ignore invalid moves or clicks on the board. Nothing will happen if player clicks within the coordinate that is not empty.

      1. Presence check

For those entry box, I added presence check for each of them. This ensures the username and password are not empty. There will be messagebox as the reminder if it is blank.

  • ![一張含有 文字, 螢幕擷取畫面, 字型 的圖片

    自動產生的描述](data:image/png;base64...)Refer to my program:

The input collected by tk.Entry is stored as player_name or password, and then the program check whether they are empty or not. If they are empty, a messagebox will display “Player information is missing”.

  • Refer to my output:

![一張含有 文字, 螢幕擷取畫面, 字型, 數字 的圖片

自動產生的描述](data:image/png;base64...) ![一張含有 文字, 螢幕擷取畫面, 字型, 數字 的圖片

自動產生的描述](data:image/png;base64...)

These function create_player_commit is used in login, password change, account create and account delete for checking.

For more testing result, please refer to 3.1

      1. Checking in registration system

Check whether the user information existed or not

  • Refer to my program:

![一張含有 文字, 螢幕擷取畫面, 字型 的圖片

自動產生的描述](data:image/png;base64...)

  • Refer to my output:

![一張含有 文字, 螢幕擷取畫面, 字型, 數字 的圖片

自動產生的描述](data:image/png;base64...)

Check whether the password is correct or not

  • Refer to my program:

![一張含有 文字, 螢幕擷取畫面, 字型 的圖片

自動產生的描述](data:image/png;base64...)

![一張含有 文字, 螢幕擷取畫面, 字型 的圖片

自動產生的描述](data:image/png;base64...)This function is input into both classes PlayerOneLohin and PlayerTwoLogin to check the password is match or not.

    1. Sorting and searching algorithms
      1. Sorting in ranking system

The sorting algorithm is used to organize players rankings based on their performance in the game. The criteria include: 1. Wins (in descending order); 2. Losses (in ascending order); 3. Ties (in ascending order).

  • Refer to my program:

Where sort is a built-in function with a custom lambda function

As a nature result, students with more wins and fewer lose will appear on top of the ranking list.

      1. Searching in the ranking system

Searching in the ranking system allows the program to linear search players statistics, such as wins, losses, and ties.

  • Refer to my program:

This concept is implemented in function inc_win_watch, inc_lose_watch and inc_tie_watch

Searching occurs after each match, linear search though the name existed in the ranking.csv

      1. Searching in the account system

Searching in the account system used a linear search to check players username and password

  • ![一張含有 文字, 螢幕擷取畫面, 字型 的圖片

    自動產生的描述](data:image/png;base64...)Refer to my program:

Line is split into name and passw, if both match, returns true

    1. Programing output
      1. Game board

After the player clicked on a empty block, the board will output a “X” or “O” to show the players move.

Refer to 2.3.3

After players move in PvCEnginee, computer will output its next step.

Please refer to 2.3.4 for the logic of computer step and input.

A string will print out win or Tie to announce the situation of the match.

  • Refer to my program:

![一張含有 文字, 螢幕擷取畫面, 字型, 軟體 的圖片

自動產生的描述](data:image/png;base64...) ![一張含有 文字, 螢幕擷取畫面, 軟體 的圖片

自動產生的描述](data:image/png;base64...)

A string “Player1 win” / “Player2 win!” / “Player win!”/ “Computer win!” will be shown in the middle of the canvus.

Eg: ![一張含有 圖形, 字型, 平面設計, 鮮豔 的圖片

自動產生的描述](data:image/png;base64...)

      1. Player Ranking

The RankingPage uses a csv file named ranking.csv to manage and display player ranking with csv.reader module.

Both information in the csv file and on the RankingPage will be updated after each match.

  • Refer to my program:

![一張含有 文字, 螢幕擷取畫面, 字型 的圖片

自動產生的描述](data:image/png;base64...)

![一張含有 文字, 字型, 螢幕擷取畫面, 數字 的圖片

自動產生的描述](data:image/png;base64...)

^use the function read_ranking

      1. Error message

Error messages are displayed for the Entry box problems.

No input in entry box A messagebox will pop out
Invalid usernames or password A messagebox will pop out
    1. Error handling
Invalid click on game board Program will ignore the click and no update on the game board
No csv file A new csv file named ranking.csv will be created

For invalid input, please refer to 2.9.3

    1. Reusability and portability
      1. Resuability

As my program is highly modular, it provides high reusability.

Classes like PvPEnginee and PvCEnginee are classes specify for tic tac toe game, it is less likely to be resuable.

But other than these game related classes, RankingPage/PlayerVsPlayerPage/PlayerVsComputerPage/SettingPage/

GameOverPage/PlayerOneLogin/PlayerTwoLogin

And functions like change_password/check_playername_and_password/delete_player/

create_player/read_ranking

are classes and functions that can be reused by small changes

      1. Portability
  • As the programming language is python, it can be cross-platforms like windows, macOS and Linux easily.
  • As the program only used libraries like Tkinter, random and time, and the file used is csv file. All of the above dont require external installations.
  • As tkinter is a basic GUI system that does not require heavy graphical processing.
  • The file used is CSV, which can be support by all operation systems
  1. Further modifications
    1. Test data

Test data is a specific input or datasets during testing,

Test Data Type Example Data Function used
Player move Player 1 clicks (0,0), (0,1), (0,2) to win PvPEngine.check_win_pvp()
Player move Player clicks (0,0), (1,1), (2,2) to win PvCEngine.check_win_pvc()
Computer move Player clickd (0,0), (0,1) blocks (0,2) PvCEngine.computer()
Account data Username: "TestPlayer" Password: "Test123" create_player()
Account delete Username: "TestPlayer" delete_player()
Ranking data "Anthony", Wins: 5, Losses: 2, Ties: 1. inc_win_match()
Ranking data Ranking: ["Anthony", 3, 1, 0] read_ranking()
Verify data Username: "Anthony" Password: "@@@3" check_playername_and_password()
Game State Data All grid cells filled but no winner PvPEngine.check_win_pvp()
    1. Test cases

Test cases is detailed sets of data to be tested to check the functionality.

Problem Expected result Exact result Pass/Fail
Player1 login empty username Corresponding message box pop out Pass
Player1 username or password not match Corresponding message box pop out 一張含有 文字, 螢幕擷取畫面, 字型, 標誌 的圖片 自動產生的描述 Pass
Login button on Player1 Login Page Go to Player2 Login Page Go to Player2 Login Page Pass
Back button on player1 Login Page Back to start page Back to start page Pass
Player2 login empty password Corresponding message box pop out Pass
Player2 username or password not match Corresponding message box pop out 一張含有 文字, 螢幕擷取畫面, 字型, 標誌 的圖片 自動產生的描述 Pass
Login button on Player1 Login Page Go to PvP Canvas Go to PvP Canvas Pass
Back button on player2 Login Page Back to start page Back to start page Pass
Player1 and player2 input are same Corresponding message box pop out Pass
PvP click on existed box Nothing happen Nothing happen Pass
PvP player1 win Corresponding string display Pass
PvP player2 win Corresponding string display Pass
PvP tie Corresponding string display Pass
PvP click on lines Nothing happen Nothing happen Pass
Ranking Page button on GameOver page Go to Ranking Page Go to Ranking Page Pass
Back button on GameOver page Back to start page Back to start page Pass
Back to start button on Ranking Page Back to start page Back to start page Pass
PvC
Player1 login empty username Corresponding message box pop out Pass
Player1 username or password not match Corresponding message box pop out 一張含有 文字, 螢幕擷取畫面, 字型, 標誌 的圖片 自動產生的描述 Pass
Login button on Player1 Login Page Go to PvC canvas Go to PvC canvas Pass
Back button on player1 Login Page Back to start page Back to start page Pass
Pvc click on existed box Nothing happen Nothing happen Pass
PvC computer win Win in this step Place X on a empty box where there is two linear O Pass
PvC computer block Block the player to win in next step Place X on a empty box where its linear box filled with O Pass
PvC computer random Random input if it cannot meet above criteria Random input Pass
PvC player1 win Corresponding string display Pass
PvC player2 win Corresponding string display Pass
PvC tie Corresponding string display Pass
PvC click on lines Nothing happen Nothing happen Pass
Ranking Page button on GameOver page Go to Ranking Page Go to Ranking Page Pass
Back button on GameOver page Back to start page Back to start page Pass
Back to start button on Ranking Page Back to start page Back to start page Pass
Press Change password button when entry box is empty Corresponding message box pop out Pass
Press Change Password button when incorrect user name Corresponding message box pop out Pass
Press Change Password button after input correct username and different password Change the password successfully and a message box pop out Pass
Press Change Password button after input correct username and original password Corresponding Message box pop out Failed, but the password did changed
Press Create player button when entry box is empty Corresponding message box pop out Pass
Press Create player button when both username and password already exist Corresponding message box pop out Pass
Press Delete player button when entry box is empty Corresponding message box pop out
Press Delete player button when username is wrong Corresponding message box pop out Pass
Press Delete player button when password is wrong Corresponding message box pop out Pass
Press Back button on Setting Page Back to start page Back to start page Pass

For extreme Data input in entry box in login or setting pages, refer to my code, information are saved in txt file in UTF-8, so almost all data input are accepted.

English Save to ax.txt Save to ac.txt successfully Pass
Symbols Save to ax.txt Save to ac.txt successfully Pass
English + symbols Save to ax.txt Save to ac.txt successfully Pass
Simple Chinese Save to ax.txt Save to ac.txt successfully Pass
Simple Chinese + English Save to ax.txt Save to ac.txt successfully Pass
Simple Chinese + Symbols Save to ax.txt Save to ac.txt successfully Pass
Traditional Chinese Save to ax.txt Save to ac.txt successfully Pass
Traditional Chinese + English Save to ax.txt Save to ac.txt successfully Pass
Traditional Chinese + Symbols Save to ax.txt Save to ac.txt successfully Pass
Space Save to ax.txt Save to ac.txt successfully Pass
Space + English Save to ax.txt Save to ac.txt successfully Pass
Space + Symbols Save to ax.txt Save to ac.txt successfully Pass
Space + Simple Chinese Save to ax.txt Save to ac.txt successfully Pass
Space + Traditional Chinese Save to ax.txt Save to ac.txt successfully Pass
    1. Unit testing
Function Input Expected Output Actual Output Pass/Fail
create_player player_name = 'TestPlayer', password = 'Test123' add 'TestPlayer:Test123' to ac.txt Exists in file Pass
delete_player player_name = 'TestPlayer' Delete 'TestPlayer:Test123' from ac.txt Exists in file Pass
read_ranking ranking.csv file Sort ranking list First player: Anthony Pass
inc_win_match player_name = 'Anthony' Update 'Anthony' wins in ranking.csv Updated wins to 8 Pass
    1. System testing
  • Gameplay:
Player Vs Player Player 1 win 徽章 (記號 1) 外框
Player 2 win 徽章 (記號 1) 外框
Tie 徽章 (記號 1) 外框
Player Vs Computer Player win 徽章 (記號 1) 外框
Computer win 徽章 (記號 1) 外框
Tie 徽章 (記號 1) 外框
  • Account records:
After creating various accounts 一張含有 文字, 螢幕擷取畫面, 字型 的圖片 自動產生的描述 _ Accept any input _ Output in csv file _ Can login again _ Change password * Delete player
  • Match records:
After playing various matches using the account created _ Record match results _ Output in csv file _ Shown in rank _ Sort in rank page
    1. Debugging process
      1. Syntax debug

As the ide I used for the programming is VS code, the app highlighted syntax errors automatically during programming.

Common errors: missing colons, missing close parentheses, etc

      1. Logic related bugs

Flow of my progress:

GUI tic tac toe

Registration system

At first, I made a cli tic tac toe using 2-D array as the game board and convert it to a gui with coordinates.

CLI tic tac toe

And then test the gui one whether it works or not.

There is no better way to test but trial and error, keep fixing the coordinate problems. After that, I added logic for the computers move base on random input.

![一張含有 文字, 螢幕擷取畫面, 鮮豔, 字型 的圖片

自動產生的描述](data:image/png;base64...)Originally, I made two separate game board first:

Display the game board separately. In the latest code, this program already merged some of the functions and arrange them into different classes.

      1. GUI related bugs
  • In order to test GUI flow, I print out string for testing the arrangement in pages
  • Refer to my program:

![一張含有 文字, 螢幕擷取畫面, 字型 的圖片

自動產生的描述](data:image/png;base64...)The string “This is page 1” is used for testing the arrangement of pages. It is still behind the game board canvas.

  • At first, after each match, the game board do not refresh after each match, the “X” and “O” still remaining on the canvas and even adding layers.

![一張含有 文字, 螢幕擷取畫面, 字型, 數字 的圖片

自動產生的描述](data:image/png;base64...)By adding reset,

the board will be clear after each match.

    1. User Acceptance test (survey)

*![一張含有 文字, 螢幕擷取畫面, 數字 的圖片

自動產生的描述](data:image/png;base64...)*

Survey results:

    1. Pros and cons of the program (by survey)
    2. Modifications (during programming)

3.6.1 modification of canvas

Modified with for loop Original draw with coordinates
一張含有 文字, 螢幕擷取畫面, 軟體 的圖片 自動產生的描述 一張含有 文字, 螢幕擷取畫面, 陳列 的圖片 自動產生的描述
一張含有 文字, 行, 螢幕擷取畫面, 圖表 的圖片 自動產生的描述 Colorful and smooth! 一張含有 螢幕擷取畫面, 文字, 行, 正方形 的圖片 自動產生的描述 Straight line

With the use of for loop, 4 lines is reduced to 3 lines, but for the overall program, it can reduce inputting similar code and reduce error in calculating the coordinates.

3.6.2 modification of check winning

Modified with for loop Original codes base on the logic

Modified one is more neat and tidy and can prevent the calculate error of array.

  1. Further modifications

Python, being a powerful programming language, there are serval further modifications for my program. Here are some of the directions.

    1. Numpy

Numpy (Numeric Python) is a library specifically supporting multi-dimension arrays and matrix, along with mathematical functions to operate on these arrays. It can perform complex operations on arrays with mineral code.

4.1.1 Numpy x Tic Tac Toe

  • Using Numpy to represent the Tic Tac Toe board as a 3x3 ndarray will allow easier manipulation of the board state

  • With numpy power array operation, which enables quickly check for winning conditions of (vertical, columns, diagonals) without using complex loops ![一張含有 文字, 螢幕擷取畫面, 字型 的圖片

    自動產生的描述](data:image/png;base64...)^(inefficient example of my program in check winning) ![一張含有 文字, 螢幕擷取畫面, 軟體, 字型 的圖片

    自動產生的描述](data:image/png;base64...)^(much more efficient with less lines but same results, however this is just a cli example. It is slightly challenging to integrate into my program)

  • Althought Tic tac toe doesnt require extensive sorting or searching, numpy can be used for managing moves and analyze the game state. For instance, the computer could sort all possible move base on the current stragegic state.

      1. Numpy x AI

NumPy enhances AI implementation in Tic Tac Toe by simplifying data handling and computations:

  • Game State Management:

The board is represented as a 3x3 NumPy array, making updates and checks straightforward.

  • Winning Condition Checks:

Win conditions (rows, columns, diagonals) are efficiently verified using array operations, reducing the reliance on nested loops.

  • AI Integration:

NumPy supports Q-learning and other algorithms by handling large datasets and performing complex computations with ease.

    1. AI implementation

Instead of random input being the step 3 consideration of the computers input, computer should think of some strategic advance positions like consider putting next step next to the occurring steps.

Thats the reason why ai implementation is important.

      1. Self-Learning

Using libraries like Gym, TensorFlow, or PyTorch, the AI can be trained to play Tic Tac Toe through self-learning by simulating games and learning from the outcomes. It develops strategies like blocking the opponent and prioritizing winning moves using reinforcement learning techniques.

      1. Q-learning (Reinforcement Learning)

Q-learning trains the AI by assigning rewards to specific actions based on game outcomes.

  • The board state is treated as input, and a Q-table stores the value of each move.
  • After some time, AI learns to make decisions that maximize its chance of winning while avoiding losing moves.
      1. Minimax Algorithm

The Minimax algorithm ensures the computer makes the best possible move by simulating all potential outcomes.

  • It evaluates moves by assigning scores (positive for a win, negative for a loss, and zero for a tie).

  • The AI chooses the move that maximizes its chances of winning or forces a tie when a win is impossible.

    4.4 User Experience Enhancements

  • Add sound effects and animations (eg: clicks for moves, applause for a win)

  • Provide hints

  • Add backward button which allows withdraw the moves

  • Make more games

  • Improve AI logic, import real AI

  1. Conclusion
    1. Summary of the program

This project successfully developed a GUI Tic Tac Toe game with Player vs Player (PvP) and Player vs Computer (PvC) modes using Python and Tkinter. It includes a user-friendly GUI, simple AI logic for the computer player and account management with a ranking system. The program is highly modular design, it is efficient to file handling and has clear event management to ensure smooth gameplay and data tracking.

    1. Learning outcomes

Working on this SBA project has been a rewarding experience that significantly enhanced my programming and problem-solving skills. Through the project, I am able to handle various python concepts like class and __init__ methords, tkinter, file handling, event handling and more.

In addition to technical skills, this project improved my logical thinking and ability to break down a problem into smaller, manageable tasks. The process of designing the program, implementing features, debugging errors, and testing edge cases taught me to approach challenges systematically.

Overall, the project not only resulted in a functional and enjoyable Tic Tac Toe game but also allowed me to grow as a programmer. Thank you!