Battleship

35
# Importin g the Operativ e System module import os # Importing the random module import random # Importing the time module import time """ GAME SPECIFIC AUTHOR CONFIGURATION """ # Application Name app_name = "BattleShip Multiplayer" # Application Version app_version = "1.3" # Application Author app_author = "CodeBarbarian" # Function to clear the console screen on *nix and windows systems def clearScreen(): os.system(['clear', 'cls'][os.name == 'nt']) """"""""""""""""""""""""""""""""" GAME SPECIFIC VARIABLES BELOW """"""""""""""""""""""""""""""""" # Player boards player1_board = [] player2_board = [] # Player Names player1_name = "" player2_name = "" # Overall Game Conditions gameWon = False gameTurns = 1 gameWinner = "" gameLoser = "" # When the game begins in seconds gameStart_time = 0 # When the game ends in seconds gameEnd_time = 0 # Player one's ship location player1_ship_row = 0 player1_ship_col = 0 # Player two's ship location player2_ship_row = 0

description

Battleship.py, python web app code

Transcript of Battleship

# Importing the Operative System module

import os

# Importing the random module

import random

# Importing the time module

import time

"""

GAME SPECIFIC AUTHOR CONFIGURATION

"""

# Application Name

app_name = "BattleShip Multiplayer"

# Application Version

app_version = "1.3"

# Application Author

app_author = "CodeBarbarian"

# Function to clear the console screen on *nix and windows systems

def clearScreen():

os.system(['clear', 'cls'][os.name == 'nt'])

"""""""""""""""""""""""""""""""""

GAME SPECIFIC VARIABLES BELOW

"""""""""""""""""""""""""""""""""

# Player boards

player1_board = []

player2_board = []

# Player Names

player1_name = ""

player2_name = ""

# Overall Game Conditions

gameWon = False

gameTurns = 1

gameWinner = ""

gameLoser = ""

# When the game begins in seconds

gameStart_time = 0

# When the game ends in seconds

gameEnd_time = 0

# Player one's ship location

player1_ship_row = 0

player1_ship_col = 0

# Player two's ship location

player2_ship_row = 0

player2_ship_col = 0

# How large should the battlefield be?

boardColRow = 10

# Ship Character

shipChar = "S"

# Fired character

firedChar = "X"

# Board Character

boardChar = " "

# Ocean Character

oceanChar = "O"

"""""""""""""""""""""""""""""""""

GAME SPECIFIC DEFINITIONS BELOW

"""""""""""""""""""""""""""""""""

def gameLogo():

print '''

______ _ _ _ _____ _ _

| ___ \ | | | | | | / ___| | (_)

| |_/ / __ _| |_| |_| | ___\ `--.| |__ _ _ __

| ___ \/ _` | __| __| |/ _ \`--. | '_ \| | '_ \

| |_/ | (_| | |_| |_| | __/\__/ | | | | | |_) |

\____/ \__,_|\__|\__|_|\___\____/|_| |_|_| .__/

| |

|_|

'''

print " Version " + str(app_version)

print " Created by " + str(app_author)

print

print

def randomizePosition(board):

return random.randint(0, len(player1_board) -1)

def printPlayerBoard(board, row, col, boardChar, shipChar):

board[row][col] = str(shipChar)

for i in board:

print str(boardChar).join(i)

board[row][col] = oceanChar

def printPlayerOppositeBoard(board, boardChar):

for i in board:

print str(boardChar).join(i)

def acknowledge(player1name, player2name):

clearScreen()

gameLogo()

print

print

return raw_input(str(player1name) + "'s turn! " + str(player2name) + ", turn away from the screen!" + " (When ready, hit ENTER)")

def acknowledgeFailure():

return raw_input("To continue press enter...")

def displayMessage(errNumber, playername=""):

message = {

1: "Congratz! You sunk " + str(playername) + "'s battleship!",

2: "We are at sea " + str(playername) + ", why are you targeting at land?",

3: "You have already shoot there!",

4: str(playername) + ": Haha! You've missed my battleship!",

5: str(playername) + "'s board with your fired attempts!",

6: "Your board with ship location and " + str(playername) + "'s fired attempts!"

}

return str(message[errNumber])

"""""""""""""""""""""""""""""""""

GAME SPECIFIC LOGIC

"""""""""""""""""""""""""""""""""

# Appending the vowel oceanChar to the boards

for i in range(boardColRow):

player1_board.append([str(oceanChar)] * boardColRow)

player2_board.append([str(oceanChar)] * boardColRow)

# Setting the position of player one's ship

player1_ship_row = randomizePosition(player1_board)

player1_ship_col = randomizePosition(player1_board)

# Setting the position of player two's ship

player2_ship_row = randomizePosition(player2_board)

player2_ship_col = randomizePosition(player2_board)

"""""""""""""""""""""""""""""""""

GAME START

"""""""""""""""""""""""""""""""""

# Clear the screen to make it prettier

clearScreen()

# Print the game logo

gameLogo()

# Set the player names

player1_name = raw_input("Player One's Name: ")

player2_name = raw_input("Player Two's Name: ")

# Begin the take time sequence

gameStart_time = time.time()

# The gameloop

while 1:

if gameTurns = boardColRow) \

or (player1_guessedCol < 0 or player1_guessedCol >= boardColRow):

print

print displayMessage(2)

print

acknowledgeFailure()

acknowledge(player2_name, player1_name)

elif player2_board[player1_guessedRow][player1_guessedCol] == str(firedChar):

print

print displayMessage(3)

print

acknowledgeFailure()

acknowledge(player2_name, player1_name)

else:

print

print displayMessage(4, player2_name)

print

acknowledgeFailure()

player2_board[player1_guessedRow][player1_guessedCol] = str(firedChar)

acknowledge(player2_name, player1_name)

"""

Player Two's Gaming Conditions

"""

clearScreen()

gameLogo()

print

print "Number of turns played: " + str(gameTurns)

print

print str(player2_name) + "'s turn!"

print

print displayMessage(5, player1_name)

# Print Player 2's Ocean without the ship on it

printPlayerOppositeBoard(player1_board, boardChar)

print

print

print displayMessage(6, player1_name)

# Print Player 1's Ocean with ship on it

printPlayerBoard(player2_board, player2_ship_row, player2_ship_col, boardChar, shipChar)

# General Game Conditions

print

print

player2_guessedRow = input(str(player2_name) + " Guess Row: ")

player2_guessedCol = input(str(player2_name) + " Guess Col: ")

if player2_guessedRow == player1_ship_row and player2_guessedCol == player1_ship_col:

print displayMessage(1, player1_name)

gameWon = True

gameWinner = str(player2_name)

gameLoser = str(player1_name)

break

else:

if (player2_guessedRow < 0 or player2_guessedRow >= boardColRow) \

or (player2_guessedCol < 0 or player2_guessedCol >= boardColRow):

print

print displayMessage(2)

print

acknowledgeFailure()

acknowledge(player2_name, player2_name)

elif player1_board[player2_guessedRow][player2_guessedCol] == str(firedChar):

print

print displayMessage(3)

print

acknowledgeFailure()

acknowledge(player2_name, player2_name)

else:

print

print displayMessage(4, player1_name)

print

acknowledgeFailure()

player1_board[player2_guessedRow][player2_guessedCol] = str(firedChar)

acknowledge(player2_name, player2_name)

gameTurns += 1

if gameWon:

# End the take time sequence

gameEnd_time = time.time()

# Print congratulation message

print "Congratulations " + str(gameWinner) + " for shooting down " + str(gameLoser) + "'s ship! in " + str(gameTurns) + " turns!"

print

# Print game time

print "The game took, " + str(gameEnd_time - gameStart_time) + " seconds to play!"

import copy, random

def print_board(s,board):

# WARNING: This function was crafted with a lot of attention. Please be aware that any# modifications to this function will result in a poor output of the board # layout. You have been warn.

#find out if you are printing the computer or user boardplayer = "Computer"if s == "u":player = "User"print "The " + player + "'s board look like this: \n"

#print the horizontal numbersprint " ",for i in range(10):print " " + str(i+1) + " ",print "\n"

for i in range(10):#print the vertical line numberif i != 9: print str(i+1) + " ",else:print str(i+1) + " ",

#print the board values, and cell dividersfor j in range(10):if board[i][j] == -1:print ' ',elif s == "u":print board[i][j],elif s == "c":if board[i][j] == "*" or board[i][j] == "$":print board[i][j],else:print " ",if j != 9:print " | ",print#print a horizontal lineif i != 9:print " ----------------------------------------------------------"else: print

def user_place_ships(board,ships):

for ship in ships.keys():

#get coordinates from user and vlidate the postionvalid = Falsewhile(not valid):

print_board("u",board)print "Placing a/an " + shipx,y = get_coor()ori = v_or_h()valid = validate(board,ships[ship],x,y,ori)if not valid:print "Cannot place a ship there.\nPlease take a look at the board and try again."raw_input("Hit ENTER to continue")

