0% found this document useful (0 votes)
63 views47 pages

Documentation Sample

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
63 views47 pages

Documentation Sample

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 47

Real Time Research Project Report(CS456PC)

on

TYPING SPEED CALCULATOR IN PYTHON


Submitted
in partial fulfillment of the requirements for the
award of the degree of

Bachelor of Technology
in
Computer Science and Engineering(Data Science)
by
M.Shashank Reddy(22261A6737)
S.Manideep(22261A6756)
T.Anirudh(22261A6757)

Under the guidance of


Mr.B.Yadaiah (Assistant Professor)
Ms.B.Varalaxmi (Assistant Professor)

Department of Emerging Technologies


Mahatma Gandhi Institute of Technology(Autonomous)
(Affiliated to Jawaharlal Nehru Technological University Hyderabad)
Kokapet(V), Gandipet(M), Hyderabad,Telangana - 500 075.
2023-2024
MAHATMA GANDHI INSTITUTE OF TECHNOLOGY(AUTONOMOUS)
(Affiliated to Jawaharlal Nehru Technological University Hyderabad)
GANDIPET, HYDERABAD – 500075, Telangana

CERTIFICATE

This is to certify that the project entitled ― “TYPING SPEED CALCULATOR IN PYTHON”
is being submitted by M.SHASHANKREDDY,S.MANIDEEP,T.ANIRUDH bearing
RollNo.22261A6737,22261A6756,22261A6757 Respectively in partial fulfillment of the requirements
for the Real Time Project in COMPUTER SCIENCE AND ENGINEERING(Data Science) is a record of
bonafide work carried out by them.

The results of the investigations enclosed in this report have been verified and found satisfactory.

PROJECT GUIDE HEAD OF THE DEPARTMENT

Mr.B.Yadaiah Dr.M.Rama Bai


(Assistant Professor) (Professor and HoD Department of ET)
Ms.B.Varalaxmi
(Assistant Professor)

External Examiner
DECLARATION

This is to certify that the work reported in this project titled -“Typing Speed
Calculator in Python ” is a record of work done by me in the Department of
Computer Science and Engineering(Data Science), Mahatma Gandhi Institute of
Technology, Hyderabad.

No part of the work is copied from books/journals/internet and wherever the


portion is taken, the same has been duly referred in the text. The report is based on the
work done entirely by team and not copied from any other source.

M.Shashank Reddy(22261A6737)

S.Manideep(22261A6756)

T.Anirudh(22261A6757)
ACKNOWLEDGEMENTS

I would like to express my sincere thanks to Dr.G.Chandra Mohan Reddy,Principal MGIT, for
providing the working facilities in college.

I wish to express my sincere thanks and gratitude to Dr. M.Rama Bai , Professor and HoD, Department
of ET, MGIT, for all the timely support and valuable suggestions during the period of project.

I am extremely thankful to, Ms. D. Deepika, Mr. Mallela Srikanth, and Mr. K. Vikas , Assistant
Professors Department of ET, MGIT, major project coordinators for their encouragement and support
throughout the project.

I am extremely thankful and indebted to my internal guide Mr.B.Yadaiah,Assistant Professor, Ms. B.


Varalaxmi,Assistant Professor Department of ET, for her constant guidance, encouragement and moral
support throughout the project.

Finally, I would also like to thank all the faculty and staff of ET Department who helped me directly or
indirectly, for completing this project.

M.Shashank Reddy(22261A6737)
S.Manideep(22261A6756)
T.Anirudh(22261A6757)
TABLE OF CONTENTS

Certificate ii

Declaration iii

Acknowledgement iv

List of Figures vii

Abstract vii

1.Introduction

1.1 Motivation 1

1.2 Problem Definition 2

1.3 Existing System 2

1.4 Proposed System 3

1.5 Requirements Specification

1.5.1 Software Requirements 4

1.5.2 Hardware Requirements 4

1.5.3 Features of python 6

1.5.4 Installation of Pygame 12

2.Literature Survey 15

3.Typing Speed Calculator Methodology 16

3.1 Logistic Regression 23

3.2 UML Diagrams 28


4.Testing and Results 29

4.1 Model Performances 33

4.2 Comparison of Models 35

5.Conclusion and Future Work

5.1 Conclusion 36

5.2 Future Work 36

Bibliography 37

Appendix 38
LIST OF FIGURES

Figure 1.1 Anaconda Navigator window on Windows 10 8

Figure 1.2 Jupyter Notebook Interface 10

Figure1.3. Flowchart 28

Figure1.4 Applications 28

Figure 1.5 Interface 30

Figure 1.6 Sentences Used 31

Figure 1.7 Folders Required 31

Figure 1.8 Outputs-1 32

Figure 1.9 Outputs-2 32


ABSTRACT
In today's digital age, proficient typing skills are essential for efficient communication and productivity.
The Typing Speed Calculator project in Python aims to provide a practical tool for users to assess and
improve their typing speed and accuracy.The project involves developing a Python program that prompts
users to type a provided passage of text. The program measures the time taken for the user to complete
typing and calculates the typing speed in words per minute (WPM). Accuracy is also evaluated by
comparing the typed text with the original passage, highlighting any errors made.

Key functionalities include:

1. User Interaction: The program interacts with users by displaying a passage and recording
their typed input.
2. Timing and Calculation: Using Python's time module, the program captures the start and
end times of typing to calculate WPM.
3. Error Detection: String comparison techniques are employed to identify and count errors
between the typed and original text.
4. Feedback: The program provides immediate feedback on typing speed and accuracy,
encouraging users to track their progress over time.

Through this project, users not only gain insights into their current typing abilities but also receive
practical feedback on areas needing improvement. Additionally, developing the Typing Speed
Calculator enhances programming skills in Python, reinforcing concepts such as string manipulation,
conditional statements, and basic algorithmic calculations.

Ultimately, the Typing Speed Calculator project in Python aims to empower users to enhance their
typing proficiency efficiently and effectively, contributing to improved productivity and communication
skills in various domains.
1. INTRODUCTION

Welcome to our Typing Speed Calculator project in Python! This project aims to help
users improve their typing skills by providing a tool to measure both speed and accuracy. Typing
speed is a crucial skill in today's digital age, whether for students, professionals, or anyone who
wants to enhance their productivity.
In this project, we've developed a user-friendly program that allows you to input a passage of
text, then measures how quickly you can type it and how accurately you reproduce it. The program
will calculate your typing speed in words per minute (WPM) and provide feedback on your
accuracy based on the number of mistakes made.
Throughout this project, we'll explore fundamental concepts such as string manipulation, user
input handling, timing, and basic calculations in Python. By the end, you'll not only have a
functioning typing speed calculator but also a deeper understanding of how to implement such
interactive programs in Python.
1.1. Motivation

