2013-11-24 5 views
-1

좋아요. 컴퓨터에 숨겨진 공간이있는 다른 보드를 개발하고 히트를 테스트하는 방법을 모르겠습니다. 다시 한 번 나는 내가 지금 가지고있는 보드에서 어떻게 히트를 테스트 할 지 확신 할 수 없다. 주의 사항 : 자신의 배를 공격하지 않으므로 플레이어 턴 기능이 컴퓨터 보드로 마이그레이션됩니다. 여기에 코드가 있습니다. 그것은 최고의 형식이되지 않을 수 있습니다 (예 : 메서드 및 개체 등)하지만 나중에 조금 닦을 수 있습니다. 또한 배를 하나의 기능으로 배치하는 다른 방법이 있을까요? 아니면 내가 가지고있는 방식대로, 그렇게해야할까요?단순한 전함 게임 구현 Python

class battleship(object): 

def __init__(self): 
    self.board = [["O"] * 10, ["O"] * 10, ["O"] * 10, ["O"] * 10, ["O"] * 10, ["O"] * 10, ["O"] * 10, ["O"] * 10, ["O"] * 10, ["O"] * 10, ] 
    self.printboard() 
    self.placeAircraftCarrier() 
    self.placeBattleShip() 
    self.placeSubmarine() 
    self.placeDestroyer() 
    self.placePatrolBoat() 
    for i in range(100): 
     self.playerTurn() 


def printboard(self): 
    print "Game Board\n" 
    print "1","2","3","4","5","6","7","8","9","10" 
    for row in self.board: 
     print "|".join(row) 
def placeBattleShip(self): 
    while True: 
     self.vOrHPlacement = input("Would you like to place the Battleship (1) Vertically or (2)Horizontally?:") 
     if self.vOrHPlacement == 1 or self.vOrHPlacement == 2: 
      break 
     else: 
      print "You must press 1 or 2." 
    while True: 
     self.battleshipRow = input("With the head as the starting place what row would you like to place the Battleship (Takes 4 Spaces)?:") 
     self.battleshipCol = input("What column would you like to start the BattleShip at?:") 
     if self.vOrHPlacement == 1: 
      if self.battleshipRow > 7 or self.battleshipRow <= 0: 
       print "\nIf placing vertically you can only choose 1-7 for the row." 
      elif self.battleshipCol <= 0 or self.battleshipCol > 10: 
       print "You must choose 1 - 10 for a column." 
      elif self.board[self.battleshipRow - 1][self.battleshipCol - 1] == "X": 
       print "There is already a ship there." 
      else: 
       self.battleshipRow -= 2 
       self.battleshipCol -= 1 
       for i in range(4): 
        self.board[self.battleshipRow + 1][self.battleshipCol] = "X" 
        self.battleshipRow += 1 
       break 
     elif self.vOrHPlacement == 2: 
      if self.battleshipCol > 7 or self.battleshipCol <= 0: 
       print "\nIf placing horizontally you can only choose 1-7 for a column." 
      elif self.battleshipRow <= 0 or self.battleshipRow > 10: 
       print "\n You must choose 1 - 10 as a row choice." 
      elif self.board[self.battleshipRow - 1][self.battleshipCol - 1] == "X": 
       print "There is already a ship there." 
      else: 
       self.battleshipRow -= 1 
       self.battleshipCol -= 2 
       for i in range(4): 
        self.board[self.battleshipRow][self.battleshipCol + 1] = "X" 
        self.battleshipCol += 1 
       break 
    self.printboard() 