#place the shipboard = place_ship(board,ships[ship],ship[0],ori,x,y)print_board("u",board)raw_input("Done placing user ships. Hit ENTER to continue")return board

def computer_place_ships(board,ships):

for ship in ships.keys():#genreate random coordinates and vlidate the postionvalid = Falsewhile(not valid):

x = random.randint(1,10)-1y = random.randint(1,10)-1o = random.randint(0,1)if o == 0: ori = "v"else:ori = "h"valid = validate(board,ships[ship],x,y,ori)

#place the shipprint "Computer placing a/an " + shipboard = place_ship(board,ships[ship],ship[0],ori,x,y)return board

def place_ship(board,ship,s,ori,x,y):

#place ship based on orientationif ori == "v":for i in range(ship):board[x+i][y] = selif ori == "h":for i in range(ship):board[x][y+i] = s

return boarddef validate(board,ship,x,y,ori):

#validate the ship can be placed at given coordinatesif ori == "v" and x+ship > 10:return Falseelif ori == "h" and y+ship > 10:return Falseelse:if ori == "v":for i in range(ship):if board[x+i][y] != -1:return Falseelif ori == "h":for i in range(ship):if board[x][y+i] != -1:return Falsereturn True

def v_or_h():

#get ship orientation from userwhile(True):user_input = raw_input("vertical or horizontal (v,h) ? ")if user_input == "v" or user_input == "h":return user_inputelse:print "Invalid input. Please only enter v or h"

def get_coor():while (True):user_input = raw_input("Please enter coordinates (row,col) ? ")try:#see that user entered 2 values seprated by commacoor = user_input.split(",")if len(coor) != 2:raise Exception("Invalid entry, too few/many coordinates.");

#check that 2 values are integerscoor[0] = int(coor[0])-1coor[1] = int(coor[1])-1

#check that values of integers are between 1 and 10 for both coordinatesif coor[0] > 9 or coor[0] < 0 or coor[1] > 9 or coor[1] < 0:raise Exception("Invalid entry. Please use values between 1 to 10 only.")

#if everything is ok, return coordinatesreturn coorexcept ValueError:print "Invalid entry. Please enter only numeric values for coordinates"except Exception as e:print e

def make_move(board,x,y):#make a move on the board and return the result, hit, miss or try again for repeat hitif board[x][y] == -1:return "miss"elif board[x][y] == '*' or board[x][y] == '$':return "try again"else:return "hit"

def user_move(board):#get coordinates from the user and try to make move#if move is a hit, check ship sunk and win conditionwhile(True):x,y = get_coor()res = make_move(board,x,y)if res == "hit":print "Hit at " + str(x+1) + "," + str(y+1)check_sink(board,x,y)board[x][y] = '$'if check_win(board):return "WIN"elif res == "miss":print "Sorry, " + str(x+1) + "," + str(y+1) + " is a miss."board[x][y] = "*"elif res == "try again":print "Sorry, that coordinate was already hit. Please try again"

if res != "try again":return board

def computer_move(board):#generate user coordinates from the user and try to make move#if move is a hit, check ship sunk and win conditionwhile(True):x = random.randint(1,10)-1y = random.randint(1,10)-1res = make_move(board,x,y)if res == "hit":print "Hit at " + str(x+1) + "," + str(y+1)check_sink(board,x,y)board[x][y] = '$'if check_win(board):return "WIN"elif res == "miss":print "Sorry, " + str(x+1) + "," + str(y+1) + " is a miss."board[x][y] = "*"

if res != "try again":return boarddef check_sink(board,x,y):

#figure out what ship was hitif board[x][y] == "A":ship = "Aircraft Carrier"elif board[x][y] == "B":ship = "Battleship"elif board[x][y] == "S":ship = "Submarine" elif board[x][y] == "D":ship = "Destroyer"elif board[x][y] == "P": ship = "Patrol Boat"#mark cell as hit and check if sunkboard[-1][ship] -= 1if board[-1][ship] == 0:print ship + " Sunk"

def check_win(board):#simple for loop to check all cells in 2d board#if any cell contains a char that is not a hit or a miss return falsefor i in range(10):for j in range(10):if board[i][j] != -1 and board[i][j] != '*' and board[i][j] != '$':return Falsereturn True

def main():

def gameLogo():