Improving typing speed and accuracy is more relevant today than ever before. Whether
you're a student striving to efficiently take notes during lectures, a professional aiming to increase
productivity at work, or simply someone who wants to communicate faster online, mastering
typing skills can significantly enhance your daily activities.

By developing a Typing Speed Calculator in Python, we aim to provide a practical tool that
not only measures your current typing proficiency but also encourages continuous improvement.
This project not only helps users gauge their typing speed in words per minute (WPM) but also
emphasizes the importance of accuracy, ensuring that speed doesn't compromise quality.

Moreover, creating this project in Python offers a valuable opportunity to delve into essential
programming concepts such as string manipulation, user input handling, and basic algorithmic
calculations. Through hands-on practice with Python, users can enhance their coding skills while
simultaneously enhancing their typing abilities.

Ultimately, our Typing Speed Calculator aims to empower users of all backgrounds to enhance
their typing proficiency effectively, making daily tasks smoother and more efficient.

1.2 Problem Definition

Develop a Python application that measures a user's typing speed in words per minute (WPM)
and provides feedback on accuracy and performance. The application should be user-friendly,
accurate, and efficient.

1
Key Features

1. Text Display: Show a passage of text for the user to type.


2. User Input: Capture the user's typed text in real-time.
3. Timer: Track the time taken by the user to type the passage.
4. Speed Calculation: Calculate the typing speed in WPM.
5. Accuracy Calculation: Calculate the accuracy percentage based on the number of correct
characters typed.
6. Feedback: Display the typing speed and accuracy to the user.
7. User Interface: Provide a simple graphical user interface (GUI) or command-line
interface (CLI) for user interaction.

1.3 Existing System

It is already existed in python language in Tkinter.Creating a typing speed calculator using


Tkinter involves creating a simple GUI where a user can type a provided text. The application
will measure the time taken by the user to type the text and calculate the typing speed in words
per minute (WPM). Here’s how you can implement this:

Create a Typing Speed Calculator:

1. Display a sample text for the user to type.


2. Capture the start time when the user begins typing.
3. Capture the end time when the user finishes typing.
4. Calculate the time taken and the typing speed in WPM.
5. Display the results to the user.

1.4 Proposed System

Pygame is a popular Python library designed for creating video games and multimedia
applications. It provides functionalities for handling graphics, sound, input devices (such as
keyboards and mice), and other essential aspects needed for game development and interactive
applications. Here's an overview of Pygame and its key features:

Key Features of Pygame:

1. Graphics: Pygame allows you to create and manipulate graphical elements easily. It
provides functions for drawing shapes, images, and text on the screen, making it suitable
for developing both 2D and simple 3D games.

2
2. Sound: You can load and play sounds in various formats (like WAV and MP3) using
Pygame. This feature is essential for adding audio effects, music, and feedback to your
applications.
3. Input Handling: Pygame simplifies capturing user input from keyboards, mice, and
joysticks. It provides functions to detect key presses, mouse movements, and button
clicks, enabling interactive user experiences.
4. Event Handling: Events in Pygame allow you to respond to user actions and system
events. Common events include window resizing, quitting the application, and timer
events for animation or game loops.
5. Collision Detection: For game development, Pygame offers utilities for collision
detection between game objects. This is crucial for implementing gameplay mechanics
like object interaction, obstacle avoidance, and scoring.
6. Animation and Sprites: Pygame supports animation by updating the display at regular
intervals. It also includes features for handling sprites (animated characters or objects) and
managing their movement, states, and interactions.
7. Cross-Platform: Pygame is cross-platform and runs on various operating systems,
including Windows, macOS, and Linux. This allows developers to write games and
applications that work across different platforms without significant modifications.
8. Community and Documentation: Pygame has an active community of developers who
contribute libraries, tutorials, and resources. The official Pygame website provides
comprehensive documentation, examples, and forums for support and collaboration.

1.5 Requirements Specification


1.5.1 Software Requirements
Language : Python 3.6
Operating system : Windows / Linux / macOS
Tools:
● Anaconda Navigator
● Jupyter Notebook
● Pandas
● Matplotlib
● Pygame
● Pip
1.5.2 Hardware Requirements
● RAM – 4GB minimum

3
1.5.1.1 Python
Python is a high-level, interpreted, interactive and object-oriented scripting language created by
Guido Rossum in 1989. Python is designed to be highly readable. Its language constructs and
object-oriented approach aim to help programmers write clear, logical code for small and
largescale projects. It is ideally designed for rapid prototyping of complex applications.

It has interfaces to many OS system calls and libraries and is extensible to C or C++. Python is
dynamically typed and garbage-collected. It supports multiple programming paradigms, including
procedural, object-oriented, and functional programming. Python programming is widely used in
Artificial Intelligence, Natural Language Generation, Neural Networks and other advanced fields
of Computer Science.

History of Python
Python was conceived in the late 1980s by Guido van Rossum at Centrum Wiskunde & Informatica
(CWI) in the Netherlands as a successor to the ABC language, capable of exception handling and
interfacing with the Amoeba operating system. Language developer Guido van Rossum
shouldered sole responsibility for the project until July 2018 but now shares his leadership as a
member of a five-person steering council.

Python 2.0 was released on 16 October 2000 with many major new features, including a
cycledetecting garbage collector and support for Unicode.

Python 3.0 was released on 3 December 2008. It was a major revision of the language that is not
completely backward-compatible. Many of its major features were backported to Python 2.6.x and
2.7.x version series. Releases of Python 3 include the 2 to 3 utility, which automates (at least
partially) the translation of Python 2 code to Python 3.

Features of Python
Python's features include:
• Easy-to-learn: Python has few keywords, simple structure, and a clearly defined syntax.
4
This allows the student to pick up the language quickly.
• Easy-to-read: Python code is more clearly defined and visible to the eyes.
• Easy-to-maintain: Python's source code is fairly easy-to-maintain.
• A broad standard library: Python's bulk of the library is very portable and crossplatform
compatible on UNIX, Windows, and Macintosh.
• Interactive Mode: Python has support for an interactive mode which allows interactive
testing and debugging of snippets of code.
• Portable: Python can run on a wide variety of hardware platforms and has the same
interface on all platforms.
• Extendable: You can add low-level modules to the Python interpreter. These modules
enable programmers to add to or customize their tools to be more efficient.
• Databases: Python provides interfaces to all major commercial databases.
• GUI Programming: Python supports GUI applications that can be created and ported to
many system calls, libraries, and windows systems, such as Windows MFC, Macintosh,
and the X Window system of Unix.
• Scalable: Python provides a better structure and support for large programs than shell
scripting.

