0

0

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

心靈之曲

心靈之曲

发布时间:2025-08-29 19:51:01

|

911人浏览过

|

来源于php中文网

原创

 使用 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免费学习笔记(深入)”;

Clippah
Clippah

AI驱动的创意视频处理平台

下载

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 开发了一款简单的战舰游戏。这个游戏虽然简单,但包含了游戏开发的基本要素,例如游戏地图、角色、规则和循环。通过学习和实践这个项目,可以为进一步学习游戏开发打下坚实的基础。

					

热门AI工具

更多
DeepSeek
DeepSeek

幻方量化公司旗下的开源大模型平台

豆包大模型
豆包大模型

字节跳动自主研发的一系列大型语言模型

通义千问
通义千问

阿里巴巴推出的全能AI助手

腾讯元宝
腾讯元宝

腾讯混元平台推出的AI助手

文心一言
文心一言

文心一言是百度开发的AI聊天机器人,通过对话可以生成各种形式的内容。

讯飞写作
讯飞写作

基于讯飞星火大模型的AI写作工具,可以快速生成新闻稿件、品宣文案、工作总结、心得体会等各种文文稿

即梦AI
即梦AI

一站式AI创作平台,免费AI图片和视频生成。

ChatGPT
ChatGPT

最最强大的AI聊天机器人程序,ChatGPT不单是聊天机器人,还能进行撰写邮件、视频脚本、文案、翻译、代码等任务。

相关专题

更多
python中print函数的用法
python中print函数的用法

python中print函数的语法是“print(value1, value2, ..., sep=' ', end=' ', file=sys.stdout, flush=False)”。本专题为大家提供print相关的文章、下载、课程内容,供大家免费下载体验。

186

2023.09.27

if什么意思
if什么意思

if的意思是“如果”的条件。它是一个用于引导条件语句的关键词,用于根据特定条件的真假情况来执行不同的代码块。本专题提供if什么意思的相关文章,供大家免费阅读。

785

2023.08.22

while的用法
while的用法

while的用法是“while 条件: 代码块”,条件是一个表达式,当条件为真时,执行代码块,然后再次判断条件是否为真,如果为真则继续执行代码块,直到条件为假为止。本专题为大家提供while相关的文章、下载、课程内容,供大家免费下载体验。

98

2023.09.25

golang map内存释放
golang map内存释放

本专题整合了golang map内存相关教程,阅读专题下面的文章了解更多相关内容。

75

2025.09.05

golang map相关教程
golang map相关教程

本专题整合了golang map相关教程,阅读专题下面的文章了解更多详细内容。

36

2025.11.16

golang map原理
golang map原理

本专题整合了golang map相关内容,阅读专题下面的文章了解更多详细内容。

61

2025.11.17

java判断map相关教程
java判断map相关教程

本专题整合了java判断map相关教程,阅读专题下面的文章了解更多详细内容。

42

2025.11.27

function是什么
function是什么

function是函数的意思,是一段具有特定功能的可重复使用的代码块,是程序的基本组成单元之一,可以接受输入参数,执行特定的操作,并返回结果。本专题为大家提供function是什么的相关的文章、下载、课程内容,供大家免费下载体验。

485

2023.08.04

go语言 注释编码
go语言 注释编码

本专题整合了go语言注释、注释规范等等内容,阅读专题下面的文章了解更多详细内容。

30

2026.01.31

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
最新Python教程 从入门到精通
最新Python教程 从入门到精通

共4课时 | 22.4万人学习

Django 教程
Django 教程

共28课时 | 3.8万人学习

SciPy 教程
SciPy 教程

共10课时 | 1.4万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号