def placeAircraftCarrier(self): 
    while True: 
     self.vOrHPlacement = input("Would you like to place the Aircraft Carrier (1) Vertically or (2)Horizontally?:") 
     if self.vOrHPlacement == 1 or self.vOrHPlacement == 2: 
      break 
     else: 
      print "You must press 1 or 2." 
    while True: 
     self.battleshipRow = input("With the head as the starting place what row would you like to place the Aircraft Carrier (Takes 5 Spaces)?:") 
     self.battleshipCol = input("What column would you like to start the Aircraft Carrier at?:") 
     if self.vOrHPlacement == 1: 
      if self.battleshipRow > 6 or self.battleshipRow <= 0: 
       print "\nIf placing vertically you can only choose 1-6 for the row." 
      elif self.battleshipCol <= 0 or self.battleshipCol > 10: 
       print "You must choose 1 - 10 for a column." 
      elif self.board[self.battleshipRow - 1][self.battleshipCol - 1] == "X": 
       print "There is already a ship there." 
      else: 
       self.battleshipRow -= 2 
       self.battleshipCol -= 1 
       for i in range(5): 
        self.board[self.battleshipRow + 1][self.battleshipCol] = "X" 
        self.battleshipRow += 1 
       break 
     elif self.vOrHPlacement == 2: 
      if self.battleshipCol > 6 or self.battleshipCol <= 0: 
       print "\nIf placing horizontally you can only choose 1-6 for a column." 
      elif self.battleshipRow <= 0 or self.battleshipRow > 10: 
       print "\n You must choose 1 - 10 as a row choice." 
      elif self.board[self.battleshipRow - 1][self.battleshipCol - 1] == "X": 
       print "There is already a ship there." 
      else: 
       self.battleshipRow -= 1 
       self.battleshipCol -= 2 
       for i in range(5): 
        self.board[self.battleshipRow][self.battleshipCol + 1] = "X" 
        self.battleshipCol += 1 
       break 
    self.printboard() 
def placeSubmarine(self): 
    while True: 
     self.vOrHPlacement = input("Would you like to place the Submarine (1) Vertically or (2)Horizontally?:") 
     if self.vOrHPlacement == 1 or self.vOrHPlacement == 2: 
      break 
     else: 
      print "You must press 1 or 2." 
    while True: 
     self.battleshipRow = input("With the head as the starting place what row would you like to place the Submarine (Takes 3 Spaces)?:") 
     self.battleshipCol = input("What column would you like to start the Submarine at?:") 
     if self.vOrHPlacement == 1: 
      if self.battleshipRow > 8 or self.battleshipRow <= 0: 
       print "\nIf placing vertically you can only choose 1-8 for the row." 
      elif self.battleshipCol <= 0 or self.battleshipCol > 10: 
       print "You must choose 1 - 10 for a column." 
      elif self.board[self.battleshipRow - 1][self.battleshipCol - 1] == "X": 
       print "There is already a ship there." 
      else: 
       self.battleshipRow -= 2 
       self.battleshipCol -= 1 
       for i in range(3): 
        self.board[self.battleshipRow + 1][self.battleshipCol] = "X" 
        self.battleshipRow += 1 
       break 
     elif self.vOrHPlacement == 2: 
      if self.battleshipCol > 8 or self.battleshipCol <= 0: 
       print "\nIf placing horizontally you can only choose 1-8 for a column." 
      elif self.battleshipRow <= 0 or self.battleshipRow > 10: 
       print "\n You must choose 1 - 10 as a row choice." 
      elif self.board[self.battleshipRow - 1][self.battleshipCol - 1] == "X": 
       print "There is already a ship there." 
      else: 
       self.battleshipRow -= 1 
       self.battleshipCol -= 2 
       for i in range(3): 
        self.board[self.battleshipRow][self.battleshipCol + 1] = "X" 
        self.battleshipCol += 1 
       break 
    self.printboard() 
