#hello
import pygame
import time
import random
import [Link]
# MySQL connection details
db_config = {
'user': 'snake_game_user',
'password': 'your_password',
'host': 'localhost',
'database': 'snake_game_db'
}
# Connect to MySQL
def connect_db():
try:
db_config = {
'user': 'snake_game_user',
'password': 'your_password',
'host': 'localhost',
'database': 'snake_game_db'
}
return [Link](**db_config)
except [Link] as err:
print(f"Database connection error: {err}")
raise
# Initialize the database and create the high_scores table
def init_db():
conn = connect_db()
cursor = [Link]()
[Link]('''CREATE TABLE IF NOT EXISTS high_scores
(id INT AUTO_INCREMENT PRIMARY KEY,
player_name VARCHAR(255),
score INT)''')
[Link]()
[Link]()
#saving player scores
def save_player_score(player_name, score):
conn = None
try:
conn = connect_db()
cursor = [Link]()
query = 'INSERT INTO high_scores (player_name, score) VALUES (%s, %s)'
[Link](query, (player_name, score))
[Link]()
except [Link] as err:
print(f"Error saving score: {err}")
finally:
if conn:
[Link]()
# Function to retrieve top 5 high scores
def get_top_scores():
try:
conn = connect_db()
cursor = [Link]()
query = 'SELECT player_name, score FROM high_scores ORDER BY score DESC
LIMIT 5'
[Link](query)
top_scores = [Link]()
[Link]()
return top_scores
except [Link] as err:
print(f"Error retrieving high scores: {err}")
return []
# Show the top scores before starting the game
def show_top_scores():
print("\n===== High Scores =====")
top_scores = get_top_scores()
if not top_scores:
print("No high scores available yet.")
else:
for rank, (player_name, score) in enumerate(top_scores, start=1):
print(f"{rank}. {player_name} - {score} points")
print("========================\n")
[Link]() # Invoke pygame
# Set display
window_x = 720
window_y = 480
b = [Link](203, 249, 255)
f = [Link](169, 95, 206)
red = [Link](199, 0, 57)
green = [Link](120, 220, 110)
sgreen= [Link](95, 206, 150) #colours
[Link].set_caption("Shristi's Snake Game")
game_window = [Link].set_mode((window_x, window_y)) # game window
clock = [Link]()
fps= 5 # fps controller
snake_pos = [100, 50] #default position and size
snake_body = [[100, 50], [90, 50], [80, 50]] # Initial 3 blocks
food_pos = [[Link](1, (window_x//10)) * 10, [Link](1,
(window_y//10)) * 10] # Position of the first food
food_spawn = True
# initial direction
direction = 'RIGHT'
change_to = direction
# to show the score on the screen
score = 0
def show_score(choice, color, font, size):
score_font = [Link](font, size)
score_surface = score_font.render('Score : ' + str(score), True, color)
score_rect = score_surface.get_rect()
game_window.blit(score_surface, score_rect)
# Game over function
def game_over():
global score
print(f"Game over. Final score: {score}")
player_name = input("Enter your name: ").strip() or "Anonymous" # Prompt for
player name
save_player_score(player_name, score) # Save the score to the database
show_top_scores() # Display the high scores
print("Thanks for playing!")
fo = [Link]('times new roman', 50)
game_over_surf = [Link]('Your Score is : ' + str(score), True, red)
game_over_rect = game_over_surf.get_rect()
game_over_rect.midtop = (window_x / 2, window_y / 4)
game_window.blit(game_over_surf, game_over_rect)
[Link]()
[Link](2)
[Link]()
quit()
# Function to adjust FPS based on score
def calculate_fps(score):
return min(30, 10 + (score // 10)) # Increase FPS every 10 points, max 30
# Main game loop
while True:
for event in [Link]():
if [Link] == [Link]:
[Link]()
quit()
elif [Link] == [Link]:
if [Link] == pygame.K_UP:
if direction != 'DOWN':
change_to = 'UP'
elif [Link] == pygame.K_DOWN:
if direction != 'UP':
change_to = 'DOWN'
elif [Link] == pygame.K_LEFT:
if direction != 'RIGHT':
change_to = 'LEFT'
elif [Link] == pygame.K_RIGHT:
if direction != 'LEFT':
change_to = 'RIGHT'
direction = change_to
# Update snake's position
if direction == 'UP':
snake_pos[1] -= 10
if direction == 'DOWN':
snake_pos[1] += 10
if direction == 'LEFT':
snake_pos[0] -= 10
if direction == 'RIGHT':
snake_pos[0] += 10
snake_body.insert(0, list(snake_pos))
if snake_pos == food_pos:
score += 10
food_spawn = False
else:
snake_body.pop() #snake grow from 'food'
if not food_spawn:
food_pos = [[Link](1, (window_x // 10)) * 10, [Link](1,
(window_y // 10)) * 10]
food_spawn = True
game_window.fill(b)
# Draw the snake
for pos in snake_body:
[Link](game_window, green, [Link](pos[0], pos[1], 10, 10))
# Draw the food
[Link](game_window, f, [Link](food_pos[0], food_pos[1], 10, 10))
# Check for collision with walls or itself
if snake_pos[0] < 0 or snake_pos[0] > window_x - 10:
game_over()
if snake_pos[1] < 0 or snake_pos[1] > window_y - 10:
game_over()
for block in snake_body[1:]:
if snake_pos == block:
game_over()
# Update the screen
show_score(1, sgreen , 'times new roman', 20)
[Link]()
# Adjust FPS dynamically
fps = calculate_fps(score)
[Link](fps)
# Initialize the database
init_db()
# Show top scores before starting the game
show_top_scores()
# Start the game
play_game()
sql part
CREATE DATABASE snake_game_db;
USE snake_game_db;
CREATE TABLE high_scores (
id INT AUTO_INCREMENT PRIMARY KEY,
player_name VARCHAR(255),
score INT
);
ALTER TABLE high_scores MODIFY player_name VARCHAR(255) NOT NULL;
ALTER TABLE high_scores MODIFY score INT NOT NULL;