Advertisement
Guest User

Untitled

a guest
Mar 5th, 2015
191
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 8.37 KB | None | 0 0
  1.  
  2. #Battleship
  3. # Specification:
  4. #     Print an introduction
  5. #     Place ships
  6. #     get attacks from AI and user
  7. #     find out who wins if:
  8. #         all of someones ships are destroyed
  9.  
  10.  
  11. from random import randrange
  12. def printIntro():
  13.     print("This program simulates a game of battleship between the player and the computer")
  14.     print("Each player places ships and then takes turns guessing where the enemy ships are to attack")
  15.     print("A ship is sunk if all pieces of it are hit")
  16.      
  17.  
  18. def printBoard(whosBoard, board):
  19.     print("{0:25}".format(whosBoard))
  20.     for i in range(len(board)):
  21.         line = ""
  22.         for j in range(len(board)):
  23.             line += board[i][j]
  24.         print(line)
  25.  
  26. def placeAIShips(board, shipList):
  27.     for ship in shipList:
  28.         if (ship == "aircarrier"):
  29.             length = 5
  30.         elif (ship == "cruiser"):
  31.             length = 3
  32.         elif (ship == "destroyer"):
  33.             length = 2
  34.         else:
  35.             print("invalid ship")
  36.          
  37.         validLoc = False
  38.         while (not validLoc):
  39.             x = randrange(0,7)
  40.             y = randrange(0,7)
  41.             direction = randrange(0, 2)
  42.             if (direction == 0):
  43.                 direction = "v"
  44.             else:
  45.                 direction = "h"
  46.  
  47.             validLoc = validateBoard(board, length, x, y, direction)
  48.         board = placeShip(board, direction, ship, length, x, y)
  49.     return board
  50.  
  51. def aIAttack(myFleet, hitList):
  52.     valid = False
  53.     while (not valid):
  54.         x = randrange(0,7)
  55.         y = randrange(0,7)
  56.         if myFleet[x][y] != "X":
  57.             valid = True
  58.     myFleet[x][y] = "X"
  59.     hitList.append((x,y))
  60.     #print(hitList)
  61.     return myFleet
  62.  
  63. def isCheating(hitList):
  64.     #read the array from the file
  65.     fileName = input("I know you're cheating where did you save the results?!: ")
  66.     myFile = open(fileName, "r")
  67.     myFleet = []
  68.     for line in myFile:
  69.         myFleet.append(line.split())
  70.     #print(myFleet)
  71.    
  72.     #check if it matches up
  73.     for i, j in hitList:
  74.         if myFleet[i][j] != "X":
  75.             return True #he caught us cheating!
  76.     return False #Why would he think we would cheat?
  77.  
  78.  
  79. def placeMyFleet(board, shipList):
  80.     for ship in shipList:
  81.         if (ship == "aircarrier"):
  82.             length = 5
  83.         elif (ship == "cruiser"):
  84.             length = 3
  85.         elif (ship == "destroyer"):
  86.             length = 2
  87.         else:
  88.             print("invalid ship")
  89.         print("Placing:", ship, "with length of", length)  
  90.         validLoc = False
  91.         while (not validLoc):
  92.               printBoard("",board)
  93.               x, y = getCoords()
  94.               direction = getDirection()
  95.               validLoc = validateBoard(board, length, x, y, direction)
  96.               if (not validLoc):
  97.                 print("Cannot place a ship there")
  98.                 print("Please a choose a different location")
  99.  
  100.         #otherwise we place the ship!
  101.         board = placeShip(board, direction, ship, length, x, y)
  102.     printBoard("Your final board: ", board)
  103.     return board
  104.  
  105. def userMove(board, hitBoard):  
  106.     valid = False
  107.     while (not valid):
  108.         x, y = getCoords()
  109.         if hitBoard[x][y] != "*":
  110.             userAnswer = input("You've already attacked here. Do you want to choose a new attack location? [Y/N] ")
  111.             if (userAnswer.upper() == "Y"):
  112.                 valid = False
  113.             elif (userAnswer.upper() == "N"):
  114.                   valid = True
  115.             else:
  116.                   print("Invalid Answer")
  117.                   valid = False
  118.         else:
  119.             valid = True
  120.      
  121.     if board[x][y] == "*":
  122.         hitBoard[x][y] = "M"
  123.     else:
  124.         hitBoard[x][y] = board[x][y]
  125.     return hitBoard
  126.  
  127. def placeShip(board, userDir, ship, shipLength, x, y):
  128.     if (userDir == "v"):
  129.         for i in range(shipLength):
  130.             board[x+i][y] = ship[0].upper()
  131.     elif (userDir == "h"):
  132.         for i in range(shipLength):
  133.             board[x][y+i] = ship[0].upper()
  134.     return board
  135.            
  136. def validateBoard(board, shipLength, xCo, yCo, userDir): #check if its possible to place ship in users location
  137.     if (userDir == "v" and xCo + shipLength >= 7):
  138.         return False
  139.     elif (userDir == "h" and yCo + shipLength >= 7):
  140.         return False
  141.     else:
  142.         if (userDir == "v"):
  143.             for i in range(shipLength):
  144.                 if (board[xCo+i][yCo] != "*"):
  145.                     return False
  146.         else:
  147.             for i in range(shipLength):
  148.                 if (board[xCo][yCo+i] != "*"):
  149.                     return False
  150.     return True
  151.  
  152.  
  153. def getCoords():
  154.     valid = False
  155.  
  156.     while (not valid):
  157.         x = int(eval(input("What is the x coordinate? ")))
  158.         y = int(eval(input("What is the y coordinate? ")))
  159.         if (x <= 7 and y <= 7):
  160.             valid = True
  161.         else:
  162.             print("One or both of your coordinates are greater than 7 (the max board size)")
  163.     return y, x
  164.  
  165. def checkWin(myHits):
  166.     totalHits = 0
  167.     for i in range(7):
  168.         for j in range(7):
  169.             if myHits[i][j] == "A":
  170.                 totalHits += 1
  171.                  
  172.             elif myHits[i][j] == "C":
  173.                 totalHits += 1
  174.                  
  175.             elif myHits[i][j] == "D":
  176.                 totalHits += 1
  177.                  
  178.  
  179.     if (totalHits == 2):
  180.         return False #we're still playing
  181.     return True #game is over
  182.  
  183.  
  184.  
  185. def getDirection():
  186.     valid = False
  187.     while (not valid):
  188.         userDir = input("What direction is ship going? Vertical(goes down) [v] or Horizontal(goes to the right) [h]? ")
  189.         if (userDir == "v" or userDir == "h"):
  190.             valid = True
  191.         else:
  192.             print("Invalid Input, please enter either v or h")
  193.     return userDir
  194.  
  195. def checkAIWin(myFleet):
  196.     for x in range(7):
  197.         for y in range(7):
  198.             if (myFleet[x][y] != "*" and myFleet[x][y] != "X"):
  199.                 return True #we're still playing
  200.     return False #game is over
  201.  
  202. def printBoardToText(board):
  203.     fileName = input("What would you like the save file to be called?: ")
  204.     myFile = open(fileName, "w")
  205.     for i in range(len(board)):
  206.         line = ""
  207.         for j in range(len(board)):
  208.             line += board[i][j] + " "
  209.         print(line, file=myFile)  
  210.  
  211. def main():
  212.     #column -> row
  213.     hitList = [] #list of numbers where ai has attacked
  214.     listOfShips = ["aircarrier", "cruiser", "destroyer"]
  215.     myFleet = [["*","*","*","*","*","*","*"],["*","*","*","*","*","*","*"],["*","*","*","*","*","*","*"],["*","*","*","*","*","*","*"],["*","*","*","*","*","*","*"],["*","*","*","*","*","*","*"],["*","*","*","*","*","*","*"]]
  216.     myHits = [["*","*","*","*","*","*","*"],["*","*","*","*","*","*","*"],["*","*","*","*","*","*","*"],["*","*","*","*","*","*","*"],["*","*","*","*","*","*","*"],["*","*","*","*","*","*","*"],["*","*","*","*","*","*","*"]]
  217.     aIBoard = [["*","*","*","*","*","*","*"],["*","*","*","*","*","*","*"],["*","*","*","*","*","*","*"],["*","*","*","*","*","*","*"],["*","*","*","*","*","*","*"],["*","*","*","*","*","*","*"],["*","*","*","*","*","*","*"]]
  218.      
  219.     printIntro()
  220.     myFleet = placeMyFleet(myFleet, ["destroyer"])
  221.     aIBoard = placeAIShips(aIBoard, ["destroyer"])
  222.     printBoard("AI Board:", aIBoard) #this is good to make sure your hits are okay
  223.  
  224.     playing = True
  225.     while (playing):
  226.         print("You're Attacking!")
  227.         printBoard("Your Hits:", myHits)
  228.  
  229.          
  230.         userMove(aIBoard, myHits)
  231.         playing = checkWin(myHits)
  232.         if (not playing):
  233.             print("You win!")
  234.             printBoardToText(myFleet)
  235.             print("I don't believe you! Show me your position!")
  236.             angry = isCheating(hitList)
  237.             if (angry):
  238.                 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!")
  239.             else:
  240.                 print("Doesn't look like you cheated. Fine, you've won fair and square!")
  241.            
  242.          
  243.         if (playing):
  244.             print("Computer is Attacking")
  245.             myFleet = aIAttack(myFleet, hitList)
  246.             printBoard("After AI's turn:", myFleet)
  247.             playing = checkAIWin(myFleet)
  248.             if(not playing):  
  249.                 print("Computer wins!")
  250.                
  251.  
  252. main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement