【问题标题】:checking a tic tac toe game on python在 python 上检查井字游戏
【发布时间】:2013-10-22 09:59:10
【问题描述】:

我正在做这个项目,我正在检查一个完成的井字游戏。用户在每行(有 3 行)中输入 x 和 o 以及句点(最多 3 个)的组合。我必须检查 x 或 o 是否转了太多圈。这就是我所拥有的:

if ttt.count(x) > 5:
                    print("x took too many turns")

这仅适用于 x。当我运行程序并测试该语句是否针对 x 出现时,并没有出现。我做错了什么?

这是一个示例运行:

0 - check a finished tic-tac-toe
1 - check a finished sudoku
2 - check a game of connect four
3 - quit
choose an option: 0
option 0
For each row, start with x. Enter a combination of x'sand o's up to three characters. For a blank space,enter a period '.'.
top row:xox
middle row:xox
bottom row:xox  
['xox', 'xox', 'xox']
0 - check a finished tic-tac-toe
1 - check a finished sudoku
2 - check a game of connect four
3 - quit
choose an option: 

这是代码的较大部分:

for x in i:
            if x not in valid_symbols:
                    print("invalid board - invalid symbol " + x )
                    done = True
                    break
            if ttt.count(x) > 5:
                print("x took too many turns")

如果我插入一个无效的符号,那么它会打印那个语句。

【问题讨论】:

  • 这可能是一个更大的部分,但你错过了最重要的部分 - 你实际定义 ttt 的地方(顺便说一句,这恰好是一个糟糕的变量名)。此外,如果您使用 4 个空格而不是制表符进行缩进,您会发现 Python 中的内容要好得多。
  • 感谢您的建议。 ttt 是井字游戏的变量名,定义为: ttt= list()
  • tic_tac_toegameboard 可能是更好的名称。

标签: if-statement for-loop python-3.x


【解决方案1】:

您似乎误解了ttt 的内容。打开解释器并尝试以下操作:

Python 3.3.2 (v3.3.2:d047928ae3f6, May 16 2013, 00:03:43) [MSC v.1600 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> tic_tac_toe = []
>>> tic_tac_toe.append(input('Top row: '))
Top row: xxx
>>>
>>> tic_tac_toe
['xxx']
>>> tic_tac_toe.count('x')
0
>>> tic_tac_toe.count('xxx')
1

当您.append('xox') 时会发生什么?列表是什么样的?

【讨论】:

  • @Wanye Werner 我编辑了我的答案,向你展示我做了什么来追加我的行
  • 我必须附加我的行是 ttt.append(rows) 然后我打印(ttt)。这在 col_size 的范围内,即 3。
  • 我不明白的是,我的代码的计数部分没有出现任何内容
  • 你在解释器里试过了吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-10-23
  • 1970-01-01
  • 1970-01-01
  • 2022-12-16
  • 2014-04-12
  • 1970-01-01
相关资源
最近更新 更多