Apart from the above-mentioned features, Python has a big list of good features, few are listed
below:
• IT supports functional and structured programming methods as well as OOP.
• It can be used as a scripting language or can be compiled to byte-code for building large
applications.
• It provides very high-level dynamic data types and supports dynamic type checking.
• IT supports automatic garbage collection.
• It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.

Python Modules NumPy


NumPy is a general-purpose array-processing package. It provides a high-performance
multidimensional array object, and tools for working with these arrays.
5
It is the fundamental package for scientific computing with Python. It contains various features
including these important ones:
● A powerful N-dimensional array object
● Sophisticated (broadcasting) functions
● Tools for integrating C/C++ and Fortran code
● Useful linear algebra, Fourier transform, and random number capabilities

Besides its obvious scientific uses, NumPy can also be used as an efficient multi-dimensional
container of generic data. Arbitrary data-types can be defined using Numpy which allows NumPy
to seamlessly and speedily integrate with a wide variety of databases.

Pandas
Pandas is a Python package providing fast, flexible, and expressive data structures designed to
make working with structured (tabular, multidimensional, potentially heterogeneous) and time
series data both easy and intuitive. It aims to be the fundamental high-level building block for
doing practical, real world data analysis in Python. Additionally, it has the broader goal of
becoming the most powerful and flexible open source data analysis / manipulation tool available
in any language.

Pandas is well suited for many different kinds of data:


● Tabular data with heterogeneously-typed columns, as in an SQL table or Excel spreadsheet
● Ordered and unordered (not necessarily fixed-frequency) time series data.
● Arbitrary matrix data (homogeneously typed or heterogeneous) with row and column
labels
● Any other form of observational / statistical data sets. The data actually need not be labeled
at all to be placed into a pandas data structure.

The two primary data structures of pandas, Series (1-dimensional) and DataFrame (2dimensional),
handle the vast majority of typical use cases in finance, statistics, social science, and many areas
of engineering. For R users, DataFrame provides everything that R’s data.frame provides and

6
much more. pandas is built on top of NumPy and is intended to integrate well within a scientific
computing environment with many other 3rd party libraries.

Matplotlib
Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a
multi-platform data visualization library built on NumPy arrays and designed to work with the
broader SciPy stack. It was introduced by John Hunter in the year 2002.

One of the greatest benefits of visualization is that it allows us visual access to huge amounts of
data in easily digestible visuals. Matplotlib consists of several plots like line, bar, scatter, histogram
etc. For simple plotting the pyplot module provides a MATLAB-like interface, particularly when
combined with IPython. For the power user, you have full control of line styles, font properties,
axes properties, etc, via an object oriented interface or via a set of functions familiar to MATLAB
users.

Plotly
Plotly is an interactive, open-source, and browser-based graphing library for Python. Built on top
of plotly.js, plotly.py is a high-level, declarative charting library. plotly.js ships with over 30 chart
types, including scientific charts, 3D graphs, statistical charts, SVG maps, financial charts, and
more.

Plotly has got some amazing features that make it better than other graphing libraries:
● It is interactive by default
● Charts are not saved as images but serialized as JSON, making them open to be read with
R, MATLAB, Julia and others easily
● Exports vector for print/publication
● Easy to manipulate/embed on web
1.5.1.2 Anaconda Navigator

Anaconda Navigator is a desktop graphical user interface (GUI) included in Anaconda®


distribution that allows you to launch applications and easily manage conda packages,
environments, and channels without using command-line commands. Navigator can search for
7
packages on Anaconda Cloud or in a local Anaconda Repository. It is available for Windows,
macOS, and Linux.

Figure 1.1 Anaconda Navigator window on Windows operating system

Usage of Navigator
In order to run, many scientific packages depend on specific versions of other packages. Data
scientists often use multiple versions of many packages and use multiple environments to separate
these different versions.

The command-line program conda is both a package manager and an environment manager. This
helps data scientists ensure that each version of each package has all the dependencies it requires
and works correctly.

Navigator is an easy, point-and-click way to work with packages and environments without
needing to type conda commands in a terminal window. You can use it to find the packages you
want, install them in an environment, run the packages, and update them – all inside Navigator.

The following applications are available by default in Navigator:


8
● JupyterLab
● Jupyter Notebook
● Spyder
● VSCode
● Glueviz
● Orange 3 App
● RStudio

Advanced conda users can also build their own Navigator applications.

Executing the code with Navigator


The simplest way is with Spyder. From the Navigator Home tab, click Spyder, and write and
execute your code. You can also use Jupyter Notebooks the same way. Jupyter Notebooks are
increasingly popular systems that combine your code, descriptive text, output, images, and
interactive interfaces into a single notebook file that is edited, viewed, and used in a web browser.

1.5.1.3 The Jupyter Notebook


The Jupyter Notebook is an open-source web application that allows you to create and share
documents that contain live code, equations, visualizations and narrative text. Uses include: data
cleaning and transformation, numerical simulation, statistical modeling, data visualization,
machine learning, and much more.

The Jupyter notebook combines two components:


A web application: A browser-based tool for interactive authoring of documents which combine
explanatory text, mathematics, computations and their rich media output.

Notebook documents: A representation of all content visible in the web application, including
inputs and outputs of the computations, explanatory text, mathematics, images, and rich media
representations of objects.

9
Main features of the web application

● In-browser editing for code, with automatic syntax highlighting, indentation, and tab
completion/introspection.

● The ability to execute code from the browser, with the results of computations attached to
the code which generated them.

● Displaying the result of computation using rich media representations, such as HTML,
LaTeX, PNG, SVG, etc. For example, publication-quality figures rendered by the
matplotlib library, can be included inline.

● In-browser editing for rich text using the Markdown markup language, which can provide
commentary for the code, is not limited to plain text.

● The ability to easily include mathematical notation within markdown cells using LaTeX,
and rendered natively by MathJax.

Figure 1.2 Jupyter Notebook Interface

Notebook name: The name displayed at the top of the page, next to the Jupyter logo, reflects the
name of the .ipynb file. Clicking on the notebook name brings up a dialog which allows you to
rename it. Thus, renaming a notebook from ―Untitled0ǁ to ―My first notebookǁ in the browser,
renames the Untitled0.ipynb file to My first notebook.ipynb.
10
Menu bar: The menu bar presents different options that may be used to manipulate the way the
notebook functions.
Toolbar: The tool bar gives a quick way of performing the most-used operations within the
notebook, by clicking on an icon.
Code cell: The default type of cell; read on for an explanation of cells.

Installation of pygame..

