boxmoe_header_banner_img

Hello! 欢迎来到悠悠畅享网!

文章导读

使用 Python 开发战舰游戏:实现玩家与电脑的对战循环


avatar
作者 2025年8月29日 15

使用 Python 开发战舰游戏:实现玩家与电脑的对战循环

本文将指导初学者使用 python 开发一款简单的战舰游戏,重点讲解如何实现玩家与电脑之间的对战循环。通过创建虚拟战场、部署舰船、以及模拟攻击,最终实现一方击沉对方所有舰船的游戏目标。文中将提供详细的代码示例,并对关键步骤进行解释,帮助读者理解游戏逻辑并完成开发。 ### 1. 游戏框架搭建 首先,我们需要搭建游戏的基本框架,包括定义游戏地图、舰船种类、以及玩家和电脑的角色。 “`python from random import randrange ship_initial = [“B”, “C”, “F”, “A”, “S”] ship_names = [“Battleship”, “Cruiser”, “Frigate“, “aircraft Carrier”, “Sub”] map_size = 10 def get_username(): “”” function getting username for welcome message “”” while True: user_name = input(“Enter your name: “) if user_name: print(f”Welcome to the battleship game {user_name}!”) return user_name else: print(“Please enter your name.”) def create_battlefield(map_size): “”” function to create a map based on size “”” return [[“_”] * map_size for _ in range(map_size)] def display_battlefield(board): “”” function to display current state of the map. “”” for row in board: print(” “.join(row))

这段代码定义了舰船的初始字母和名称,地图大小,创建地图和显示地图的函数。create_battlefield 函数创建一个二维列表,代表游戏地图,初始状态下所有格子都是空的,用 “_” 表示。display_battlefield 函数用于在控制台打印当前的游戏地图状态。

2. 舰船部署

接下来,我们需要实现玩家和电脑各自部署舰船的功能。玩家需要手动输入舰船的坐标,而电脑则随机生成舰船的坐标。

def player_ship_coordinate(player_board, occupied):     """     function for player placement ship     """     while True:         try:             row = int(input("Enter the row for Battleship: "))             col = int(input("Enter the column for Battleship: "))             if 0 <= row < 10 and 0 <= col < 10 and (row, col) not in occupied:                 player_board[row][col] = "B"                 occupied.add((row, col))                 break             else:                 print("Invalid coordinates. Please enter correct value.")         except ValueError:             print("Invalid input. Please enter a valid integer.")      while True:         try:             row = int(input("Enter the row for Cruiser: "))             col = int(input("Enter the column for Cruiser: "))             if 0 <= row < 10 and 0 <= col < 10 and (row, col) not in occupied:                 player_board[row][col] = "C"                 occupied.add((row, col))                 break             else:                 print("Invalid coordinates. Please enter correct values.")         except ValueError:             print("Invalid input. Please enter a valid integer.")      while True:         try:             row = int(input("Enter the row for Frigate: "))             col = int(input("Enter the column for Frigate: "))             if 0 <= row < 10 and 0 <= col < 10 and (row, col) not in occupied:                 player_board[row][col] = "F"                 occupied.add((row, col))                 break             else:                 print("Invalid coordinates. Please enter correct values")         except ValueError:             print("Invalid input. Please enter a valid integer.")      while True:         try:             row = int(input("Enter the row for Aircraft Carrier: "))             col = int(input("Enter the column for Aircraft Carrier: "))              if 0 <= row < 10 and 0 <= col < 10 and (row, col) not in occupied:                 player_board[row][col] = "A"                 occupied.add((row, col))                 break             else:                 print("Invalid coordinates. Please enter correct values")         except ValueError:             print("Invalid input. Please enter a valid integer.")      while True:         try:             row = int(input("Enter the row for Submarine: "))             col = int(input("Enter the column for Submarine: "))              if 0 <= row < 10 and 0 <= col < 10 and (row, col) not in occupied:                 player_board[row][col] = "S"                 occupied.add((row, col))                 break             else:                 print("Invalid coordinates. Please enter correct values")         except ValueError:             print("Invalid input. Please enter a valid integer.")      return player_board, occupied  def comp_ship_coordinate(comp_board):     """     function for computer opponent.     """     for ship in ship_initial:         while True:             row = randrange(0, 10)             col = randrange(0, 10)             if comp_board[row][col] == "_":                 comp_board[row][col] = ship                 break      return comp_board

player_ship_coordinate 函数允许玩家输入每艘舰船的坐标,并将其放置在游戏地图上。 comp_ship_coordinate 函数则随机地在电脑的地图上放置舰船。

3. 实现对战循环

现在,我们需要实现玩家和电脑之间的对战循环。在每一轮中,玩家攻击电脑,电脑也攻击玩家,直到一方的所有舰船都被击沉。

