Skip to content

Commit

Permalink
Merge branch 'main' into feature/chat-gpt-discord-bot
Browse files Browse the repository at this point in the history
  • Loading branch information
Mrinank-Bhowmick authored Jun 6, 2024
2 parents b54eed3 + 6100185 commit 14e7346
Show file tree
Hide file tree
Showing 17 changed files with 1,221 additions and 351 deletions.
370 changes: 192 additions & 178 deletions README.md

Large diffs are not rendered by default.

75 changes: 64 additions & 11 deletions projects/Quiz Game/main.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,37 @@
# import the sqlite3 to reterive previous scores
import sqlite3
# create Conn to have the database file
def create_connection(db_file):
""" create a database connection to the SQLite database """
conn = None
try:
conn = sqlite3.connect(db_file)
except sqlite3.Error as e:
print(e)
return conn
# store the player's score with their name
def save_score(conn, name, score):
"""
Save the player's score to the database
"""
sql = ''' INSERT INTO scores(name, score)
VALUES(?,?) '''
cur = conn.cursor()
cur.execute(sql, (name, score))
conn.commit()
return cur.lastrowid
# recall the previous scores to display them
def get_all_scores(conn):
"""
Query all rows in the scores table
"""
cur = conn.cursor()
cur.execute("SELECT * FROM scores ORDER BY score DESC")

rows = cur.fetchall()
return rows

# The beginning of the game
print("Welcome to AskPython Quiz")

# Get user's readiness to play the Quiz
Expand Down Expand Up @@ -26,23 +60,42 @@
print("Wrong Answer :(") # User's answer is incorrect

# Question 3
answer = input(
"Question 3: What is the name of your favourite website for learning Python?"
)
answer = input("Question 3: What is the name of your favourite website for learning Python?")
if answer.lower() == "askpython":
score += 1
print("correct") # User's answer is correct, increment the score
else:
print("Wrong Answer :(") # User's answer is incorrect

# Display the result and user's score
print(
"Thank you for Playing this small quiz game, you attempted",
score,
"questions correctly!",
)
mark = int((score / total_questions) * 100)
print(f"Marks obtained: {mark}%")
# Display the result and user's score
print("Thank you for Playing this small quiz game, you attempted", score, "questions correctly!")
mark = int((score / total_questions) * 100)
print(f"Marks obtained: {mark}%")

# Getting the player's name and score to insert into the database
player_name = input("Enter your name: ")
player_score = score

database = "quiz_game.db"

# Create a database connection
conn = create_connection(database)

if conn is not None:
# Save the player's score
save_score(conn, player_name, player_score)

# Display all scores
print("Previous scores:")
scores = get_all_scores(conn)
for row in scores:
print(f"Name: {row[1]}, Score: {row[2]}, Date: {row[3]}")

conn.close()
else:
print("Error! Cannot create the database connection.")
else:
print(" Please, when you're ready, enter the game again.")

# Farewell message
print("BYE!")
27 changes: 27 additions & 0 deletions projects/Quiz Game/setup_db.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import sqlite3

def create_database():
# Connect to the SQLite database (it will create the file if it doesn't exist)
conn = sqlite3.connect('quiz_game.db')

# Create a cursor object
cursor = conn.cursor()

# Create a table to store players' scores
cursor.execute('''
CREATE TABLE IF NOT EXISTS scores (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
score INTEGER NOT NULL,
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP
)
''')

# Commit the changes and close the connection
conn.commit()
conn.close()

print("Database and table created successfully.")

if __name__ == "__main__":
create_database()
162 changes: 0 additions & 162 deletions projects/Snake Game/game.py

This file was deleted.

27 changes: 27 additions & 0 deletions projects/Snake Game/src/constants.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
from enum import Enum
from collections import namedtuple


class RgbColors:
WHITE = (255, 255, 255)
RED = (200, 0, 0)
BLUE1 = (0, 0, 255)
BLUE2 = (0, 100, 255)
BLACK = (0, 0, 0)


class GameSettings:
BLOCK_SIZE = 20
SPEED = 5
WIDTH = 640
HEIGHT = 480


class Direction(Enum):
RIGHT = 1
LEFT = 2
UP = 3
DOWN = 4


Point = namedtuple('Point', ['x', 'y'])
84 changes: 84 additions & 0 deletions projects/Snake Game/src/display.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
import pygame
from constants import RgbColors, GameSettings


class Display:
"""Manages the display of the game."""
def __init__(self):
pygame.init()
self.width = GameSettings.WIDTH
self.height = GameSettings.HEIGHT
self.font = pygame.font.Font(None, 25)
self.window = pygame.display.set_mode((self.width, self.height))
pygame.display.set_caption("Snake")
self.clock = pygame.time.Clock()

def update_ui(self, snake, food, score, high_score):
"""Updates the UI with the current game state.
Args:
snake (Snake): The snake object that contains the snake body (Snake.blocks).
food (Point): The food object to be displayed.
score (int): The current game score.
high_score: The highest score achieved so far.
"""
self.window.fill(RgbColors.BLACK)
self.draw_snake(snake)
self.draw_food(food)
self.draw_score(score)
self.render_high_score(high_score)
pygame.display.flip()

def draw_snake(self, snake):
for block in snake.blocks:
pygame.draw.rect(
self.window, RgbColors.BLUE1,
pygame.Rect(block.x, block.y, GameSettings.BLOCK_SIZE, GameSettings.BLOCK_SIZE)
)
pygame.draw.rect(
self.window, RgbColors.BLUE2, pygame.Rect(block.x + 4, block.y + 4, 12, 12)
)

def draw_food(self, food):
pygame.draw.rect(
self.window,
RgbColors.RED,
pygame.Rect(food.x, food.y, GameSettings.BLOCK_SIZE, GameSettings.BLOCK_SIZE),
)

def draw_score(self, score):
self.font = pygame.font.Font(None, 25)
score_display = self.font.render(f"Score: {score}", True, RgbColors.WHITE)
self.window.blit(score_display, [0, 0])

def render_game_over(self):
self.font = pygame.font.Font(None, 48)
game_over_display = self.font.render("GAME OVER", True, RgbColors.WHITE)
text_width = game_over_display.get_width()
text_height = game_over_display.get_height()
text_x = (self.width - text_width) // 2
text_y = (self.height // 4) - (text_height // 2)
self.window.blit(game_over_display,
[text_x, text_y])
pygame.display.flip()

def render_play_again(self):
self.font = pygame.font.Font(None, 32)
play_again_display = self.font.render("Play again? (Y/N)", True, RgbColors.WHITE)
display_box = play_again_display.get_rect(center=(self.width // 2, self.height // 2))
self.window.blit(play_again_display, display_box)
pygame.display.flip()

def render_high_score(self, high_score):
high_score_display = self.font.render(f"High Score: {high_score}", True, RgbColors.WHITE)
self.window.blit(high_score_display, [self.width - high_score_display.get_width(), 0])

def render_new_high_score(self, new_high_score):
new_high_score_display = self.font.render(f"New High Score: {new_high_score}", True, RgbColors.WHITE)
text_width = new_high_score_display.get_width()
text_height = new_high_score_display.get_height()
text_x = (self.width - text_width) // 2
text_y = (self.height // 3) - (text_height // 2)
self.window.blit(new_high_score_display,
[text_x, text_y])
pygame.display.flip()
Loading

0 comments on commit 14e7346

Please sign in to comment.