print '''

______ _ _ _ _____ _ _

| ___ \ | | | | | | / ___| | (_)

| |_/ / __ _| |_| |_| | ___\ `--.| |__ _ _ __

| ___ \/ _` | __| __| |/ _ \`--. | '_ \| | '_ \

| |_/ | (_| | |_| |_| | __/\__/ | | | | | |_) |

\____/ \__,_|\__|\__|_|\___\____/|_| |_|_| .__/

| |

|_|

'''

print " Version " + str(app_version)

print " Created by " + str(app_author)

print

print

gameLogo()#types of shipsships = {"Aircraft Carrier":5, "Battleship":4, "Submarine":3, "Destroyer":3, "Patrol Boat":2}

#setup blank 10x10 boardboard = []for i in range(10):board_row = []for j in range(10):board_row.append(-1)board.append(board_row)

#setup user and computer boardsuser_board = copy.deepcopy(board)comp_board = copy.deepcopy(board)

#add ships as last element in the arrayuser_board.append(copy.deepcopy(ships))comp_board.append(copy.deepcopy(ships))

#ship placementuser_board = user_place_ships(user_board,ships)comp_board = computer_place_ships(comp_board,ships)

#game main loopwhile(1):

#user moveprint_board("c",comp_board)comp_board = user_move(comp_board)

#check if user wonif comp_board == "WIN":print "User WON! :)"quit()#display current computer boardprint_board("c",comp_board)raw_input("To end user turn hit ENTER")

#computer moveuser_board = computer_move(user_board)#check if computer moveif user_board == "WIN":print "Computer WON! :("quit()#display user boardprint_board("u",user_board)raw_input("To end computer turn hit ENTER")if __name__=="__main__":main()

import copy, random

# Application Nameapp_name = "BattleShip Multiplayer"# Application Versionapp_version = "1.3"# Application Authorapp_author = "Samudhbhav"

def print_board(s,board):

# WARNING: This function was crafted with a lot of attention. Please be aware that any# modifications to this function will result in a poor output of the board # layout. You have been warn.

#find out if you are printing the computer or user boardplayer = "Computer"if s == "u":player = "User"print "The " + player + "'s board look like this: \n"

#print the horizontal numbersprint " ",for i in range(10):print " " + str(i+1) + " ",print "\n"

for i in range(10):#print the vertical line numberif i != 9: print str(i+1) + " ",else:print str(i+1) + " ",

#print the board values, and cell dividersfor j in range(10):if board[i][j] == -1:print ' ',elif s == "u":print board[i][j],elif s == "c":if board[i][j] == "*" or board[i][j] == "$":print board[i][j],else:print " ",if j != 9:print " | ",print#print a horizontal lineif i != 9:print " ----------------------------------------------------------"else: print

def user_place_ships(board,ships):

for ship in ships.keys():

#get coordinates from user and vlidate the postionvalid = Falsewhile(not valid):

print_board("u",board)print "Placing a/an " + shipx,y = get_coor()ori = v_or_h()valid = validate(board,ships[ship],x,y,ori)if not valid:print "Cannot place a ship there.\nPlease take a look at the board and try again."raw_input("Hit ENTER to continue")

#place the shipboard = place_ship(board,ships[ship],ship[0],ori,x,y)print_board("u",board)raw_input("Done placing user ships. Hit ENTER to continue")return board

def computer_place_ships(board,ships):

for ship in ships.keys():#genreate random coordinates and vlidate the postionvalid = Falsewhile(not valid):

x = random.randint(1,10)-1y = random.randint(1,10)-1o = random.randint(0,1)if o == 0: ori = "v"else:ori = "h"valid = validate(board,ships[ship],x,y,ori)

#place the shipprint "Computer placing a/an " + shipboard = place_ship(board,ships[ship],ship[0],ori,x,y)return board

def place_ship(board,ship,s,ori,x,y):

#place ship based on orientationif ori == "v":for i in range(ship):board[x+i][y] = selif ori == "h":for i in range(ship):board[x][y+i] = s

return boarddef validate(board,ship,x,y,ori):

#validate the ship can be placed at given coordinatesif ori == "v" and x+ship > 10:return Falseelif ori == "h" and y+ship > 10:return Falseelse:if ori == "v":for i in range(ship):if board[x+i][y] != -1:return Falseelif ori == "h":for i in range(ship):if board[x][y+i] != -1:return Falsereturn True

def v_or_h():

#get ship orientation from userwhile(True):user_input = raw_input("vertical or horizontal (v,h) ? ")if user_input == "v" or user_input == "h":return user_inputelse:print "Invalid input. Please only enter v or h"