def check_player_hit(comp_board, dummy_board, user):     """     Function for player hit or missed on enemy ship     """     print(user)     row = int(input("Enter your row: "))     col = int(input("Enter your col: "))     hit = 1  # Assume there will be a hit      if comp_board[row][col] == "B":         comp_board[row][col] = "b"         dummy_board[row][col] = "X" # 'X' will signify on the dummy board when a player hits a ship         print("Computer: Battleship been hit!")     elif comp_board[row][col] == "C":         comp_board[row][col] = "c"         dummy_board[row][col] = "X"         print("Computer: Cruiser been hit!")     elif comp_board[row][col] == "F":         comp_board[row][col] = "f"         dummy_board[row][col] = "X"         print("Computer: Frigate been hit!")     elif comp_board[row][col] == "A":         comp_board[row][col] = "a"         dummy_board[row][col] = "X"         print("Computer: Aircraft Carrier been hit")     elif comp_board[row][col] == "S":         comp_board[row][col] = "s"         dummy_board[row][col] = "X"         print("Computer: Sub been hit")     else:         dummy_board[row][col] = "*"         hit = 0  # Note that there was not a hit         print("Missed me!")      return hit   def check_comp_hit(player_board):                       # Refactored function to map hits and misses     """     function for comp hit or missed on the player ship     """      hit = 1                                             # Assunme there will be a hit      while True:                                         # Randomly select a row and column that has not previously been fired upon         row = randrange(0, 10)         col = randrange(0, 10)         if player_board[row][col] != "*" and player_board[row][col] != "a" and player_board[row][col] != "b" and comp_board[row][col] != "c" and comp_board[row][col] != "f" and comp_board[row][col] != "s":             break      print("Computer has selected coordinates", row, col)      if player_board[row][col] == "B":                   # If the computer has hit a vessel, change the value to lowercase and return a hit value of "1"         player_board[row][col] = "b"         print("Player: Battleship been hit!")     elif player_board[row][col] == "C":         player_board[row][col] = "c"         print("Player: Cruiser been hit!")     elif player_board[row][col] == "F":         player_board[row][col] = "f"         print("Player: Frigate been hit!")         hit = 1     elif player_board[row][col] == "A":         player_board[row][col] = "a"         print("Player: Aircraft carrier been hit!")     elif player_board[row][col] == "S":         player_board[row][col] = "s"         print("Player: Sub been hit!")     else:         hit = 0                                         # Note that there was not a hit         print("Missed me!")         player_board[row][col] = "*"      return hit 

check_player_hit 函数允许玩家输入攻击坐标,并判断是否击中电脑的舰船。如果击中,则在 dummy_board 上标记 “X”。 check_comp_hit 函数模拟电脑的攻击,随机选择坐标并判断是否击中玩家的舰船。

立即学习Python免费学习笔记(深入)”;

4. 游戏主循环

最后,我们需要将以上所有功能整合到游戏的主循环中。

if __name__ == "__main__":          user = get_username()          player_board = create_battlefield(map_size)         comp_board   = create_battlefield(map_size)         dummy_board = create_battlefield(map_size) # create a dummy board          occupied = set()          print("Player's turn:")         player_ship_coordinate(player_board, occupied)         display_battlefield(player_board)          print("nComputer opponent's turn:")         comp_ship_coordinate(comp_board)         # display_battlefield(comp_board) # for testing purposes         display_battlefield(dummy_board)  # display the blank dummy board instead of computer board          # Suggested while loop to alternate between the player and computer firing upon positions          player_hits = 0          comp_hits   = 0          while True:             player_hits += check_player_hit(comp_board, dummy_board, user)   # If the player hit count reaches "5" all of the computer's vessels have been sunk             if player_hits == 5:                 print("Player has won - game over")                 break              comp_hits += check_comp_hit(player_board)           # If the computer hit count reaches "5" all of the player's vessels have been sunk             if comp_hits == 5:                 print("Computer has won - game over")                 break               print(f"Player {user} board")                       # Just included the redisplay of the boards for testing purposes             display_battlefield(player_board)              print(" ")              print("Computer board")             display_battlefield(dummy_board) # display dummy board instead of computer board

这段代码首先初始化游戏地图和舰船,然后进入主循环。在循环中,玩家和电脑轮流攻击,直到一方的所有舰船都被击沉,游戏结束。

注意事项

  • 坐标有效性验证: 在玩家输入坐标时,需要验证坐标是否在地图范围内,以及该坐标是否已经被占用。
  • 击沉判断: 需要添加判断舰船是否被完全击沉的逻辑,以便在游戏结束时给出正确的提示。
  • 界面优化: 可以使用更友好的界面,例如使用图形界面库,提高游戏的可玩性。

总结

通过以上步骤,我们成功地使用 Python 开发了一款简单的战舰游戏。这个游戏虽然简单,但包含了游戏开发的基本要素,例如游戏地图、角色、规则和循环。通过学习和实践这个项目,可以为进一步学习游戏开发打下坚实的基础。




评论(已关闭)

评论已关闭

text=ZqhQzanResources