Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #Battleship
- # Specification:
- # Print an introduction
- # Place ships
- # get attacks from AI and user
- # find out who wins if:
- # all of someones ships are destroyed
- from random import randrange
- def printIntro():
- print("This program simulates a game of battleship between the player and the computer")
- print("Each player places ships and then takes turns guessing where the enemy ships are to attack")
- print("A ship is sunk if all pieces of it are hit")
- def printBoard(whosBoard, board):
- print("{0:25}".format(whosBoard))
- for i in range(len(board)):
- line = ""
- for j in range(len(board)):
- line += board[i][j]
- print(line)
- def placeAIShips(board, shipList):
- for ship in shipList:
- if (ship == "aircarrier"):
- length = 5
- elif (ship == "cruiser"):
- length = 3
- elif (ship == "destroyer"):
- length = 2
- else:
- print("invalid ship")
- validLoc = False
- while (not validLoc):
- x = randrange(0,7)
- y = randrange(0,7)
- direction = randrange(0, 2)
- if (direction == 0):
- direction = "v"
- else:
- direction = "h"
- validLoc = validateBoard(board, length, x, y, direction)
- board = placeShip(board, direction, ship, length, x, y)
- return board
- def aIAttack(myFleet, hitList):
- valid = False
- while (not valid):
- x = randrange(0,7)
- y = randrange(0,7)
- if myFleet[x][y] != "X":
- valid = True
- myFleet[x][y] = "X"
- hitList.append((x,y))
- #print(hitList)
- return myFleet
- def isCheating(hitList):
- #read the array from the file
- fileName = input("I know you're cheating where did you save the results?!: ")
- myFile = open(fileName, "r")
- myFleet = []
- for line in myFile:
- myFleet.append(line.split())
- #print(myFleet)
- #check if it matches up
- for i, j in hitList:
- if myFleet[i][j] != "X":
- return True #he caught us cheating!
- return False #Why would he think we would cheat?
- def placeMyFleet(board, shipList):
- for ship in shipList:
- if (ship == "aircarrier"):
- length = 5
- elif (ship == "cruiser"):
- length = 3
- elif (ship == "destroyer"):
- length = 2
- else:
- print("invalid ship")
- print("Placing:", ship, "with length of", length)
- validLoc = False
- while (not validLoc):
- printBoard("",board)
- x, y = getCoords()
- direction = getDirection()
- validLoc = validateBoard(board, length, x, y, direction)
- if (not validLoc):
- print("Cannot place a ship there")
- print("Please a choose a different location")
- #otherwise we place the ship!
- board = placeShip(board, direction, ship, length, x, y)
- printBoard("Your final board: ", board)
- return board
- def userMove(board, hitBoard):
- valid = False
- while (not valid):
- x, y = getCoords()
- if hitBoard[x][y] != "*":
- userAnswer = input("You've already attacked here. Do you want to choose a new attack location? [Y/N] ")
- if (userAnswer.upper() == "Y"):
- valid = False
- elif (userAnswer.upper() == "N"):
- valid = True
- else:
- print("Invalid Answer")
- valid = False
- else:
- valid = True
- if board[x][y] == "*":
- hitBoard[x][y] = "M"
- else:
- hitBoard[x][y] = board[x][y]
- return hitBoard
- def placeShip(board, userDir, ship, shipLength, x, y):
- if (userDir == "v"):
- for i in range(shipLength):
- board[x+i][y] = ship[0].upper()
- elif (userDir == "h"):
- for i in range(shipLength):
- board[x][y+i] = ship[0].upper()
- return board
- def validateBoard(board, shipLength, xCo, yCo, userDir): #check if its possible to place ship in users location
- if (userDir == "v" and xCo + shipLength >= 7):
- return False
- elif (userDir == "h" and yCo + shipLength >= 7):
- return False
- else:
- if (userDir == "v"):
- for i in range(shipLength):
- if (board[xCo+i][yCo] != "*"):
- return False
- else:
- for i in range(shipLength):
- if (board[xCo][yCo+i] != "*"):
- return False
- return True
- def getCoords():
- valid = False
- while (not valid):
- x = int(eval(input("What is the x coordinate? ")))
- y = int(eval(input("What is the y coordinate? ")))
- if (x <= 7 and y <= 7):
- valid = True
- else:
- print("One or both of your coordinates are greater than 7 (the max board size)")
- return y, x
- def checkWin(myHits):
- totalHits = 0
- for i in range(7):
- for j in range(7):
- if myHits[i][j] == "A":
- totalHits += 1
- elif myHits[i][j] == "C":
- totalHits += 1
- elif myHits[i][j] == "D":
- totalHits += 1
- if (totalHits == 2):
- return False #we're still playing
- return True #game is over
- def getDirection():
- valid = False
- while (not valid):
- userDir = input("What direction is ship going? Vertical(goes down) [v] or Horizontal(goes to the right) [h]? ")
- if (userDir == "v" or userDir == "h"):
- valid = True
- else:
- print("Invalid Input, please enter either v or h")
- return userDir
- def checkAIWin(myFleet):
- for x in range(7):
- for y in range(7):
- if (myFleet[x][y] != "*" and myFleet[x][y] != "X"):
- return True #we're still playing
- return False #game is over
- def printBoardToText(board):
- fileName = input("What would you like the save file to be called?: ")
- myFile = open(fileName, "w")
- for i in range(len(board)):
- line = ""
- for j in range(len(board)):
- line += board[i][j] + " "
- print(line, file=myFile)
- def main():
- #column -> row
- hitList = [] #list of numbers where ai has attacked
- listOfShips = ["aircarrier", "cruiser", "destroyer"]
- myFleet = [["*","*","*","*","*","*","*"],["*","*","*","*","*","*","*"],["*","*","*","*","*","*","*"],["*","*","*","*","*","*","*"],["*","*","*","*","*","*","*"],["*","*","*","*","*","*","*"],["*","*","*","*","*","*","*"]]
- myHits = [["*","*","*","*","*","*","*"],["*","*","*","*","*","*","*"],["*","*","*","*","*","*","*"],["*","*","*","*","*","*","*"],["*","*","*","*","*","*","*"],["*","*","*","*","*","*","*"],["*","*","*","*","*","*","*"]]
- aIBoard = [["*","*","*","*","*","*","*"],["*","*","*","*","*","*","*"],["*","*","*","*","*","*","*"],["*","*","*","*","*","*","*"],["*","*","*","*","*","*","*"],["*","*","*","*","*","*","*"],["*","*","*","*","*","*","*"]]
- printIntro()
- myFleet = placeMyFleet(myFleet, ["destroyer"])
- aIBoard = placeAIShips(aIBoard, ["destroyer"])
- printBoard("AI Board:", aIBoard) #this is good to make sure your hits are okay
- playing = True
- while (playing):
- print("You're Attacking!")
- printBoard("Your Hits:", myHits)
- userMove(aIBoard, myHits)
- playing = checkWin(myHits)
- if (not playing):
- print("You win!")
- printBoardToText(myFleet)
- print("I don't believe you! Show me your position!")
- angry = isCheating(hitList)
- if (angry):
- print("I cant believe you'd do this to me, after all we've been through! Just go and betray my trust like that as if we meant nothing!")
- else:
- print("Doesn't look like you cheated. Fine, you've won fair and square!")
- if (playing):
- print("Computer is Attacking")
- myFleet = aIAttack(myFleet, hitList)
- printBoard("After AI's turn:", myFleet)
- playing = checkAIWin(myFleet)
- if(not playing):
- print("Computer wins!")
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement