0% found this document useful (0 votes)
8 views

snake game python+ sql code

The document contains a Python script for a Snake game using Pygame and MySQL for storing high scores. It includes functions to connect to a MySQL database, initialize the high scores table, save player scores, and retrieve the top five scores. The game features a main loop for controlling the snake, handling collisions, and displaying scores, with a game over function that prompts for player names and saves their scores.

Uploaded by

smoldedgaybean
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)
8 views

snake game python+ sql code

The document contains a Python script for a Snake game using Pygame and MySQL for storing high scores. It includes functions to connect to a MySQL database, initialize the high scores table, save player scores, and retrieve the top five scores. The game features a main loop for controlling the snake, handling collisions, and displaying scores, with a game over function that prompts for player names and saves their scores.

Uploaded by

smoldedgaybean
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/ 5

#hello

import pygame
import time
import random
import mysql.connector

# 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 mysql.connector.connect(**db_config)
except mysql.connector.Error 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 = conn.cursor()
cursor.execute('''CREATE TABLE IF NOT EXISTS high_scores
(id INT AUTO_INCREMENT PRIMARY KEY,
player_name VARCHAR(255),
score INT)''')
conn.commit()
conn.close()

#saving player scores


def save_player_score(player_name, score):
conn = None
try:
conn = connect_db()
cursor = conn.cursor()
query = 'INSERT INTO high_scores (player_name, score) VALUES (%s, %s)'
cursor.execute(query, (player_name, score))
conn.commit()
except mysql.connector.Error as err:
print(f"Error saving score: {err}")
finally:
if conn:
conn.close()

# Function to retrieve top 5 high scores


def get_top_scores():
try:
conn = connect_db()
cursor = conn.cursor()
query = 'SELECT player_name, score FROM high_scores ORDER BY score DESC
LIMIT 5'
cursor.execute(query)
top_scores = cursor.fetchall()
conn.close()
return top_scores
except mysql.connector.Error 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")

pygame.init() # Invoke pygame

# Set display
window_x = 720
window_y = 480

b = pygame.Color(203, 249, 255)


f = pygame.Color(169, 95, 206)
red = pygame.Color(199, 0, 57)
green = pygame.Color(120, 220, 110)
sgreen= pygame.Color(95, 206, 150) #colours

pygame.display.set_caption("Shristi's Snake Game")


game_window = pygame.display.set_mode((window_x, window_y)) # game window

clock = pygame.time.Clock()
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 = [random.randrange(1, (window_x//10)) * 10, random.randrange(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 = pygame.font.SysFont(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 = pygame.font.SysFont('times new roman', 50)


game_over_surf = fo.render('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)
pygame.display.flip()
time.sleep(2)
pygame.quit()
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 pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
if direction != 'DOWN':
change_to = 'UP'
elif event.key == pygame.K_DOWN:
if direction != 'UP':
change_to = 'DOWN'
elif event.key == pygame.K_LEFT:
if direction != 'RIGHT':
change_to = 'LEFT'
elif event.key == 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 = [random.randrange(1, (window_x // 10)) * 10, random.randrange(1,
(window_y // 10)) * 10]

food_spawn = True
game_window.fill(b)

# Draw the snake


for pos in snake_body:
pygame.draw.rect(game_window, green, pygame.Rect(pos[0], pos[1], 10, 10))

# Draw the food


pygame.draw.rect(game_window, f, pygame.Rect(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)
pygame.display.update()

# Adjust FPS dynamically


fps = calculate_fps(score)
clock.tick(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;

You might also like