To install Pygame, you need to have Python and pip (Python's package installer) installed on your
system. Follow these steps:

Step 1: Install Python and pip

If you don't already have Python and pip installed, download and install Python from python.org.
Make sure to check the option to add Python to your system PATH during the installation.

Step 2: Install Pygame using pip

Open a terminal (command prompt on Windows, terminal on macOS/Linux) and run the
following command:

pip install pygame

This will download and install the latest version of Pygame from the Python Package Index
(PyPI).

Step 3: Verify the Installation

To verify that Pygame is installed correctly, you can run a simple Pygame program. Open a
Python interactive shell by typing python in your terminal and run the following code:

python
Copy code
import pygame
pygame.init()
print("Pygame version:", pygame.version.ver)

If Pygame is installed correctly, it will print the version of Pygame you have installed.

11
Step 4: Troubleshooting

If you encounter any issues during the installation, here are some common troubleshooting steps:

1. Upgrade pip: Make sure you have the latest version of pip by running:

bash
Copy code
pip install --upgrade pip

2. Check Python and pip installation: Ensure that Python and pip are installed correctly
and are accessible from your command line. You can check their versions by running:

bash
Copy code
python --version
pip --version

3. Install Pygame in a virtual environment: If you are facing issues with global
installations, consider creating a virtual environment and installing Pygame within it:

bash
Copy code
python -m venv myenv
source myenv/bin/activate # On Windows, use
`myenv\Scripts\activate`
pip install pygame

Example Pygame Program

Here is a simple example to test your Pygame installation:

python
Copy code
import pygame
import sys

# Initialize Pygame
pygame.init()

# Set up the display


width, height = 800, 600
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption('Pygame Installation Test')

12
# Main loop
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False

screen.fill((255, 255, 255))


pygame.display.flip()

# Quit Pygame
pygame.quit()
sys.exit()

Save this code in a file named test_pygame.py and run it using the following command:

bash
Copy code
python test_pygame.py

You should see a window with a white background, which indicates that Pygame is installed and
working correctly. Close the window to exit the program.

13
2. LITERATURE SURVEY
Literature Survey on Typing Speed
Calculator in Python Using Pygame
1. Introduction

Typing speed calculators are applications designed to measure the speed and accuracy of a user's
typing. They have become popular tools for improving typing skills, conducting speed tests, and
enhancing overall typing efficiency. Python, with its simplicity and robust libraries, is often used to
develop such applications. Pygame, a set of Python modules designed for writing video games, is
particularly well-suited for creating interactive and graphical applications like a typing speed
calculator.

2. Background and Related Work

Typing Speed Measurement: Typing speed is typically measured in words per minute (WPM),
where a word is standardized to five characters, including spaces and punctuation. Accuracy is often
measured alongside speed, indicating the percentage of correctly typed characters or words.

Pygame: Pygame is a cross-platform set of Python modules designed for writing video games. It
includes computer graphics and sound libraries, making it suitable for creating interactive applications
with graphical interfaces. Pygame is used widely in educational environments to teach programming
and game development.

3. Existing Typing Speed Calculators

Key Features: Existing typing speed calculators often include features such as:

• Real-time display of typing speed and accuracy.


• Highlighting of errors and corrections.
• Various difficulty levels or typing modes.
• Progress tracking and statistics.

Examples:

1. TypingTest.com: A popular web-based typing test that provides real-time feedback on typing
speed and accuracy.
2. 10FastFingers: Another web-based typing speed test known for its competitive environment,
where users can compare their scores with others globally.
3. TypeRacer: An online multiplayer typing game where users race against each other by typing
quotes from books, movies, and songs.

These applications are primarily web-based, utilizing JavaScript and other web technologies to
provide a responsive and interactive user experience.

14
4. Typing Speed Calculators in Python Using Pygame

Advantages of Using Pygame:

• Cross-Platform Compatibility: Pygame applications can run on multiple platforms,


including Windows, macOS, and Linux.
• Interactive Graphics: Pygame's robust graphical capabilities enable the creation of visually
appealing and interactive interfaces.
• Ease of Learning: Python's simplicity and readability, combined with Pygame's
straightforward API, make it accessible for beginners and educational purposes.

Key Components:

1. User Interface (UI):


o Text Display: Display the text that the user needs to type.
o Input Handling: Capture and display user input in real-time.
o Feedback Mechanism: Provide real-time feedback on typing speed, errors, and
accuracy.
2. Performance Measurement:
o Typing Speed Calculation: Calculate words per minute (WPM) based on the number
of correctly typed words and elapsed time.
o Error Detection: Identify and highlight errors in the typed text.
3. Data Persistence:
o Session Data: Store and retrieve typing session data for progress tracking.
o User Profiles: Support multiple user profiles to track individual performance over
time.

15
Typing Speed Calculator in Python Using Pygame..

Introduction.

Typing speed is a crucial skill in the modern digital age, where efficient and accurate typing can
significantly enhance productivity and communication. As the demand for proficient typing increases
across various professions and educational environments, tools that help individuals measure and
improve their typing skills have become invaluable. One such tool is the typing speed calculator,
which not only measures typing speed but also provides feedback on accuracy and error patterns.

Python, renowned for its simplicity and versatility, is an ideal programming language for developing
such applications. Its extensive libraries and supportive community make it accessible to both novice
and experienced developers. Pygame, a set of Python modules specifically designed for writing video
games, offers robust capabilities for creating interactive and visually appealing graphical user
interfaces. This makes Pygame an excellent choice for developing a typing speed calculator.

The project "Typing Speed Calculator in Python Using Pygame" aims to combine the power of
Python and Pygame to create an engaging and effective tool for measuring and improving typing
speed. This application will provide real-time feedback on typing performance, helping users to
identify their strengths and areas for improvement. Additionally, the project will incorporate data
persistence to track progress over time, offering a comprehensive solution for users to enhance their
typing skills.

In this project, we will explore the development process of a typing speed calculator, covering the
essential components such as user interface design, performance measurement, and data storage. We
will leverage Pygame's graphical capabilities to create an intuitive and interactive user experience,
ensuring that the application is both functional and enjoyable to use. Through this project, we aim to
deliver a valuable tool that can assist individuals in becoming more proficient typists, ultimately
contributing to their overall productivity and efficiency.

Understanding a problem and a final goal


It’s important to understand what insights one needs to get from the analysis. In short, you must
decide what question to ask and consequently what type of machine learning problem to solve:
classification or regression.

16
● Classification

In the context of a typing speed calculator in Python, classification typically refers to categorizing
typing speeds into different levels or classes based on certain criteria. This can be achieved using
machine learning techniques, such as logistic regression, to predict and classify typing speeds into
categories like "slow," "average," or "fast" based on input data.

Here's how classification can be applied to a typing speed calculator using Python:

Classification Approach

1. Data Collection: Gather typing speed data from users. This can include metrics such as
session duration, number of characters typed, errors made, etc.
2. Data Preprocessing: Prepare the collected data for classification. This involves cleaning the
data, handling missing values, and transforming it into a suitable format for the classifier.
3. Feature Selection: Choose relevant features that can help predict typing speed categories.
This might include session duration, error rate, typing speed over time, etc.
4. Model Training: Train a classification model using supervised learning techniques. Common
models for classification include logistic regression, decision trees, random forests, or neural
networks.
5. Model Evaluation: Evaluate the trained model using performance metrics such as accuracy,
precision, recall, and F1-score. This step ensures that the model can accurately classify typing
speeds into the desired categories.
6. Integration with Typing Speed Calculator: Implement the trained classification model into
the typing speed calculator application. As users type, the application can use the model to
classify their typing speed into predefined categories (e.g., slow, average, fast).

Integration in Typing Speed Calculator

Integrating this classification model into a typing speed calculator involves using the model to predict
and display the user's typing speed category based on their typing session characteristics (e.g., session
duration, error rate). This enhances the calculator's functionality by providing users with personalized
feedback and insights into their typing proficiency.

