
这段代码定义了舰船的初始字母和名称,地图大小,创建地图和显示地图的函数。create_battlefield 函数创建一个二维列表,代表游戏地图,初始状态下所有格子都是空的,用 "_" 表示。display_battlefield 函数用于在控制台打印当前的游戏地图状态。
接下来,我们需要实现玩家和电脑各自部署舰船的功能。玩家需要手动输入舰船的坐标,而电脑则随机生成舰船的坐标。
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_boardplayer_ship_coordinate 函数允许玩家输入每艘舰船的坐标,并将其放置在游戏地图上。 comp_ship_coordinate 函数则随机地在电脑的地图上放置舰船。
现在,我们需要实现玩家和电脑之间的对战循环。在每一轮中,玩家攻击电脑,电脑也攻击玩家,直到一方的所有舰船都被击沉。
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免费学习笔记(深入)”;
最后,我们需要将以上所有功能整合到游戏的主循环中。
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 开发了一款简单的战舰游戏。这个游戏虽然简单,但包含了游戏开发的基本要素,例如游戏地图、角色、规则和循环。通过学习和实践这个项目,可以为进一步学习游戏开发打下坚实的基础。
以上就是使用 Python 开发战舰游戏:实现玩家与电脑的对战循环的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号