【问题标题】:pop index out of range in while弹出索引超出范围
【发布时间】:2022-01-20 04:30:13
【问题描述】:

我正在玩井字游戏,我想让Computer 变量永远不要选择Player 输入选择的内容。

from ast import If

import random

from re import X

wordlist = [' ',' ',' '], [' ',' ', ' '], [' ',' ',' ']

wordlist2 = ['1', '2', '3', '4', '5', '6', '7', '8', '9']

def Game():
    for element in wordlist:
        print(element)
        
while True:
    
    Player = input()
    
    Computer = random.choice(wordlist2)
    
    #Player
    if Player == '1':
        wordlist[0][0] = 'x'
        if Player == '1':
            wordlist2.pop(0)
        
    if Player == '2':
        wordlist[0][1] = 'x'
        if Player == '2':
            wordlist2.pop(1)
        
    if Player == '3':
        wordlist[0][2] = 'x'
        if Player == '3':
            wordlist2.pop(2)

        
    if Player == '4':
        wordlist[1][0] = 'x'
        if Player == '4':
            wordlist2.pop(3)
        
    if Player == '5':
        wordlist[1][1] = 'x'
        if Player == '5':
            wordlist2.pop(4)
        
    if Player == '6':
        wordlist[1][2] = 'x'
        if Player == '6':
            wordlist2.pop(5)
        
    if Player == '7':
        wordlist[2][0] = 'x'
        if Player == '7':
            wordlist2.pop(6)
        
    if Player == '8':
        wordlist[2][1] = 'x'
        if Player == '8':
            wordlist2.pop(7)
        
    if Player == '9':
        wordlist[2][2] = 'x'
        if Player == '9':
            wordlist2.pop(8)
        
    #Computer
    
    if Computer == '1':
        wordlist[0][0] = 'o'
        
    if Computer == '2':
        wordlist[0][1] = 'o'
        
    if Computer == '3':
        wordlist[0][2] = 'o'
        
    if Computer == '4':
        wordlist[1][0] = 'o'
        
    if Computer == '5':
        wordlist[1][1] = 'o'
        
    if Computer == '6':
        wordlist[1][2] = 'o'
        
    if Computer == '7':
        wordlist[2][0] = 'o'
        
    if Computer == '8':
        wordlist[2][1] = 'o'
        
    if Computer == '9':
        wordlist[2][2] = 'o'
        
    Game()

错误

发生异常:IndexError pop index out of range

【问题讨论】:

  • 我建议你开始接受你的答案...

标签: python list


【解决方案1】:

关于你的问题,我看到 3 个问题...

  1. Pop 方法使用索引,每次删除元素时都会改变,可能更容易使用remove 方法,但请注意它使用的是值而不是索引。

  2. 在所有玩家条件 (IF) 后移动计算机选择,否则玩家和计算机可能以相同的数字结束。

  3. 你只是删除玩家号码,删除电脑播放的号码。

让我提出一些额外的建议:

  1. 所有条件都是IF,这会导致问题,首先播放器条件应该是IF,然后使用ELIF,电脑也是如此。

  2. 这个游戏永远不会有赢家,它会一直运行到没有更多可用的数字,然后以可怕的回溯失败。添加一些代码来查找行并宣布获胜者,或者如果没有更多数字可供选择,则说它是平局。

  3. 根据我的经验,在此类项目中使用 dictionary 可能更容易

希望这会有所帮助,您就快到了!

【讨论】:

  • 非常感谢您帮助我,先生,我现在需要的是break语句,再次感谢:)
猜你喜欢
  • 2012-08-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-04
相关资源
最近更新 更多