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

As44 Modified

Uploaded by

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

As44 Modified

Uploaded by

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

S.

NO CONTENT PAGE NO

ABSTRACT
1

2
OBJECTIVE

3
INTRODUCTION

4
EXISTING AND PROPOSED SYSTEM

HARDWARE AND SOFTWARE


5 REQUIREMENTS

6
DECOMPOSITION

7
SOURCE CODE

8
OUTPUT

9
CONCLUSION

10
APPENDIX

11
BIBLIOGRAPHY
ABSTRACT

The Battleship game project is an engaging and interactive application developed usi
Python's Tkinter library. This digital version of the classic board game involves placing
ships on a 10x10 grid and challenging players to guess their locations within a set
number of attempts. By simulating a naval battle scenario, the game enhances playe
logical thinking and problem-solving skills through an enjoyable and user-friendly
interface. The project not only demonstrates the application of basic programming
concepts but also introduces advanced topics such as graphical user interface (GUI)
development, event handling, and game logic implementation in Python.

This project showcases Python's versatility in creating interactive applications and


emphasizes the importance of graphical interfaces in enhancing user experience. Th
Battleship game is designed to provide educational value and entertainment, making
a valuable tool for both learning and leisure. It serves as a practical example for
students and developers to understand the flow of a real-world application,
demonstrating how theoretical knowledge can be applied to create a functional and
enjoyable software program. Overall, the project aims to foster creativity, strategic
thinking, and technical skills through engaging gameplay.
OBJECTIVE:
The Battleship game project aims to create a digital version of the classic board game
with enhanced features and interactive gameplay. This project combines educational
objectives with entertainment to provide a comprehensive learning experience in
programming and game development.

PRIMARY OBJECTIVES AND AIMS:


Developing a Fully Functional Battleship Game:
The main goal is to create a working and enjoyable game that mimics the traditional
Battleship game but with added digital enhancements.
Enhancing Logical Thinking and Problem-Solving Skills:
Through interactive gameplay, players will improve their strategic thinking, spatial
awareness, and problem-solving abilities.
Demonstrating Python Programming Concepts:
The project showcases the use of fundamental and advanced Python programming
concepts such as loops, conditionals, functions, and randomization.
Introducing GUI Development with Tkinter:
By using the Tkinter library, the project provides a practical introduction to creating
graphical user interfaces, which is an essential skill in software development.
Understanding Event-Driven Programming:
The game involves handling user interactions (such as clicks), which helps in
understanding event-driven programming, an important concept in interactive
applications.
Creating an Engaging Learning Experience:
The project aims to be both educational and fun, making learning programming more
engaging and less intimidating for beginners.
Providing a Platform for Further Learning and Expansion:
The project serves as a foundation for future improvements and expansions, such as
adding new features, enhancing graphics, and potentially implementing multiplayer
options.

INTRODUCTION:
Battleship is a classic naval combat game where players aim to sink their opponent's
fleet of ships by guessing their locations on a grid. This project implements a single-
player version of the game where the player competes against the computer. The
computer randomly places ships on the grid, and the player has a limited number of
attempts to guess their locations.

KEY FEATURES
Interactive Gameplay:
Players can interact with the game by clicking on the grid to guess ship positions. The
interactive nature of the game keeps players engaged and focused, providing an
immersive experience.
Real-time Feedback:
The game provides instant feedback on hits and misses, updating the score and chan
left. This feature helps players adjust their strategies dynamically, enhancing the
learning experience.
Random Ship Placement:
Each game starts with ships placed at random positions, ensuring a unique experienc
every time. This randomness adds to the challenge and replay value of the game.
User-friendly Interface:
The graphical interface is designed to be intuitive and easy to navigate, making the
game accessible to players of all ages and skill levels.

TECHNICAL DETAILS
Language:
Python 3.x, a versatile and widely-used programming language known for its simplici
and readability.
Library:
Tkinter for GUI development, a standard library in Python that allows for easy
creation of graphical interfaces.
Game Grid:
10x10 grid represented by buttons, providing a structured and organized layout for th
game.
Scoring:
Points are awarded based on the number of ships hit and remaining chances,
encouraging strategic thinking and careful planning.
Chances:
Players start with 10 chances and can earn more by hitting ships, adding an element
risk and reward to the gameplay.
EXISTING AND PROPOSED SYSTEM