def placeDestroyer(self): 
    while True: 
     self.vOrHPlacement = input("Would you like to place the Destroyer (1) Vertically or (2)Horizontally?:") 
     if self.vOrHPlacement == 1 or self.vOrHPlacement == 2: 
      break 
     else: 
      print "You must press 1 or 2." 
    while True: 
     self.battleshipRow = input("With the head as the starting place what row would you like to place the Destroyer (Takes 3 Spaces)?:") 
     self.battleshipCol = input("What column would you like to start the Destroyer at?:") 
     if self.vOrHPlacement == 1: 
      if self.battleshipRow > 8 or self.battleshipRow <= 0: 
       print "\nIf placing vertically you can only choose 1-8 for the row." 
      elif self.battleshipCol <= 0 or self.battleshipCol > 10: 
       print "You must choose 1 - 10 for a column." 
      elif self.board[self.battleshipRow - 1][self.battleshipCol - 1] == "X": 
       print "There is already a ship there." 
      else: 
       self.battleshipRow -= 2 
       self.battleshipCol -= 1 
       for i in range(3): 
        self.board[self.battleshipRow + 1][self.battleshipCol] = "X" 
        self.battleshipRow += 1 
       break 
     elif self.vOrHPlacement == 2: 
      if self.battleshipCol > 8 or self.battleshipCol <= 0: 
       print "\nIf placing horizontally you can only choose 1-8 for a column." 
      elif self.battleshipRow <= 0 or self.battleshipRow > 10: 
       print "\n You must choose 1 - 10 as a row choice." 
      elif self.board[self.battleshipRow - 1][self.battleshipCol - 1] == "X": 
       print "There is already a ship there." 
      else: 
       self.battleshipRow -= 1 
       self.battleshipCol -= 2 
       for i in range(3): 
        self.board[self.battleshipRow][self.battleshipCol + 1] = "X" 
        self.battleshipCol += 1 
       break 
    self.printboard() 
def placePatrolBoat(self): 
    while True: 
     self.vOrHPlacement = input("Would you like to place the Patrol Boat (1) Vertically or (2)Horizontally?:") 
     if self.vOrHPlacement == 1 or self.vOrHPlacement == 2: 
      break 
     else: 
      print "You must press 1 or 2." 
    while True: 
     self.battleshipRow = input("With the head as the starting place what row would you like to place the Patrol Boat (Takes 2 Spaces)?:") 
     self.battleshipCol = input("What column would you like to start the Patrol Boat at?:") 
     if self.vOrHPlacement == 1: 
      if self.battleshipRow > 9 or self.battleshipRow <= 0: 
       print "\nIf placing vertically you can only choose 1-9 for the row." 
      elif self.battleshipCol <= 0 or self.battleshipCol > 10: 
       print "You must choose 1 - 10 for a column." 
      elif self.board[self.battleshipRow - 1][self.battleshipCol - 1] == "X": 
       print "There is already a ship there." 
      else: 
       self.battleshipRow -= 2 
       self.battleshipCol -= 1 
       for i in range(2): 
        self.board[self.battleshipRow + 1][self.battleshipCol] = "X" 
        self.battleshipRow += 1 
       break 
     elif self.vOrHPlacement == 2: 
      if self.battleshipCol > 9 or self.battleshipCol <= 0: 
       print "\nIf placing horizontally you can only choose 1-9 for a column." 
      elif self.battleshipRow <= 0 or self.battleshipRow > 10: 
       print "\n You must choose 1 - 10 as a row choice." 
      elif self.board[self.battleshipRow - 1][self.battleshipCol - 1] == "X": 
       print "There is already a ship there." 
      else: 
       self.battleshipRow -= 1 
       self.battleshipCol -= 2 
       for i in range(2): 
        self.board[self.battleshipRow][self.battleshipCol + 1] = "X" 
        self.battleshipCol += 1 
       break 
    self.printboard() 
def playerTurn(self): 
    while True: 
     self.row = input("What row coordinate would you like to hit?:") 
     self.column = input("What column coordinate would you like to hit?") 
     if self.row > 10 or self.row < 0: 
      print "You must pick a row coordinate between 1 and 10." 
     elif self.column > 10 or self.column < 0: 
      print "You must pick a column coordinate between 1 and 10." 
     elif self.board[self.row - 1][self.column - 1] == "*": 
      print "You have already hit there." 
     else: 
      self.board[self.row - 1][self.column - 1] = "*" 
      break 
    self.printboard() 

b = battleship() 
+0