By applying classification techniques like logistic regression in Python, you can enhance the typing
speed calculator to not only measure typing speed but also classify and provide actionable insights for
users to improve their typing skills effectively.

● Regression

Regression in the context of a typing speed calculator involves predicting the typing speed of a user
based on various input features. Unlike classification, which categorizes typing speeds into classes

17
(e.g., slow, average, fast), regression predicts a continuous value representing the typing speed,
usually measured in words per minute (WPM).

Here’s how regression can be applied to a typing speed calculator using Python:

Regression Approach

1. Data Collection: Gather typing session data from users, including metrics such as session
duration, number of characters typed, errors made, etc.
2. Data Preprocessing: Clean and preprocess the collected data. Handle missing values,
normalize or scale features if necessary, and split the data into training and test sets.
3. Feature Selection: Choose relevant features that can help predict typing speed accurately.
This might include session duration, error rate, typing speed over time, etc.
4. Model Selection: Choose a regression model suitable for predicting typing speed. Common
regression models include linear regression, polynomial regression, support vector regression
(SVR), or neural networks.
5. Model Training: Train the selected regression model using the training data. Adjust model
parameters and hyperparameters to optimize performance.
6. Model Evaluation: Evaluate the trained model using appropriate regression metrics such as
mean squared error (MSE), root mean squared error (RMSE), R-squared score (R²), etc. This
step ensures that the model can accurately predict typing speeds based on input features.
7. Integration with Typing Speed Calculator: Implement the trained regression model into the
typing speed calculator application. As users type, the application can use the model to predict
their typing speed in real-time or after completing a typing session.

Attributes used for preparation..


1. Text Display Attributes

• Target Text: The text that users are required to type. This can vary in length and complexity.
• Text Formatting: Font size, color, and style for displaying the target text and user input.
• Text Positioning: Coordinates to position the text on the Pygame window.

2. User Interface Attributes

• Input Handling: Capture user keyboard input and update the display accordingly.
• Feedback Display: Real-time display of typing speed (in WPM) and accuracy metrics.
• Visual Cues: Highlighting errors or correctness in user input (e.g., color changes for correct
and incorrect characters).

3. Timing and Performance Attributes

• Timing Mechanism: Track session duration to calculate typing speed accurately.


• Performance Metrics: Compute metrics like words per minute (WPM), characters per minute
(CPM), error rate (percentage of mistakes), accuracy rate (percentage of correct entries), etc.
• Real-time Updates: Update performance metrics dynamically as the user types.

18
4. User Interaction Attributes

• Keyboard Events: Handle keyboard events (key press, key release) to capture user input.
• Feedback Mechanism: Provide immediate feedback on typing speed and accuracy as the user
types.
• Session Management: Start, pause, resume, and end typing sessions.

5. Data Persistence Attributes

• Session Data Storage: Store session data such as typing speed, accuracy, session duration, and
timestamps for progress tracking and analysis.
• User Profiles: Allow multiple users to maintain their typing records and track improvement
over time.

6. Optional Machine Learning Attributes


(if integrated)

• Predictive Models: Use machine learning models to predict typing speed categories (e.g.,
slow, average, fast) based on historical data.
• Model Integration: Interface with trained models to provide personalized feedback and
recommendations for improving typing skills.

Data preparation and preprocessing


Historical data that was selected for solving the problem must be transformed into a format suitable
for machine learning. Since model performance and therefore the quality of received insights
depend on the quality of data, the primary aim is to make sure all data points are presented using
the same logic, and the overall dataset is free of inconsistencies.

Feature engineering, extraction, and selection


Feature engineering is a very important part of dataset preparation. During the process, a set of
attributes (input features) are created that represent various behavior patterns related to customer
engagement level with a service or product. In a broad sense, features are measurable characteristics
of observations that an ML model takes into account to predict outcomes (in this case the decision
related to churn probability.)

19
Modeling and Testing

Modeling and testing a typing speed calculator in Python using Pygame involves several steps,
including designing the user interface, implementing the typing logic, integrating machine learning
models for prediction or classification, and testing the application's functionality. Below, I'll outline a
structured approach to model and test a typing speed calculator using Python and Pygame.

1.Setting Up the Environment

First, ensure you have Python and Pygame installed. If not, follow the installation steps provided
earlier in this conversation.

2. Designing the Typing Speed Calculator


Interface

The user interface of the typing speed calculator in Pygame should include components for displaying
text, capturing user input, and providing feedback on typing speed and accuracy. Here's a basic outline
of how you might structure your Pygame application:

• Display Area: Show the text to be typed and user input.


• Feedback Area: Display real-time feedback on typing speed (WPM) and accuracy.
• Input Handling: Capture user keyboard input and update the display accordingly.

3. Integrating Machine Learning Models


(Optional)

If you want to enhance your typing speed calculator with predictive capabilities, you can integrate
machine learning models. For example, you could use a classification model to categorize typing
speeds into different levels (slow, average, fast) based on session data like duration and accuracy.
Here's a high-level overview of how you might integrate such a model:

• Train a classification model (e.g., logistic regression, decision tree) using historical typing
session data.
• Use the trained model to predict typing speed categories based on current session data (e.g.,
session duration, error rate).
• Display the predicted typing speed category to the user as feedback.

4. Testing the Application

Testing the typing speed calculator involves both functional testing (ensuring the application performs
as expected) and performance testing (evaluating typing speed accuracy and responsiveness). Here are
some key aspects to test:

• User Interface: Verify that all UI components display correctly and respond to user input.

20
• Typing Logic: Test the accuracy of typing speed calculations under different scenarios (e.g.,
varying text lengths, user typing speeds).
• Integration with Models: Validate the accuracy of predictions made by integrated machine
learning models (if applicable).
• Performance: Measure the responsiveness and smoothness of the application during typing
sessions, ensuring it handles real-time input effectively.

3.1 Logistic Regression

To create a typing speed calculator using logistic regression in Python with Pygame, we will follow
these steps:

