You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python战舰游戏:如何用while循环检测用户空输入?

战舰游戏输入校验:添加空/全空格输入检测

你当前的代码只校验了输入是否在合法范围内,但没处理用户输入空内容或仅空格的情况。input()不会返回None——用户按回车得到空字符串'',输入全空格得到' ',所以之前的判断逻辑没覆盖这两种场景。

用strip()去除输入前后的空白字符,就能把全空格输入转为空字符串,再结合空值判断就能解决问题,修改后的代码如下:

def getUserInput(self):
    try:
        # 处理行坐标:先去空白,再校验
        x_row = input("Please Select the row coordinate (1-8)").strip()
        while not x_row or x_row not in '12345678':
            print("Invalid input! Enter a number between 1-8 (no empty spaces).")
            x_row = input("Please Select the row coordinate (1-8)").strip()

        # 处理列坐标:去空白后转大写,再校验
        y_column = input("Please Select the column coordinate (A-H)").strip().upper()
        while not y_column or y_column not in 'ABCDEFGH':
            print("Invalid input! Enter a letter between A-H (no empty spaces).")
            y_column = input("Please Select the column coordinate (A-H)").strip().upper()
        
        # 返回格式化后的坐标(可选,根据你的需求调整)
        return int(x_row), y_column
    except Exception as e:
        print(f"Error: {e}")

核心修改说明:

  • strip()处理:每次输入后立即调用strip(),去除前后所有空白字符(空格、换行等),把全空格输入转为空字符串
  • 循环条件优化:while not x_row or x_row not in '12345678'——先判断处理后的输入是否为空(空输入/全空格),再判断是否在合法范围内,一次性拦截两种非法情况
  • 提示信息优化:明确告知用户不能输入空白内容,比原来的提示更友好

这样修改后,就能完整拦截所有非法输入场景,同时保留原有的范围校验逻辑。

内容的提问来源于stack exchange,提问作者John M

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 10:35:24