def get_coor():while (True):user_input = raw_input("Please enter coordinates (row,col) ? ")try:#see that user entered 2 values seprated by commacoor = user_input.split(",")if len(coor) != 2:raise Exception("Invalid entry, too few/many coordinates.");

#check that 2 values are integerscoor[0] = int(coor[0])-1coor[1] = int(coor[1])-1

#check that values of integers are between 1 and 10 for both coordinatesif coor[0] > 9 or coor[0] < 0 or coor[1] > 9 or coor[1] < 0:raise Exception("Invalid entry. Please use values between 1 to 10 only.")

#if everything is ok, return coordinatesreturn coorexcept ValueError:print "Invalid entry. Please enter only numeric values for coordinates"except Exception as e:print e

def make_move(board,x,y):#make a move on the board and return the result, hit, miss or try again for repeat hitif board[x][y] == -1:return "miss"elif board[x][y] == '*' or board[x][y] == '$':return "try again"else:return "hit"

def user_move(board):#get coordinates from the user and try to make move#if move is a hit, check ship sunk and win conditionwhile(True):x,y = get_coor()res = make_move(board,x,y)if res == "hit":print "Hit at " + str(x+1) + "," + str(y+1)check_sink(board,x,y)board[x][y] = '$'if check_win(board):return "WIN"elif res == "miss":print "Sorry, " + str(x+1) + "," + str(y+1) + " is a miss."board[x][y] = "*"elif res == "try again":print "Sorry, that coordinate was already hit. Please try again"

if res != "try again":return board

def computer_move(board):#generate user coordinates from the user and try to make move#if move is a hit, check ship sunk and win conditionwhile(True):x = random.randint(1,10)-1y = random.randint(1,10)-1res = make_move(board,x,y)if res == "hit":print "Hit at " + str(x+1) + "," + str(y+1)check_sink(board,x,y)board[x][y] = '$'if check_win(board):return "WIN"elif res == "miss":print "Sorry, " + str(x+1) + "," + str(y+1) + " is a miss."board[x][y] = "*"

if res != "try again":return boarddef check_sink(board,x,y):

#figure out what ship was hitif board[x][y] == "A":ship = "Aircraft Carrier"elif board[x][y] == "B":ship = "Battleship"elif board[x][y] == "S":ship = "Submarine" elif board[x][y] == "D":ship = "Destroyer"elif board[x][y] == "P": ship = "Patrol Boat"#mark cell as hit and check if sunkboard[-1][ship] -= 1if board[-1][ship] == 0:print ship + " Sunk"

def check_win(board):#simple for loop to check all cells in 2d board#if any cell contains a char that is not a hit or a miss return falsefor i in range(10):for j in range(10):if board[i][j] != -1 and board[i][j] != '*' and board[i][j] != '$':return Falsereturn True

def gameLogo(): print ''' ______ _ _ _ _____ _ _ | ___ \ | | | | | | / ___| | (_) | |_/ / __ _| |_| |_| | ___\ `--.| |__ _ _ __ | ___ \/ _` | __| __| |/ _ \`--. | '_ \| | '_ \ | |_/ | (_| | |_| |_| | __/\__/ | | | | | |_) | \____/ \__,_|\__|\__|_|\___\____/|_| |_|_| .__/ | | |_|

''' print " Version " + str(app_version) print " Created by " + str(app_author) print print

def main():

gameLogo() #types of shipsships = {"Aircraft Carrier":5, "Battleship":4, "Submarine":3, "Destroyer":3, "Patrol Boat":2}

#setup blank 10x10 boardboard = []for i in range(10):board_row = []for j in range(10):board_row.append(-1)board.append(board_row)

#setup user and computer boardsuser_board = copy.deepcopy(board)comp_board = copy.deepcopy(board)

#add ships as last element in the arrayuser_board.append(copy.deepcopy(ships))comp_board.append(copy.deepcopy(ships))

#ship placementuser_board = user_place_ships(user_board,ships)comp_board = computer_place_ships(comp_board,ships)

#game main loopwhile(1):

#user moveprint_board("c",comp_board)comp_board = user_move(comp_board)

#check if user wonif comp_board == "WIN":print "User WON! :)"quit()#display current computer boardprint_board("c",comp_board)raw_input("To end user turn hit ENTER")

#computer moveuser_board = computer_move(user_board)#check if computer moveif user_board == "WIN":print "Computer WON! :("quit()#display user boardprint_board("u",user_board)raw_input("To end computer turn hit ENTER")if __name__=="__main__":main()