0% found this document useful (0 votes)
21 views21 pages

Python

Uploaded by

veerjyotsammi1
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)
21 views21 pages

Python

Uploaded by

veerjyotsammi1
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/ 21

SRDAV Public School

SESSION 2024-2025

Computer Science Project


ON

Wordle Game Using SQL Dataset & Python

SUBMITTED BY.

Veerjyot Singh Sammi


ACKNOWLEGEMENT
On completion of my investigatory project, I feel extremely
delighted. It wasn’t a single effort. I would like to thank my
Computer Science teacher for supporting me and giving
me this opportunity to work on this project. I would like to
thank my parents for helping and encouraging me to
pursue this project.

Signature of Student
CERTIFICATE
This is to certify that Veerjyot Singh Sammi of class: XII - C
of SRDAV Public School has done his project on WORDLE
GAME USING SQL DATASET AND PYTHON under
my supervision. He has taken interest and has shown at
most sincerity in completion of this project. I certify this
project up to my expectation & as per guidelines issued by
CBSE, New Delhi

Teacher Signature
INDEX

S.no Topic

1 Acknowledgment

2 Certificate

3 Hardware and Software requirement

4 Introduction

5 About Libraries Used

6 Python Code

7 HTML and CSS Code

8 Output

9 References
HARDWARE AND SOFTWARE REQUIRED

Hardware
1. Desktop Computer / Laptop
2. Mobile Phone (Optional)

Software
1. Python
2. MySQL
3. Code Editor (eg :- PyCharm, VS Code)
4. Browser to access the page (eg :- Safari, Chrome)
Introduction
This project is a web-based implementation of the popular
word puzzle game Wordle, designed to challenge players'
vocabulary and logical deduction skills. In this game,
players attempt to guess a hidden five-letter word by
submitting their guesses and receiving feedback after each
attempt. The ultimate goal is to deduce the correct word
within a limited number of attempts. With its engaging
gameplay and instant feedback, Wordle encourages
players to think strategically and expand their vocabulary.
The project is built using Python and Flask for back-end
development, combined with an SQL database to manage
a rich dataset of 5,000 valid five-letter words. The
database plays a critical role in ensuring that the player’s
guesses are validated against an extensive list of possible
words. It also randomly selects a new target word at the
start of each game session, maintaining the challenge and
excitement of the game.
Key Aspects of the Project:
Game Logic: The project implements the core rules of
Wordle, providing players with immediate feedback on
their guesses:
• Green: Indicates a correct letter in the correct position.
• Yellow: Indicates a correct letter in the wrong position.
• Gray: Indicates an incorrect letter.
Database Integration: The system integrates an SQL
database that serves two primary purposes:
1. It validates user guesses against a predefined list of
valid five-letter words.
2. It randomly selects a target word for each game
session, ensuring a fresh challenge for every new
game.
Interactive User Interface: The web application features a
user-friendly interface where players can:
• Enter their guesses.
• View previously guessed words along with their color-
coded feedback.
• Use a virtual keyboard that dynamically updates to
show which letters are correct, misplaced, or absent.
Real-Time Feedback: The game provides real-time
feedback after each guess, instantly updating the game
state with color-coded clues. This enhances player
engagement by offering immediate responses, which
improves the overall gameplay experience.
By combining a robust SQL database with a dynamic web
application, this project demonstrates a comprehensive
approach to building an interactive game. It highlights my
skills in back-end logic design, database integration, and
the creation of user-friendly front-end interfaces,
showcasing a balanced focus on both functionality and
user experience.
About Library Used

Flask: A Web Framework for Python


Flask is a popular and lightweight web framework for
Python, used to build web applications quickly and with
minimal code. Flask follows the WSGI (Web Server
Gateway Interface) standard and is considered a
"microframework" because it doesn't include tools or
libraries for everything—leaving developers with the
flexibility to choose what they need. Flask is easy to use
for small to medium-scale applications but is powerful
enough for larger projects when extended with additional
libraries.

SQLite3: A Lightweight Database


SQLite3 is a database engine that implements a self-
contained, serverless, and zero-configuration database. It
is widely used for applications that need a lightweight
relational database but don’t want the overhead of running
a separate database server like MySQL or PostgreSQL.
SQLite is embedded directly into the application and stores
the data in a single file.
Random: Library for Random Number Generation
The random library in Python is part of the standard library
and provides functions to generate random numbers,
shuffle sequences, and pick random elements from a list or
range. It’s commonly used for simulations, games, testing,
and other applications where randomness is needed.
Python Code
Code available at :–
https://github.com/VeerjyotSingh/Wordle

File 1: app.py

from flask import Flask, request, render_template, session,


redirect, url_for
import random
import sqlite3

#intializing our flask app and session secret key


app = Flask(__name__)
app.secret_key = ('Wordle_Game')

"""
1.Connecting to the database
2.creating a cursor object
3.creating a table words if it does not exist
4.Selecting all the words in the db
5.Storing all the words in form of a list words
"""

conn = sqlite3.connect("words.db")
cursor = conn.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS Words (
id INTEGER PRIMARY KEY AUTOINCREMENT,
word TEXT NOT NULL
)""")

cursor.execute("SELECT word FROM Words")


words = []

for row in cursor.fetchall():


words.append(row[0])
CORRECT_WORD = ""
def get_new_word():
"""Selecting a random word from the words list
if word is empty, it sets the CORRECT_WORD to flask"""
global CORRECT_WORD
if words:
CORRECT_WORD = random.choice(words)
else:
CORRECT_WORD = "flask"

#initializing the main page for flask


@app.route('/', methods=['GET', 'POST'])
def wordle():
if 'game_state' not in session:
# Initialize session variables
session['game_state'] = {
'attempts': [],
'keyboard': {chr(c): None for c in range(97,
123)}, # a-z with initial state None
'game_over': False,
'message': ""
}

game_state = session['game_state']

if request.method == 'POST' and not


game_state['game_over']:
user_word = request.form['word'].lower()

if len(user_word) != len(CORRECT_WORD):
game_state['message'] = f"Word must be
{len(CORRECT_WORD)} letters long."
elif len(game_state['attempts']) >= 5:
game_state['message'] = f"Game over! The correct
word was '{CORRECT_WORD}'."
game_state['game_over'] = True
else:
feedback = []
for i, char in enumerate(user_word):
if char == CORRECT_WORD[i]:
feedback.append('green') # Correct
position
game_state['keyboard'][char] = 'green'
elif char in CORRECT_WORD:
feedback.append('yellow') # Correct
letter, wrong position
if game_state['keyboard'][char] !=
'green': # Avoid downgrading green
game_state['keyboard'][char] =
'yellow'
else:
feedback.append('gray') # Incorrect
letter
game_state['keyboard'][char] = 'gray'

game_state['attempts'].append({'word': user_word,
'feedback': feedback})

if user_word == CORRECT_WORD:
game_state['message'] = "Correct! You guessed
the word!"
game_state['game_over'] = True
elif len(game_state['attempts']) >= 5:
game_state['message'] = f"Game over! The
correct word was '{CORRECT_WORD}'."
game_state['game_over'] = True
else:
game_state['message'] = f"Wrong! Attempts
left: {5 - len(game_state['attempts'])}"

session.modified = True

return render_template('wordle.html',
game_state=game_state)

"""
1.Getting new word
2.removing the game state from the session
3.redirecting to the main game page
"""
@app.route('/reset')
def reset():
get_new_word()
session.pop('game_state', None)
return redirect(url_for('wordle'))

if __name__ == '__main__':
#getting a new word at start of the game
get_new_word()
app.run(debug=True)
File 2 :- database.py

import sqlite3

# Connect to SQLite database (or create it if it doesn't


exist)
conn = sqlite3.connect('words.db')
cursor = conn.cursor()

# Create the table if it doesn't exist


cursor.execute("""
CREATE TABLE IF NOT EXISTS Words (
id INTEGER PRIMARY KEY AUTOINCREMENT,
word TEXT NOT NULL
)
""")

# Open the text file containing words


with open('words.txt', 'r') as file:
words = file.readlines()

# Insert each word into the database


for word in words:
word = word.strip()
cursor.execute("INSERT INTO Words (word) VALUES (?)",
(word,))

# Commit the changes and close the connection


conn.commit()
conn.close()

print("Words have been loaded into the database.")


HTML and CSS file
File 1 :- Wordle.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Wordle Game</title>
<link rel="stylesheet" href="{{ url_for('static',
filename='styles.css') }}">
</head>
<body>
<div class="container">
<header>
<h1>Wordle Game</h1>
</header>
<main>
<p class="message">{{ game_state['message'] }}</p>

<!-- Display guessed words with feedback -->


<div class="guesses">
{% for attempt in game_state['attempts'] %}
<div class="guess">
{% for i in
range(attempt['word']|length) %}
<span class="letter {{
attempt['feedback'][i] }}">
{{ attempt['word'][i] }}
</span>
{% endfor %}
</div>
{% endfor %}
</div>

{% if not game_state['game_over'] %}
<form method="post" class="word-form">
<label for="word">Enter your word:</label>
<!-- Adds an accessible label -->
<input
type="text"
id="word"
name="word"
placeholder="Type a 5-letter word"
maxlength=5
title="Type a 5-letter word"
required
>
<button type="submit">Submit</button>
</form>

{% else %}
<a href="/reset" class="reset-btn">Play
Again</a>
{% endif %}

<!-- Display the virtual keyboard -->


<div class="keyboard">
{% for row in ['qwertyuiop', 'asdfghjkl',
'zxcvbnm'] %}
<div class="keyboard-row">
{% for char in row %}
<button class="key {{
game_state['keyboard'][char] or '' }}" disabled>
{{ char.upper() }}
</button>
{% endfor %}
</div>
{% endfor %}
</div>
</main>
</div>
</body>
</html>

File 2 :- styles.css
/* General styling */
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
margin: 0;
padding: 0;
}

.container {
max-width: 600px;
margin: 0 auto;
padding: 20px;
text-align: center;
}

.message {
font-size: 1.2rem;
margin-bottom: 20px;
}

/* Guesses */
.guesses {
margin: 20px 0;
}

.guess {
display: flex;
justify-content: center;
gap: 5px;
margin-bottom: 10px;
}

.letter {
display: inline-block;
width: 40px;
height: 40px;
line-height: 40px;
text-align: center;
font-size: 1.2rem;
font-weight: bold;
border: 1px solid #ccc;
border-radius: 5px;
}

.green {
background-color: #6aaa64;
color: white;
}

.yellow {
background-color: #c9b458;
color: white;
}

.gray {
background-color: #787c7e;
color: white;
}

/* Keyboard */
.keyboard {
margin-top: 20px;
}

.keyboard-row {
display: flex;
justify-content: center;
gap: 5px;
margin-bottom: 10px;
}

.key {
width: 40px;
height: 40px;
font-size: 1rem;
border: none;
border-radius: 5px;
background-color: #d3d6da;
cursor: not-allowed;
}

.key.green {
background-color: #6aaa64;
color: white;
}

.key.yellow {
background-color: #c9b458;
color: white;
}

.key.gray {
background-color: #787c7e;
color: white;
}
.word-form input {
z-index: 1; /* Ensure it's above other elements */
pointer-events: auto; /* Ensure it's interactive */
}
Outputs
References
1. Flask Documents :-
https://flask.palletsprojects.com/en/stable/
2. Python4me site :-
https://www.python4me.com
3. Wikipedia for research:-
https://www.wikipedia.org
4. W3School :-
https://www.w3schools.com/python/

You might also like