EXISTING SYSTEM
The traditional Battleship game has been around for many years and is usually played
with physical boards and pieces. Here are the main features of the existing system:

KEY FEATURES OF THE EXISTING SYSTEM:


Physical Board and Pieces:
Boards and Pegs: Players use paper or plastic boards and pegs to play.
Manual Setup: Players place their ships manually on the grid.
Turn-Based Gameplay:
Taking Turns: Players take turns guessing where the opponent’s ships are.
Keeping Track: Players must keep track of their guesses and hits themselves.
Limited Feedback and Automation:
No Instant Feedback: Players wait for the opponent to say if a guess is a hit or miss.
Manual Rule Checking: Players have to remember and follow the rules without help.
No Customization:
Fixed Rules: The game has set rules and setup, with no room for changes.
No Difficulty Levels: There are no options for different skill levels.
Social Interaction:
Face-to-Face Play: The game is played in person, which can be fun and social.
Physical Interaction: Handling the pieces adds a tactile element to the game.
PROPOSED SYSTEM
The proposed system brings Battleship to the digital world using Python and Tkinter.
This version has many improvements over the traditional GAME:

PROPOSED SYSTEM ENHANCEMENTS INCLUDE:


Digital Gameplay:
Automatic Setup: The game places ships randomly on the grid.
Real-time Updates: The game gives immediate feedback on hits and misses and upd
the score and chances left.
Enhanced User Interface:
Graphical Grid: A 10x10 grid of buttons makes it easy to play and see what’s
happening.
Visual Feedback: Colors change to show hits, misses, and where the remaining ships
are.
Customization and Flexibility:
Adjustable Settings: Players can change game settings, like the number of ships or
starting chances.
Future Expansions: It’s easy to add new features, like different game modes or
multiplayer.
Increased Efficiency and Accuracy:
Automated Rules: The game automatically checks and follows the rules, reducing
mistakes.
Accurate Tracking: The game keeps a precise record of guesses, hits, and misses.
Enhanced Engagement and Learning:
Interactive Play: Clicking on the grid and seeing immediate results make the game
more engaging.
Educational Value: Players learn programming concepts like GUI development and
event handling.
Accessibility and Convenience:
Cross-Platform: The game works on Windows, macOS, and Linux.
Easy to Use: No physical setup is needed, and the game can be played on any
computer.

HARDWARE AND SOFTWARE REQUIREMENTS

HARDWARE REQUIREMENTS
A computer with at least 2GB of RAM and a 1GHz processor for smooth gameplay.
A monitor with a resolution of at least 1024x768 to clearly display the game.

SOFTWARE REQUIREMENTS
Operating System: Windows, macOS, or Linux. The game should run on any of these
platforms.
Python: Python 3.x installed. Using the latest version ensures compatibility and acces
to new features.
Tkinter: Tkinter library for making the GUI (included with Python). Tkinter makes it
easy to create and manage the graphical interface.
DECOMPOSITION
The Battleship game project consists of several key components, each responsible for
different aspects of the game. Breaking down the project into these components help
in understanding the structure and functionality of the game.

MAIN COMPONENTS
Grid Setup
Function: create_board()
Purpose: To initialize the game board and set up the grid for gameplay.
Details:
Creates a 10x10 grid of buttons using nested loops.
Initializes game variables like attempts, score, and found ships.
Configures the appearance of each button and assigns a command to
handle clicks.
Sets up labels to display the number of chances and score, ensuring player
have the information they need during the game.
Ship Placement
Function: place_ships()
Purpose: To randomly place ships on the grid at the beginning of each game.
Details:
Clears any previous ship positions to start fresh each game.
Randomly selects unique positions on the grid until the required number o
ships (usually 5) are placed.
Ensures that ship positions do not overlap or duplicate, maintaining the
randomness and fairness of the game.
Event Handling
Function: click(row, col)
Purpose: To manage user interactions and update the game state based on player
actions.
Details:
Checks if the clicked button has already been clicked to prevent duplicate
actions.
Updates the button color based on whether a ship is hit (red) or missed
(blue).
Adjusts the number of remaining attempts and the score based on hits and
misses.
Tracks found ships and remaining ships, providing immediate feedback to
the player.
Calls other functions as needed to handle end-of-game scenarios (win or
loss).
Game Logic
Integrated with: click(row, col) function
Purpose: To determine the outcome of player actions and manage the overall game
state.
Details:
Calculates the score by combining the number of found ships and
remaining attempts.
Checks if all ships have been found or if the player has run out of attempts
Provides visual feedback and prompts to the player based on the game
state (e.g., game over, win).
Manages the flow of the game, ensuring it progresses smoothly from start
to finish.
Game Control
Functions: start_game(), reset_game(), exit_game()
Purpose: To control the overall game flow, including starting, resetting, and exiting th
game.
Details:
start_game(): Initializes the game by setting up the board and placing ships. It
hides the start and exit buttons to transition into the game mode.
reset_game(): Resets the game board to its initial state, allowing for a new
round of gameplay. It resets variables and updates the grid and labels.
exit_game(): Closes the game window and terminates the application, ensurin
a clean exit from the game.

ADDITIONAL COMPONENTS
Visual Feedback
Purpose: To provide players with clear visual cues based on their actions and the gam
state.
Details:
Buttons change color to indicate hits (red), misses (blue), and remaining
ships (yellow when revealed).
Labels are updated in real-time to show the number of remaining chances
and the current score, keeping players informed.
User Interaction
Purpose: To facilitate smooth and intuitive interaction between the player and the
game.
Details:
Handles clicks on the grid buttons, providing immediate feedback and updating the
game state.
Ensures that the interface is user-friendly and accessible, making the game
enjoyable for players of all ages.
Randomization
Purpose: To ensure that each game is unique and challenging.
Details:
Uses the random module to generate random positions for ships, ensuring
no two games are the same.
Adds an element of unpredictability, making the game more interesting
and replayable.
End-of-Game Scenarios
Purpose: To handle the game's conclusion based on the player's performance.
Details:
Provides prompts and options for the player when the game ends, whethe
they win or lose.
Calls the reveal_ships() function to show the remaining ships if the player
runs out of attempts, offering closure and understanding of the game
outcome.
SOURCE CODE:
import tkinter as tk
import random
from tkinter import messagebox

def create_board():
global buttons, attempts, chances_label, score_label, score, found_ships, ships,
clicked_buttons
attempts = 10
found_ships = 0
score = 0 # Initialize score here
ships = set() # Initialize ships here
clicked_buttons = set() # Track clicked buttons
buttons = []
for row in range(10):
row_buttons = []
for col in range(10):
button = tk.Button(root, width=6, height=3, bg='lightblue', relief='raised',
bd=5,
command=lambda r=row, c=col: click(r, c))
button.grid(row=row+1, column=col+1, padx=3, pady=3)
row_buttons.append(button)
buttons.append(row_buttons)

# Display chances left


chances_label = tk.Label(root, text=f"Chances: {attempts}", font=('Helvetica', 14))
chances_label.grid(row=11, columnspan=6, pady=10)
# Display score
score_label = tk.Label(root, text=f"Score: {score}", font=('Helvetica', 14))
score_label.grid(row=11, column=6, columnspan=6, pady=10)
def place_ships():
global ships
ships.clear()
while len(ships) < 5:
row = random.randint(0, 9)
col = random.randint(0, 9)
ships.add((row, col))

def click(row, col):