1. Collect and preprocess data: Collect typing speed data over multiple sessions and preprocess
it.
2. Train a logistic regression model: Train the model on the collected data.
3. Integrate the model into the Pygame application: Use the model to predict typing speed
during a Pygame session.

Step 1: Collect and Preprocess Data

First, we need to collect typing speed data. We'll simulate this step with some generated data for
demonstration purposes.

Step 2: Integrate the Model into the


Pygame Application

Next, we integrate the trained logistic regression model into a Pygame application. The application
will collect typing data in real-time and use the model to predict whether the typing speed is above a
certain threshold.

typing_speed_calculator.py
Explanation

1. Data Collection and Preprocessing:


o Simulate or replace with real data collection.
o Preprocess the data using StandardScaler.
2. Model Training:
o Train a logistic regression model on the preprocessed data.
o Save the model to a file (logistic_model.pkl) for later use.
3. Pygame Integration:
o Initialize Pygame and set up the display.

21
o Load the logistic regression model and scaler.
o Implement a typing speed calculator in Pygame that collects user input and calculates
typing speed.
o Use the logistic regression model to predict if the typing speed exceeds a threshold
(e.g., 60 WPM) based on the number of practice sessions.

Logistic Function

A logistic function is a common sigmoid function that can be used for modeling growth and can be
adapted for various applications, including typing speed calculation. In this context, we can assume
that typing speed improves over time with practice, but eventually plateaus at a certain point.

The general form of the logistic function is:

f(t)=L1+e−k(t−t0)f(t)=1+e−k(t−t0)L

where:

• LL is the maximum value (the plateau).


• kk is the logistic growth rate.
• tt is the time or the number of practice sessions.
• t0t0 is the time at which the speed is at the midpoint of its maximum value.

Deployment and monitoring

To deploy a typing speed calculator using a logistic function in Python, you can create a web
application. One popular framework for building web applications in Python is Flask. Here's a step-
by-step guide to deploying your typing speed calculator using Flask.

Step 1: Set up your project

1. Create a new directory for your project.


2. Set up a virtual environment (optional but recommended).
3. Install Flask.

Step 2: Create the Flask application

Create a new file called app.py in your project directory and add the following code:

22
Step 3: Create HTML templates

Create a directory called templates in your project directory. Inside the templates directory,
create two HTML files: index.html and result.html.

Step 4: Run the application

You can now run your Flask application. In your terminal, make sure you're in your project directory
and run:

Open your web browser and go to http://127.0.0.1:5000/. You should see the typing speed
calculator form. Fill in the values and submit the form to see the estimated typing speed.

Step 5: Deploy the application

To deploy your Flask application to a production environment, you can use a platform like Heroku,
AWS, or any other web hosting service that supports Python applications. Here are the basic steps to
deploy on Heroku:

1. Install the Heroku CLI and log in.


2. Create a Procfile in your project directory with the following content:
3. Create a requirements.txt .ile:
4. Initialize a Git repository and commit your code.
5. Create a new Heroku app and push your code.
6. Open your deployed app.

Monitoring Tips

1. Set Up Alerts: Configure Sentry and any other monitoring tools to send you alerts via email,
Slack, or other channels if issues are detected.
2. Analyze Logs: Regularly review your log files to understand usage patterns and identify
potential issues.
3. Performance Monitoring: Use tools like New Relic or a custom monitoring solution to track
performance metrics like CPU and memory usage if your application grows in complexity.

By following these steps, you can create a typing speed calculator using Pygame and set up basic
monitoring to track its performance and handle errors effectively.

Insights and Actions


Creating insights and actions for a typing speed calculator in Python using Pygame involves analyzing
the collected data to improve user experience and the performance of the application. Here are some
potential insights and actions you can implement:

23
Insights

1. Typing Speed Trends:


o Track how typing speed changes over multiple sessions.
o Identify patterns, such as improvement over time or peak performance periods.
2. Common Errors:
o Analyze the most frequently mistyped words or characters.
o Identify common points of slowdown or hesitation.
3. User Engagement:
o Monitor how often users return to practice typing.
o Track session duration and user interaction levels.
4. Performance Metrics:
o Measure the time taken to process user inputs and update the screen.
o Track any performance issues, such as frame drops or lag.

Actions

1. Personalized Feedback:
o Provide users with feedback on their typing speed trends, highlighting improvements
or areas needing practice.
o Suggest exercises focused on commonly mistyped words or problematic characters.
2. Gamification:
o Introduce elements like levels, badges, or leaderboards to increase user engagement.
o Set challenges or goals to motivate users to practice more.
3. Error Correction Practice:
o Implement features that allow users to practice correcting common errors.
o Offer tips or strategies for overcoming specific typing challenges.
4. Performance Optimization:
o Optimize the Pygame application to ensure smooth performance, especially on lower-
end hardware.
o Reduce latency and improve responsiveness to enhance user experience.

Additional Features

• Data Persistence: The code now includes functions to save and load session data from
a data.json file. This allows for tracking user progress over time.
• Error Tracking: Errors are tracked and logged, providing insights into which characters are
commonly mistyped.
• Session Insights: Each session’s data, including typing speed and errors, is saved and can be
analyzed later.

24
Monitoring and Feedback

1. Analyze Data: Regularly analyze the data stored in data.json to identify trends and
provide personalized feedback.
2. Implement Feedback: Based on the analyzed data, provide real-time feedback to users about
their performance and common mistakes.
3. Continuous Improvement: Use the insights gained from monitoring to continuously improve
the application, making it more responsive, user-friendly, and informative.

By implementing these features, you can gain valuable insights into user behavior and typing
performance, enabling you to make informed decisions to enhance the user experience.

25
UML Diagrams….
FLOW CHART..

Fig.1.3 shows the start to end process and how it is going to execute..
fig.1.4 shows the applications of the project..

26
4. TESTING AND RESULTS

Creating a comprehensive typing speed calculator in Python involves several aspects, including user
interface design, accuracy measurement, error handling, and potentially advanced features like
graphical visualization of results. Below, I'll outline a detailed approach that could span up to 4 pages,
covering each aspect in depth.

The typing speed calculator aims to measure how fast a user can type by calculating the number of
correct words typed per minute (WPM). This project will guide you through designing and
implementing such a calculator using Python. We'll cover the following topics in detail:

User interface design


Timing mechanism
Accuracy measurement
Error handling
Advanced features (optional)

1.User Interface Design


Creating a user-friendly interface enhances the usability of the typing speed calculator. Here's how you
can design it:
2.Welcome Message: Start with a welcoming message and instructions.
Prompt for Input: Ask the user to press Enter to begin typing.
Display Text: Provide a predefined text or allow the user to input their own text.
Input Field: Capture the user's typing input.
Feedback: Provide real-time feedback on accuracy and typing speed.
Results: Display final results including WPM, accuracy percentage, and elapsed time.
3.Timing Mechanism
Accurate timing is crucial for calculating WPM. Use time.time() to record start and end times, and
calculate elapsed time between them.
4. Accuracy Measurement
To measure accuracy:
Compare each word typed by the user with the corresponding word in the prompt.
Count correctly typed words.
Calculate accuracy as a percentage of correct words out of total words.
5. Error Handling
Implement error handling to ensure the program runs smoothly:
Handle unexpected inputs.
Provide clear error messages.

27
Gracefully manage user interactions and exceptions.
6. Advanced Features (Optional)
Consider adding advanced features:
Customizable Text: Allow users to input their own text for testing.
Graphical Visualization: Use libraries like Matplotlib to graphically represent typing speed
progress or historical data.
Multi-user Support: Implement functionality to handle multiple users and store their historical
performance.
Speed vs Accuracy Trade-off: Provide insights or tips to improve both speed and accuracy based
on test results.
RESULTS….
Interface.(Fig 1.5)

28
Random sentences used are…(fig 1.6)

Folders…(fig1.7)

29
Outputs.. (fig 1.8)(fig 1.9)

30
4.1 Model Performancnes
4.1.1 Logistic Regression

Implementing Logistic Regression in a typing speed calculator can provide robust performance metrics
for assessing user typing proficiency. Logistic Regression is well-suited for binary classification tasks,
such as categorizing users into proficient or non-proficient typists based on their typing speed and error
rates.

One of the key strengths of Logistic Regression lies in its interpretability and simplicity. It calculates
the probability of a binary outcome (e.g., proficient or non-proficient) based on input features (e.g.,
typing speed, error rate), allowing the typing speed calculator to provide users with clear insights into
their current typing abilities.

Moreover, Logistic Regression models are computationally efficient and can handle large datasets with
relative ease. This efficiency is crucial for real-time applications where users expect instantaneous
feedback on their typing performance.

To optimize the performance of Logistic Regression in a typing speed calculator, feature engineering
plays a vital role. Selecting relevant features such as typing speed metrics (WPM), error rates (errors
per minute), and possibly additional factors like keystroke dynamics can enhance the model's predictive
accuracy.

In conclusion, integrating Logistic Regression into a typing speed calculator offers a straightforward
yet effective approach to evaluating and improving typing skills. It provides users with actionable
feedback based on statistical probabilities, aiding them in achieving higher typing efficiency and
accuracy over time.

4.1.2 Decision Tree Classifier


Incorporating a Decision Tree classifier into a typing speed calculator can significantly enhance its
ability to analyze user performance and provide tailored feedback. Decision Trees work by creating a
model that predicts the value of a target variable based on several input features, making them
particularly useful for identifying patterns in typing behavior. By examining factors such as typing
speed, error frequency, and specific error types, the Decision Tree classifier can segment users into
different performance categories and identify key determinants of typing proficiency.

This classification allows the typing speed calculator to offer personalized improvement strategies. For
instance, if the Decision Tree identifies that a user consistently makes transpositional errors with certain
letter pairs, the tool can suggest targeted exercises to address this issue. Furthermore, Decision Trees
are inherently interpretable, meaning that the paths and decision rules leading to specific classifications

31
are clear and understandable. This transparency enables users to understand why certain
recommendations are made, fostering a deeper engagement with the learning process.

Overall, the use of a Decision Tree classifier transforms the typing speed calculator into a more
intelligent and responsive educational tool, capable of delivering customized training plans and
insightful feedback, ultimately helping users to enhance their typing skills more effectively.

4.1.3 KNN Classifier


Integrating a KNN (K-Nearest Neighbors) classifier into a typing speed calculator can greatly
improve its ability to provide personalized feedback and adaptive learning experiences. The KNN
algorithm, known for its simplicity and effectiveness, classifies input data based on the closest data
points in the feature space, making it well-suited for identifying patterns in typing behavior. By
analyzing features such as typing speed, accuracy, and error types, the KNN classifier can group users
with similar typing profiles and predict their performance levels. This allows the typing speed calculator
to offer customized practice sessions and targeted exercises based on the collective experience of users
with similar typing characteristics. Additionally, the KNN classifier can help in real-time error detection
and correction by referencing common mistakes made by users within the same proximity in the feature
space. Overall, incorporating a KNN classifier enhances the typing speed calculator's ability to adapt to
individual user needs, making it a more effective tool for improving typing skills through personalized
and data-driven feedback.

4.1.4 SVM Classifier


Implementing an SVM (Support Vector Machine) classifier in a typing speed calculator can
significantly enhance its functionality and accuracy in assessing user performance. An SVM classifier
excels at distinguishing between different classes of data, making it ideal for categorizing types of errors
and predicting user proficiency levels. By analyzing features such as typing speed, error frequency, and
specific mistake patterns, the SVM can identify underlying trends and provide tailored feedback. This
approach allows the typing speed calculator to adapt dynamically to individual users, offering
personalized practice recommendations and identifying areas needing improvement. Moreover, the
SVM classifier's robustness in handling high-dimensional data ensures that even subtle variations in
typing behavior are accurately captured and analyzed. Integrating an SVM classifier thus transforms
the typing speed calculator into a more intelligent and responsive tool, capable of delivering deeper
insights and more effective training strategies for users aiming to enhance their typing skills.

32
4.2 Comparison of Models
When comparing models for a typing speed calculator, several factors come into play, including
accuracy, user engagement, adaptability, and technological integration. Traditional models, which
primarily measure words per minute (WPM) and basic error counts, offer simplicity and ease of use but
may lack depth in analysis and personalization. More advanced models, incorporating machine learning
algorithms, provide adaptive learning experiences that adjust difficulty based on user performance,
offering a tailored approach to skill development. These models often include detailed error analysis,
categorizing mistakes to provide specific feedback, thereby enhancing the learning process.
Additionally, models with gamification elements, such as achievements and leaderboards, significantly
boost user engagement and motivation. Integrating real-time error correction and multilingual support
further broadens the utility of these models, catering to a global audience and various user needs.
Ultimately, while traditional models serve well for basic assessment, advanced and gamified models
offer a more comprehensive, engaging, and effective approach to improving typing skills.

33
5. CONCLUSION AND FUTURE WORK
5.1 Conclusion
In conclusion, the typing speed calculator stands as a valuable tool for individuals seeking to enhance
their typing proficiency. Its ability to measure typing speed and accuracy provides users with
immediate feedback, facilitating continuous improvement. The potential for future enhancements,
including advanced error analysis, personalized learning paths, and gamification, promises to elevate
the user experience further. By integrating multilingual support, mobile optimization, and detailed
analytics, the typing speed calculator can cater to a diverse user base, from students to professionals.
As it evolves, incorporating educational alignment and innovative input methods, it will not only serve
as a practical utility but also as a comprehensive educational resource, empowering users to achieve
greater typing efficiency and accuracy in an engaging and interactive manner.
5.2 Future Work
To expand and improve your typing speed calculator, consider these enhancements:
Error Handling: Handle cases where users may input incorrect text or press Enter prematurely.
Accuracy and Efficiency: Implement methods to ensure accurate timing and character counting,
considering edge cases such as punctuation and special characters.
User Interface: Develop a graphical user interface (GUI) using libraries like Tkinter or PyQt for a more
user-friendly experience.
Advanced Metrics: Calculate additional metrics such as accuracy (percentage of correct keystrokes)
or keystrokes per hour.
Multi-User Support: Extend the program to support multiple users and track typing progress over time.
Compatibility: Ensure compatibility across different platforms and Python version.

34
BIBLIOGRAPHY

1.Python Documentation:
Official Python documentation provides comprehensive information on built-in functions (input(),
time.time()), modules (time), and string operations (len()).
Website: Python Documentation

2.Stack Overflow:
Stack Overflow is a valuable resource for troubleshooting and finding solutions to specific coding
challenges related to Python.
Website: Stack Overflow
3.Python String Methods:
Understanding Python's string manipulation methods (replace(), split(), etc.) can help in handling
user input and calculating typing speed accurately.
Website: Python String Methods
4.Python Time Module:
The time module documentation provides details on functions like time.time() for measuring time
intervals, which is crucial for calculating typing speed.
Website: Python Time Module
5.Typing Speed Calculation Formula:
Information on how to calculate typing speed (words per minute) based on characters typed and
time elapsed can be found in various typing speed measurement resources.
Example: Typing Speed Calculation
6.Python GUI Libraries (Optional):
If you plan to extend your typing speed calculator with a graphical user interface (GUI), resources
on libraries like Tkinter or PyQt can be useful.
Websites: Tkinter Documentation, PyQt Documentation,Pygame Documentataion.
These resources collectively provide a solid foundation for developing a typing speed calculator in
Python, covering fundamental programming techniques, time measurement, string manipulation, and
optional GUI development.

35
Appendix…

import pygame
from pygame.locals import *
import sys
import time
import random

class Game:
def __init__(self):
self.w = 750
self.h = 500
self.reset = True
self.active = False
self.input_text = ''
self.word = ''
self.time_start = 0
self.total_time = 0
self.accuracy = '0%'
self.results = 'Time:0 Accuracy:0 % Wpm:0 '
self.wpm = 0
self.end = False
self.HEAD_C = (255, 213, 102)
self.TEXT_C = (240, 240, 240)
self.RESULT_C = (255, 70, 70)

pygame.init()
try:
self.open_img = pygame.image.load('type-speed-open.png')
self.open_img = pygame.transform.scale(self.open_img, (self.w, self.h))
except pygame.error as e:
print(f"Unable to load type-speed-open.png: {e}")
sys.exit()

try:
self.bg = pygame.image.load('background.jpg')
self.bg = pygame.transform.scale(self.bg, (self.w, self.h))
except pygame.error as e:
print(f"Unable to load background.jpg: {e}")
sys.exit()

36
try:
self.time_img = pygame.image.load('icon.png')
self.time_img = pygame.transform.scale(self.time_img, (150, 150))
except pygame.error as e:
print(f"Unable to load icon.png: {e}")
sys.exit()

self.screen = pygame.display.set_mode((self.w, self.h))


pygame.display.set_caption('Type Speed Test')

def draw_text(self, screen, msg, y, fsize, color):


font = pygame.font.Font(None, fsize)
text = font.render(msg, 1, color)
text_rect = text.get_rect(center=(self.w/2, y))
screen.blit(text, text_rect)

def get_sentence(self):
try:
with open('sentences.txt') as f:
sentences = f.read().split('\n')
sentence = random.choice(sentences)
return sentence
except Exception as e:
print(f"Error reading sentences.txt: {e}")
return ""

def show_results(self, screen):


if not self.end:
self.total_time = time.time() - self.time_start
count = sum(1 for i, c in enumerate(self.word) if i < len(self.input_text) and self.input_text[i]
== c)
self.accuracy = count / len(self.word) * 100 if len(self.word) > 0 else 0
self.wpm = len(self.input_text) * 60 / (5 * self.total_time) if self.total_time > 0 else 0
self.end = True
self.results = f'Time:{round(self.total_time)} secs Accuracy:{round(self.accuracy)}% Wpm:
{round(self.wpm)}'
screen.blit(self.time_img, (self.w/2-75, self.h-140))
self.draw_text(screen, "Reset", self.h - 70, 26, (100, 100, 100))
self.draw_text(screen, self.results, 350, 28, self.RESULT_C)
pygame.display.update()

def run(self):
self.reset_game()

37
self.running = True
while self.running:
clock = pygame.time.Clock()
self.screen.fill((0, 0, 0), (50, 250, 650, 50))
pygame.draw.rect(self.screen, self.HEAD_C, (50, 250, 650, 50), 2)
self.draw_text(self.screen, self.input_text, 274, 26, (250, 250, 250))
pygame.display.update()

for event in pygame.event.get():


if event.type == QUIT:
self.running = False
pygame.quit()
sys.exit()
elif event.type == pygame.MOUSEBUTTONUP:
x, y = pygame.mouse.get_pos()
if 50 <= x <= 650 and 250 <= y <= 300:
self.active = True
self.input_text = ''
self.time_start = time.time()
if 310 <= x <= 510 and y >= 390 and self.end:
self.reset_game()
elif event.type == pygame.KEYDOWN:
if self.active and not self.end:
if event.key == pygame.K_RETURN:
self.show_results(self.screen)
elif event.key == pygame.K_BACKSPACE:
self.input_text = self.input_text[:-1]
else:
self.input_text += event.unicode

clock.tick(60)

def reset_game(self):
self.screen.blit(self.open_img, (0, 0))
pygame.display.update()
time.sleep(1)

self.reset = False
self.end = False
self.input_text = ''
self.word = ''
self.time_start = 0
self.total_time = 0

38
self.wpm = 0

self.word = self.get_sentence()
if not self.word:
self.reset_game()
else:
self.screen.fill((0, 0, 0))
self.screen.blit(self.bg, (0, 0))
self.draw_text(self.screen, "Typing Speed Test", 80, 80, self.HEAD_C)
pygame.draw.rect(self.screen, (255, 192, 25), (50, 250, 650, 50), 2)
self.draw_text(self.screen, self.word, 200, 28, self.TEXT_C)
pygame.display.update()

if __name__ == "__main__":
Game().run()

39

You might also like