같은 몇 가지 물건을 할 수있는 나는 어쩌면 내가 보드 객체를해야한다 생각하고, 선박 객체하지만 난 게임 보드로를 구현할 수있는 방법을 잘하지 않았다. 기본적으로 각 작업장 방법은 배 길이에 대한 약간의 변경과 정확히 동일합니다. –

+0

[편집] (http://stackoverflow.com/posts/20179953/edit) 기능을 사용하십시오. –

답변

0

코드 조직이 많이 필요합니다. 나는 어떤 종류의 루핑이나 인풋으로부터 클래스를 자유롭게 유지할 것을 제안 할 것이다! 사용자의 물건을 입력하십시오. & 그런 다음 다른 인스턴스가 아닌 클래스 인스턴스에 추가하십시오. 코드 &을 작성하여 다른 사람들이 귀하를 도울 수 있도록 문서를 추가하십시오.

는이

class BattleShip: 
    """ Ship object container""" 

    def __init__(self, position_x, position_y, size): 
     """ Necessary variables for the ship go here """ 
     self.position_x = position_x 
     self.position_y = position_y 
     self.size = size 

    def contains(self, position_x, position_y): 
     """ Returns true if supplied point lies inside this ship """ 
     # code 

    def destroy(self, position_x, position_y): 
     """ Destroys the ship's point supplied if it contains it """ 
     assert self.contains(position_x, position_y) 
     # Now update the gameboard 
     # code 

    def isCompletelyDestroyed(self): 
     """ Returns True if ship is completely destoryed else False """ 
     # code 


class GameBoard: 
    """ The container for the ships """ 
    def __init__(self, size): 
     """Initialize clean GameBoard depending on size, etc """ 
     self.occupied = "+" # representation for ships 
     self.destroyed = 'x' # representation for destroyed area 
     self.clear = '-' # representation for clear water 

    def printBoard(self): 
     """ Print the current gameboard state """ 

    def update(self, ship): 
     """ Updates the gameboard according to updated ship """ 


# Now do the mainloop 
while game_not_over: 
    # run game 
+0

조언 해 주셔서 감사합니다. 내가 말했듯이 저는 CS의 1 학기 때만 아주 아마추어 프로그래머입니다. 나는 코드를 작성하는 즉시 주석을 달아주는 습관이 필요하다. 그러나 사람은 여기에있는 물건에 대해 정말로 가혹한 사람들입니다. 어떤 사람들은 지팡이가 엉덩이를 쑤셔 넣은 것처럼 보입니다. 죄송합니다. 개인적으로 별 의미가 없습니다. 나는 당신이 가혹하다는 것을 말하고 있지 않다. 왜냐하면 내가 다시 읽었을 때 나는 그 선들 사이에서 읽을지도 모르기 때문이다. 하지만 어쨌든. 수업을 설정하는 방법에 대한 제안을 해주셔서 대단히 감사합니다. 나는 보드로 완전히 파괴 된 부분을 어떻게 얻을 수 있을지 잘 모르겠다. –

+0

또한 Idk는 배가 이미 존재하는지 여부를 확인하는 방법과 클래스 내부에 루프가없는 잘못된 입력 (인덱스 오류)을 추가하는 경우 입력으로 루프하는 방법을 설명합니다. 개체가 지금 가지고있는 방식대로 설정되어있는 경우. 나는 수표가 선박 클래스 자체에 있어야한다고 생각한다. 아니면 어딘가에 포함 된 메서드에서. –

+0

새 이민자를 위해, StackOverflow에있는 사람들이 약간 가혹한 것처럼 보일지 모르지만, 그럴 수는 없다. 2 개의 선박이 같은지 확인해야 할뿐만 아니라 모든 포인트를 공유하지 않아도되는지 확인할 필요가 없습니다. 그래서 보드에 모든 점을 추적하는 변수를 만들 것을 제안합니다. (이것을 위해 ['sets'] (http://docs.python.org/2/library/stdtypes.html#set)를 사용하십시오) 보드의 fully_destroyed 메소드는 총 배송 대 파괴 된 배송 수를 추적해야합니다. 배가 파괴되면 전화 해. –