global attempts, score, found_ships
if (row, col) in clicked_buttons:
messagebox.showwarning("Warning", "You already clicked this block. Try
another one.")
return
clicked_buttons.add((row, col))
if (row, col) in ships:
buttons[row][col].configure(bg='red')
ships.remove((row, col))
found_ships += 1
attempts += 2 # Add 2 chances for hitting a ship
else:
buttons[row][col].configure(bg='blue')
attempts -= 1
chances_label.config(text=f"Chances: {attempts}")
# Calculate score based on found ships and attempts left
score = found_ships * 10 + attempts
score_label.config(text=f"Score: {score}")
if attempts <= 0:
reveal_ships()
result = messagebox.askyesno("Battleship", f"Game Over! Your score is {score}.
Do you want to play again?")
if result:
reset_game()
else:
root.destroy()
elif not ships:
result = messagebox.askyesno("Battleship", f"You win! Your score is {score}. Do
you want to play again?")
if result:
reset_game()
else:
root.destroy()

def reveal_ships():
for row, col in ships:
buttons[row][col].configure(bg='yellow')
def start_game():
start_button.grid_forget()
exit_button.grid_forget()
create_board()
place_ships()
def reset_game():
global attempts, score, found_ships, ships, clicked_buttons
for row in buttons:
for button in row:
button.configure(bg='lightblue', state='normal')
place_ships()
attempts = 10
found_ships = 0
clicked_buttons.clear()
chances_label.config(text=f"Chances: {attempts}")
score_label.config(text=f"Score: {score}")

def exit_game():
root.destroy()

root = tk.Tk()
root.title("Battleship")
button_style = {
"width": 20,
"height": 2,
"bg": "lightblue",
"relief": "raised",
"bd": 10,
"font": ('Helvetica', 12, 'bold')
}
start_button = tk.Button(root, text="Start", command=start_game, **button_style)
start_button.grid(row=0, columnspan=12, pady=20)

exit_button = tk.Button(root, text="Exit", command=exit_game, **button_style)


exit_button.grid(row=1, columnspan=12)

root.mainloop()
OUTPUT:
CONCLUSION
The Battleship game project demonstrates how Python and Tkinter can be used to
create an interactive and educational game. By developing this game, several key
programming concepts have been explored, including:

GUI Development: Creating a user-friendly interface using Tkinter.


Event Handling: Managing user interactions, such as button clicks, to provide rea
time feedback.
Randomization: Implementing random ship placement to ensure each game is
unique.
Game Logic: Developing the core mechanics of the game, such as scoring, hit/mis
detection, and win/loss conditions.
Project Structuring: Breaking down the project into manageable components to
maintain clear organization.

This project highlights the importance of interactive learning in programming


education. By building and playing the Battleship game, students can gain hands-on
experience with Python and understand the flow of a real-world application. The
digital version of Battleship can be easily expanded with new features, such as differe
difficulty levels, enhanced graphics, and multiplayer modes, providing a solid
foundation for future development.
Overall, the Battleship game project is a valuable tool for both learning and
entertainment. It encourages logical thinking, problem-solving, and creativity, making
it an excellent addition to any educational curriculum or personal learning journey.
APPENDIX
KEY FEATURES
Interactive Gameplay: Clickable 10x10 grid for guessing ship locations.
Real-time Feedback: Instant color-coded responses for hits and misses.
Random Ship Placement: Unique ship positions each game.
Scoring System: Real-time score updates based on hits and remaining chances.
User-friendly Interface: Simple, intuitive design for easy navigation.
Game Control: Start, reset, and exit functions for smooth gameplay.

ALGORITHM
Initialize the Game:
Set up the main window and display start and exit buttons.
Start the Game:
Hide the start and exit buttons.
Set up the game board and place ships randomly.
Create Board:
Initialize variables and create a 10x10 grid of buttons.
Display labels for chances and score.
Place Ships:
Randomly place ships on the grid, ensuring no duplicates.
Handle Button Clicks:
Check if the button was already clicked.
Update button color and game state based on hits or misses.
Update chances and score, and check for game end conditions.
End of Game:
Display win or game over messages.
Offer to play again or exit.
Reset Game:
Reset variables and board for a new game.
Exit Game:
Close the application.

BIBLIOGRAPHY
www.wikipedia
www.google.com
NCERT computer science book

You might also like