PRESS START
VIDEO GAME
VIDEO GAME
PRESENTATION
232323
HI-SCORE
Summary
My last day of work at the synergy internship will be Friday August 2nd
© 20XX dom and nick GAMES
import random import os import colorama from colorama import Fore, Style import time import sys
Importing Modules
The game starts by importing several essential Python modules: random, os, colorama, time, and sys. The random module is used for generating random ship placements and computer moves. The os module provides functionality to clear the terminal screen between turns. colorama is used for adding color to terminal output, enhancing the visual feedback of hits, misses, and game outcomes. time is employed to create delays for user interaction effects, while sys is used for handling output directly to the terminal.
def print_slow(text): for char in text: sys.stdout.write(char) # Write each character to the terminal sys.stdout.flush() # Ensure the character is displayed immediately time.sleep(0.05) # Wait for a short time before printing the next character print() # Move to the next line after printing all characters def get_valid_input(prompt, min_val, max_val): while True: try: value = int(input(prompt)) # Read input from user and convert it to an integer if min_val <= value <= max_val: # Check if the value is within the specified range return value else: print(f"Please enter a number between {min_val} and {max_val}.") except ValueError: print("Invalid input. Please enter a number.")
Text Display and Input Handling
The print_slow function displays text character by character with a slight delay, creating a typing effect. This enhances the user experience by making the game's narrative more engaging. The get_valid_input function prompts the user for input and ensures that it falls within a specified range. It handles invalid input gracefully by providing feedback and re-prompting the user until valid input is received. This function ensures robust error handling and user interaction consistency.
def display_board(board, show_all=False): # Print column headers print(" " + " ".join(str(i) for i in range(1, len(board) + 1))) for i, row in enumerate(board): # Enumerate over rows in the board if show_all: # Display all cells including ship positions ('#', 'X', 'O') and empty cells ('~') row_display = " ".join(cell if cell in ['#', 'X', 'O'] else '~' for cell in row) else: # Hide ship positions; display only hits ('X') and misses ('O') with empty cells ('~') row_display = " ".join(cell if cell in ['X', 'O'] else '~' for cell in row) print(f"{i+1} {row_display}") # Print row number (e.g., "1") and row contents print()
Displaying the Board
The display_board function is responsible for rendering the game board. It can display the board with all ship positions visible or only the results of previous guesses. If show_all is True, it shows all cells including ship positions marked by #, hits marked by X, and misses marked by O. Otherwise, it only shows the hits and misses along with empty cells represented by ~. This function provides clear and informative visual feedback to players during the game.
def place_ship_manually(board, ship, size):
while True:
display_board(board, show_all=True) # Show the board to the user
print(f"Placing {ship} (Size: {size})") # Prompt user about the ship placement
# Get user input for starting row and column
start_row = get_valid_input(f"Enter the start row (1-{len(board)}): ", 1, len(board)) - 1
start_col = get_valid_input(f"Enter the start column (1-{len(board)}): ", 1, len(board)) - 1
orientation = input("Enter orientation (H for horizontal, V for vertical): ").upper()
# Check if the ship can be placed horizontally
if orientation == 'H' and start_col + size <= len(board):
if all(board[start_row][col] == '~' for col in range(start_col, start_col + size)):
# Place the ship on the board
for col in range(start_col, start_col + size):
board[start_row][col] = '#' # Mark the ship's position
return [(start_row, start_col), (start_row, start_col + size - 1)] # Return the ship's start and end coordinates
# Check if the ship can be placed vertically
elif orientation == 'V' and start_row + size <= len(board):
if all(board[row][start_col] == '~' for row in range(start_row, start_row + size)):
# Place the ship on the board
for row in range(start_row, start_row + size):
board[row][start_col] = '#' # Mark the ship's position
return [(start_row, start_col), (start_row + size - 1, start_col)] # Return the ship's start and end coordinates
# placement is invalid and prompt to try again
print("Invalid placement. Try again.")
Placing Ships Manually
The place_ship_manually function is a great tool that lets players place their ships on the board by choosing the starting position and orientation. It makes sure that the ships are placed correctly without overlapping or going off the board. The function also helps decide if the ship should go horizontally or vertically, and then updates the board accordingly. This hands-on way of placing ships gives players more control over their strategy and adds a personal feel to the game setup.
def place_ship_randomly(board, size): while True: # Continuously loop until the ship is placed correctly row = random.randint(0, len(board) - 1) # Randomly select a row col = random.randint(0, len(board) - 1) # Randomly select a column orientation = random.choice(['H', 'V']) # Randomly choose orientation (horizontal or vertical) # Check if the ship can be placed horizontally if orientation == 'H' and col + size <= len(board): if all(board[row][c] == '~' for c in range(col, col + size)): # Place the ship on the board for c in range(col, col + size): board[row][c] = '#' # Mark the ship's position return [(row, col), (row, col + size - 1)] # Return the ship's start and end coordinates # Check if the ship can be placed vertically elif orientation == 'V' and row + size <= len(board): if all(board[r][col] == '~' for r in range(row, row + size)): # Place the ship on the board for r in range(row, row + size): board[r][col] = '#' # Mark the ship's position return [(row, col), (row + size - 1, col)] # Return the ship's start and end coordinates
Placing Ships Randomly
The place_ship_randomly function automates the ship placement process for the computer. It randomly selects a position and orientation for each ship and verifies that the placement is valid. This function ensures that ships are placed without overlapping or exceeding board limits, adding a layer of unpredictability to the computer's strategy. Random placement keeps the game challenging and fair by avoiding predictable ship arrangements.
def game_loop(player, computer): turns = 0 max_turns = 100 while player['hits'] < sum(ship["size"] for ship in player['ships']) and computer['hits'] < sum(ship["size"] for ship in computer['ships']) and turns < max_turns: os.system('cls' if os.name == 'nt' else 'clear') print("Your board:") display_board(player['board'], show_all=True) print("Enemy's board:") display_board(computer['board']) row = get_valid_input(f"Enter the row (1-{len(player['board'])}): ", 1, len(player['board'])) - 1 col = get_valid_input(f"Enter the column (1-{len(player['board'])}): ", 1, len(player['board'])) - 1 if (row, col) in player['guesses']: print("You've already guessed that location. Try again.") continue player['guesses'].append((row, col)) hit = False for i, (start, end) in enumerate(computer['ship_positions']): if (start[0] <= row <= end[0]) and (start[1] <= col <= end[1]): hit = True computer['board'][row][col] = 'X' player['hits'] += 1 print(Fore.GREEN + f"Hit at ({row+1}, {col+1})!" + Style.RESET_ALL) if player['hits'] == sum(ship["size"] for ship in player['ships']): print(Fore.GREEN + "You sank all the enemy ships!" + Style.RESET_ALL) break elif player['hits'] == sum(ship["size"] for ship in computer['ships']): print(Fore.GREEN + f"You sank the {computer['ships'][i]['name']}!" + Style.RESET_ALL) break if not hit: computer['board'][row][col] = 'O' print(Fore.RED + f"Miss at ({row+1}, {col+1})." + Style.RESET_ALL) row = random.randint(0, len(player['board']) - 1 col = random.randint(0, len(player['board']) - 1) while (row, col) in computer['guesses']: row = random.randint(0, len(player['board']) - 1) col = random.randint(0, len(player['board']) - 1) computer['guesses'].append((row, col))
Subtitle hit = False for i, (start, end) in enumerate(player['ship_positions']): if (start[0] <= row <= end[0]) and (start[1] <= col <= end[1]): hit = True player['board'][row][col] = 'X' computer['hits'] += 1 print(Fore.GREEN + f"The enemy hit your ship at ({row+1}, {col+1})!" + Style.RESET_ALL) if computer['hits'] == sum(ship["size"] for ship in computer['ships']): print(Fore.RED + "The enemy sank all your ships!" + Style.RESET_ALL) break elif computer['hits'] == sum(ship["size"] for ship in player['ships']): print(Fore.RED + f"The enemy sank your {player['ships'][i]['name']}!" + Style.RESET_ALL) break if not hit: player['board'][row][col] = 'O' print(Fore.RED + f"The enemy missed at ({row+1}, {col+1})." + Style.RESET_ALL) turns += 1 if player['hits'] >= sum(ship["size"] for ship in player['ships']): print(Fore.GREEN + "You won!" + Style.RESET_ALL) elif computer['hits'] >= sum(ship["size"] for ship in computer['ships']): print(Fore.RED + "The enemy won!" + Style.RESET_ALL) else: print(Fore.YELLOW + "The game ended in a draw." + Style.RESET_ALL)
Game Loop
The game_loop function is in charge of managing the gameplay mechanics by taking turns between the player and the computer, handling guesses, updating the board, and checking for hits or misses. It also deals with game-ending situations such as sinking all ships or reaching the maximum number of turns. The function gives visual feedback for hits, misses, and game outcomes to make the experience more dynamic. The loop keeps going until one side emerges victorious or the game ends in a draw.
if __name__ == "__main__":
# Define the size of the grid and ensure it is at least 10x10
grid_size = get_valid_input("Enter the size of the grid (minimum 10x10): ", 10, 100)
# Define the ships with their names and sizes
ships = [
{"name": "Aircraft Carrier", "size": 5},
{"name": "Battleship", "size": 4},
{"name": "Submarine", "size": 3},
{"name": "Cruiser", "size": 3},
{"name": "Destroyer", "size": 2}
]
# Initialize player and computer boards with empty cells ('~')
player_board = [['~' for _ in range(grid_size)] for _ in range(grid_size)]
computer_board = [['~' for _ in range(grid_size)] for _ in range(grid_size)]
# Initialize player and computer dictionaries with their respective boards, ships, and other attributes
player = {
"board": player_board,
"ships": ships,
"ship_positions": [], # List to store positions of ships placed by the player
"guesses": [], # List to store guesses made by the player
"hits": 0 # Counter for the number of hits the player has made
}
computer = {
"board": computer_board,
"ships": ships,
"ship_positions": [], # List to store positions of ships placed by the computer
"guesses": [], # List to store guesses made by the computer
"hits": 0 # Counter for the number of hits the computer has made
}
# Player names ships and places them manually on the board
for ship in ships:
ship["name"] = input(f"Enter a name for your {ship['name']} (Size: {ship['size']}): ")
ship_position = place_ship_manually(player_board, ship["name"], ship["size"]) # Place ship manually
player["ship_positions"].append(ship_position) # Add ship position to player's list
# Computer places ships randomly on the board
for ship in ships:
ship_position = place_ship_randomly(computer_board, ship["size"]) # Place ship randomly
computer["ship_positions"].append(ship_position) # Add ship position to computer's list
# Start the game loop to begin the gameplay
game_loop(player, computer)
# Print game results based on the outcome if player['hits'] == sum(ship["size"] for ship in player['ships']):
print(Fore.GREEN + "Congratulations, you won!" + Style.RESET_ALL) # Player wins print(""" """) # Display win ASCII art elif computer['hits'] == sum(ship["size"] for ship in computer['ships']):
print(Fore.RED + "You lost." + Style.RESET_ALL) # Computer wins print(""" """) # Display loss ASCII art else:
print(Fore.YELLOW + "The game ended in a draw." + Style.RESET_ALL) # Game ends in a draw
colorama.deinit()
BUSSINESS PROPSAL THE CODE
Video Game Presentation
X Dømïnîç šimpśöñ X
Created on July 23, 2024
Start designing with a free template
Discover more than 1500 professional designs like these:
View
Hanukkah Presentation
View
Vintage Photo Album
View
Nature Presentation
View
Halloween Presentation
View
Tarot Presentation
View
Vaporwave presentation
View
Women's Presentation
Explore all templates
Transcript
PRESS START
VIDEO GAME
VIDEO GAME
PRESENTATION
232323
HI-SCORE
Summary
My last day of work at the synergy internship will be Friday August 2nd
© 20XX dom and nick GAMES
import random import os import colorama from colorama import Fore, Style import time import sys
Importing Modules
The game starts by importing several essential Python modules: random, os, colorama, time, and sys. The random module is used for generating random ship placements and computer moves. The os module provides functionality to clear the terminal screen between turns. colorama is used for adding color to terminal output, enhancing the visual feedback of hits, misses, and game outcomes. time is employed to create delays for user interaction effects, while sys is used for handling output directly to the terminal.
def print_slow(text): for char in text: sys.stdout.write(char) # Write each character to the terminal sys.stdout.flush() # Ensure the character is displayed immediately time.sleep(0.05) # Wait for a short time before printing the next character print() # Move to the next line after printing all characters def get_valid_input(prompt, min_val, max_val): while True: try: value = int(input(prompt)) # Read input from user and convert it to an integer if min_val <= value <= max_val: # Check if the value is within the specified range return value else: print(f"Please enter a number between {min_val} and {max_val}.") except ValueError: print("Invalid input. Please enter a number.")
Text Display and Input Handling
The print_slow function displays text character by character with a slight delay, creating a typing effect. This enhances the user experience by making the game's narrative more engaging. The get_valid_input function prompts the user for input and ensures that it falls within a specified range. It handles invalid input gracefully by providing feedback and re-prompting the user until valid input is received. This function ensures robust error handling and user interaction consistency.
def display_board(board, show_all=False): # Print column headers print(" " + " ".join(str(i) for i in range(1, len(board) + 1))) for i, row in enumerate(board): # Enumerate over rows in the board if show_all: # Display all cells including ship positions ('#', 'X', 'O') and empty cells ('~') row_display = " ".join(cell if cell in ['#', 'X', 'O'] else '~' for cell in row) else: # Hide ship positions; display only hits ('X') and misses ('O') with empty cells ('~') row_display = " ".join(cell if cell in ['X', 'O'] else '~' for cell in row) print(f"{i+1} {row_display}") # Print row number (e.g., "1") and row contents print()
Displaying the Board
The display_board function is responsible for rendering the game board. It can display the board with all ship positions visible or only the results of previous guesses. If show_all is True, it shows all cells including ship positions marked by #, hits marked by X, and misses marked by O. Otherwise, it only shows the hits and misses along with empty cells represented by ~. This function provides clear and informative visual feedback to players during the game.
def place_ship_manually(board, ship, size): while True: display_board(board, show_all=True) # Show the board to the user print(f"Placing {ship} (Size: {size})") # Prompt user about the ship placement # Get user input for starting row and column start_row = get_valid_input(f"Enter the start row (1-{len(board)}): ", 1, len(board)) - 1 start_col = get_valid_input(f"Enter the start column (1-{len(board)}): ", 1, len(board)) - 1 orientation = input("Enter orientation (H for horizontal, V for vertical): ").upper() # Check if the ship can be placed horizontally if orientation == 'H' and start_col + size <= len(board): if all(board[start_row][col] == '~' for col in range(start_col, start_col + size)): # Place the ship on the board for col in range(start_col, start_col + size): board[start_row][col] = '#' # Mark the ship's position return [(start_row, start_col), (start_row, start_col + size - 1)] # Return the ship's start and end coordinates # Check if the ship can be placed vertically elif orientation == 'V' and start_row + size <= len(board): if all(board[row][start_col] == '~' for row in range(start_row, start_row + size)): # Place the ship on the board for row in range(start_row, start_row + size): board[row][start_col] = '#' # Mark the ship's position return [(start_row, start_col), (start_row + size - 1, start_col)] # Return the ship's start and end coordinates # placement is invalid and prompt to try again print("Invalid placement. Try again.")
Placing Ships Manually
The place_ship_manually function is a great tool that lets players place their ships on the board by choosing the starting position and orientation. It makes sure that the ships are placed correctly without overlapping or going off the board. The function also helps decide if the ship should go horizontally or vertically, and then updates the board accordingly. This hands-on way of placing ships gives players more control over their strategy and adds a personal feel to the game setup.
def place_ship_randomly(board, size): while True: # Continuously loop until the ship is placed correctly row = random.randint(0, len(board) - 1) # Randomly select a row col = random.randint(0, len(board) - 1) # Randomly select a column orientation = random.choice(['H', 'V']) # Randomly choose orientation (horizontal or vertical) # Check if the ship can be placed horizontally if orientation == 'H' and col + size <= len(board): if all(board[row][c] == '~' for c in range(col, col + size)): # Place the ship on the board for c in range(col, col + size): board[row][c] = '#' # Mark the ship's position return [(row, col), (row, col + size - 1)] # Return the ship's start and end coordinates # Check if the ship can be placed vertically elif orientation == 'V' and row + size <= len(board): if all(board[r][col] == '~' for r in range(row, row + size)): # Place the ship on the board for r in range(row, row + size): board[r][col] = '#' # Mark the ship's position return [(row, col), (row + size - 1, col)] # Return the ship's start and end coordinates
Placing Ships Randomly
The place_ship_randomly function automates the ship placement process for the computer. It randomly selects a position and orientation for each ship and verifies that the placement is valid. This function ensures that ships are placed without overlapping or exceeding board limits, adding a layer of unpredictability to the computer's strategy. Random placement keeps the game challenging and fair by avoiding predictable ship arrangements.
def game_loop(player, computer): turns = 0 max_turns = 100 while player['hits'] < sum(ship["size"] for ship in player['ships']) and computer['hits'] < sum(ship["size"] for ship in computer['ships']) and turns < max_turns: os.system('cls' if os.name == 'nt' else 'clear') print("Your board:") display_board(player['board'], show_all=True) print("Enemy's board:") display_board(computer['board']) row = get_valid_input(f"Enter the row (1-{len(player['board'])}): ", 1, len(player['board'])) - 1 col = get_valid_input(f"Enter the column (1-{len(player['board'])}): ", 1, len(player['board'])) - 1 if (row, col) in player['guesses']: print("You've already guessed that location. Try again.") continue player['guesses'].append((row, col)) hit = False for i, (start, end) in enumerate(computer['ship_positions']): if (start[0] <= row <= end[0]) and (start[1] <= col <= end[1]): hit = True computer['board'][row][col] = 'X' player['hits'] += 1 print(Fore.GREEN + f"Hit at ({row+1}, {col+1})!" + Style.RESET_ALL) if player['hits'] == sum(ship["size"] for ship in player['ships']): print(Fore.GREEN + "You sank all the enemy ships!" + Style.RESET_ALL) break elif player['hits'] == sum(ship["size"] for ship in computer['ships']): print(Fore.GREEN + f"You sank the {computer['ships'][i]['name']}!" + Style.RESET_ALL) break if not hit: computer['board'][row][col] = 'O' print(Fore.RED + f"Miss at ({row+1}, {col+1})." + Style.RESET_ALL) row = random.randint(0, len(player['board']) - 1 col = random.randint(0, len(player['board']) - 1) while (row, col) in computer['guesses']: row = random.randint(0, len(player['board']) - 1) col = random.randint(0, len(player['board']) - 1) computer['guesses'].append((row, col))
Subtitle hit = False for i, (start, end) in enumerate(player['ship_positions']): if (start[0] <= row <= end[0]) and (start[1] <= col <= end[1]): hit = True player['board'][row][col] = 'X' computer['hits'] += 1 print(Fore.GREEN + f"The enemy hit your ship at ({row+1}, {col+1})!" + Style.RESET_ALL) if computer['hits'] == sum(ship["size"] for ship in computer['ships']): print(Fore.RED + "The enemy sank all your ships!" + Style.RESET_ALL) break elif computer['hits'] == sum(ship["size"] for ship in player['ships']): print(Fore.RED + f"The enemy sank your {player['ships'][i]['name']}!" + Style.RESET_ALL) break if not hit: player['board'][row][col] = 'O' print(Fore.RED + f"The enemy missed at ({row+1}, {col+1})." + Style.RESET_ALL) turns += 1 if player['hits'] >= sum(ship["size"] for ship in player['ships']): print(Fore.GREEN + "You won!" + Style.RESET_ALL) elif computer['hits'] >= sum(ship["size"] for ship in computer['ships']): print(Fore.RED + "The enemy won!" + Style.RESET_ALL) else: print(Fore.YELLOW + "The game ended in a draw." + Style.RESET_ALL)
Game Loop
The game_loop function is in charge of managing the gameplay mechanics by taking turns between the player and the computer, handling guesses, updating the board, and checking for hits or misses. It also deals with game-ending situations such as sinking all ships or reaching the maximum number of turns. The function gives visual feedback for hits, misses, and game outcomes to make the experience more dynamic. The loop keeps going until one side emerges victorious or the game ends in a draw.
if __name__ == "__main__": # Define the size of the grid and ensure it is at least 10x10 grid_size = get_valid_input("Enter the size of the grid (minimum 10x10): ", 10, 100) # Define the ships with their names and sizes ships = [ {"name": "Aircraft Carrier", "size": 5}, {"name": "Battleship", "size": 4}, {"name": "Submarine", "size": 3}, {"name": "Cruiser", "size": 3}, {"name": "Destroyer", "size": 2} ] # Initialize player and computer boards with empty cells ('~') player_board = [['~' for _ in range(grid_size)] for _ in range(grid_size)] computer_board = [['~' for _ in range(grid_size)] for _ in range(grid_size)] # Initialize player and computer dictionaries with their respective boards, ships, and other attributes player = { "board": player_board, "ships": ships, "ship_positions": [], # List to store positions of ships placed by the player "guesses": [], # List to store guesses made by the player "hits": 0 # Counter for the number of hits the player has made } computer = { "board": computer_board, "ships": ships, "ship_positions": [], # List to store positions of ships placed by the computer "guesses": [], # List to store guesses made by the computer "hits": 0 # Counter for the number of hits the computer has made } # Player names ships and places them manually on the board for ship in ships: ship["name"] = input(f"Enter a name for your {ship['name']} (Size: {ship['size']}): ") ship_position = place_ship_manually(player_board, ship["name"], ship["size"]) # Place ship manually player["ship_positions"].append(ship_position) # Add ship position to player's list # Computer places ships randomly on the board for ship in ships: ship_position = place_ship_randomly(computer_board, ship["size"]) # Place ship randomly computer["ship_positions"].append(ship_position) # Add ship position to computer's list # Start the game loop to begin the gameplay game_loop(player, computer)
# Print game results based on the outcome if player['hits'] == sum(ship["size"] for ship in player['ships']): print(Fore.GREEN + "Congratulations, you won!" + Style.RESET_ALL) # Player wins print(""" """) # Display win ASCII art elif computer['hits'] == sum(ship["size"] for ship in computer['ships']): print(Fore.RED + "You lost." + Style.RESET_ALL) # Computer wins print(""" """) # Display loss ASCII art else: print(Fore.YELLOW + "The game ended in a draw." + Style.RESET_ALL) # Game ends in a draw colorama.deinit()
BUSSINESS PROPSAL THE CODE