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

game in python

python

Uploaded by

kavithaksreddy88
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

game in python

python

Uploaded by

kavithaksreddy88
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 7

import random

# Class to represent a Sudoku game

class Sudoku:

def __init__(self):

self.grid = self.generate_sudoku()

# Function to generate a Sudoku grid (empty, to be solved)

def generate_sudoku(self):

grid = [[0 for _ in range(9)] for _ in range(9)]

self.fill_grid(grid)

return grid

# Function to fill the Sudoku grid with numbers (random placement)

def fill_grid(self, grid):

for _ in range(9): # Try to place numbers in 9 random positions

row, col = random.randint(0, 8), random.randint(0, 8)

num = random.randint(1, 9)

if self.is_safe(grid, row, col, num):

grid[row][col] = num

# Function to check if placing a number is safe


def is_safe(self, grid, row, col, num):

# Check if the number already exists in the row or column

for i in range(9):

if grid[row][i] == num or grid[i][col] == num:

return False

# Check if the number exists in the 3x3 sub-grid

start_row, start_col = 3 * (row // 3), 3 * (col // 3)

for i in range(3):

for j in range(3):

if grid[start_row + i][start_col + j] == num:

return False

return True

# Function to display the Sudoku grid

def display_grid(self):

for row in self.grid:

print(" ".join(str(cell) if cell != 0 else '.' for cell in row))

# Function to solve the Sudoku using backtracking

def solve(self, grid):


empty_cell = self.find_empty_cell(grid)

if not empty_cell:

return True # Puzzle solved

row, col = empty_cell

for num in range(1, 10):

if self.is_safe(grid, row, col, num):

grid[row][col] = num

if self.solve(grid):

return True

grid[row][col] = 0 # Backtrack

return False

# Function to find the next empty cell (0 in this case)

def find_empty_cell(self, grid):

for i in range(9):

for j in range(9):

if grid[i][j] == 0:

return (i, j)

return None
# Function to check if the Sudoku puzzle is solved

def is_solved(self):

for row in self.grid:

if 0 in row:

return False

return True

# Class to represent the player

class Player:

def __init__(self, name):

self.name = name

self.score = 0

def increase_score(self):

self.score += 1

def get_score(self):

return self.score

# Function for main game logic

def main():
print("Welcome to Sudoku Solver Game!\n")

# Get player name and create player object

player_name = input("Enter your name: ")

player = Player(player_name)

# Create a Sudoku puzzle

game = Sudoku()

print("Here is your Sudoku Puzzle:")

game.display_grid()

# Allow player to make moves

while not game.is_solved():

try:

row = int(input("Enter row (0-8): "))

col = int(input("Enter column (0-8): "))

num = int(input("Enter number (1-9): "))

# Check if inputs are valid

if 0 <= row < 9 and 0 <= col < 9 and 1 <= num <= 9:

if game.is_safe(game.grid, row, col, num):


game.grid[row][col] = num

print("Updated Sudoku Grid:")

game.display_grid()

# Check if puzzle is solved

if game.is_solved():

print("Congratulations, you have solved the Sudoku!")

player.increase_score()

break

else:

print("Invalid move! The number doesn't fit in this position.")

else:

print("Invalid input. Row and column must be between 0-8, and


number must be between 1-9.")

except ValueError:

print("Please enter valid integers for row, column, and number.")

print(f"Your score: {player.get_score()}")

# Save player score to a file

with open("player_scores.txt", "a") as file:

file.write(f"{player.name}: {player.get_score()}\n")
print("Your score has been saved!")

if __name__ == "__main__":

main()

You might also like