【问题标题】:Automated S.O.S. game representation and extraction of game results自动 S.O.S.游戏表示和游戏结果的提取
【发布时间】:2021-04-09 03:01:08
【问题描述】:

我正在创建一个 Python 程序,它采用矩形的尺寸并通过列表创建一个表格。然后它必须找到可用位置的总数,并用字母“S”填充其中的一半,用字母“O”填充剩余的位置。我的目标是在 50 次重复的循环中计算“SOS”一词在水平、垂直和对角线上出现的次数,并提取三连音的平均数量。

到目前为止我的代码,

import random
n = 6
m = 7
a = [[i * j for j in range(m)] for i in range(n)]
for i in range(n):
    for j in range(m):
        if i < j:
            a[i][j] = 'O'
        elif i >= j:
            a[i][j] = 'S'

random.shuffle(a)
for i in range(50):
    for row in a:
        print(' '.join([str(elem) for elem in row]))

虽然我不确定到目前为止我的方法是否合适,但我需要有关如何为水平、垂直和对角线创建计数结构的想法。

提前谢谢你

【问题讨论】:

    标签: python arrays list arraylist


    【解决方案1】:

    您可以在某个坐标 x,y 上取一个字母,然后从该位置开始在 3x3 块中搜索,如下所示:

    for y in range(len(a)): #cycle through every line
        for x in range(len(a[y])): #cycle through every column
            if a[y][x] == 'S':
    
                #check if it will go out of boundaries horizontally
                if not x >= len(a[y])-3:
                    if a[y][x+1] == 'O' and a[y][x+2] == 'S':
                        #this will execute if there is a horizontal SOS
                        print(f"found horizontal SOS at position x: {x}; y: {y}")
    
                #check if it will go out of boundaries horizontally and vertically
                if (not x >= len(a[y])-3) and (not y >= len(a)-3):
                    if a[y+1][x+1] == 'O' and a[y+2][x+2] == 'S':
                        #this will execute if there is a diagonal SOS
                        print(f"found diagonal SOS at position x: {x}; y: {y}")
    
                #check if it will go out of boundaries vertically
                if not y >= len(a)-3:
                    if a[y+1][x] == 'O' and a[y+2][x] == 'S':
                        #this will execute if there is a vertical SOS
                        print(f"found vertical SOS at position x: {x}; y: {y}")
    

    当我们检查脚本是否会水平或垂直超出边界时,我们总是减去 3,因为必须至少有 2 个位置才能水平查看,len() 方法返回列表的长度,因为它开始于零我们减去 1,然后再减去 2,因为我们需要这 2 个空格。

    【讨论】:

    • 感谢您的回答,只有一个问题。通过使用您的代码,我得到一个 IndexError: list index out of range。如何控制边界?
    • @AndreasKreouzos 变量 a 必须是列表列表,如下所示:a = [['S', 'O', 'S'], ['O', 'O', 'S'], ['S', 'S', 'O']] 因为第一个循环循环遍历列表,第二个循环遍历列表中的项目
    • 好的,谢谢,我会试试看我哪里出错了。
    • 您好,您的代码运行良好,但仍然无法弄清楚如何限制代码不超过列表边界。
    • 非常感谢,我最近开始了我的编程之旅,我正在努力变得更强大。绝对不是一件容易的事,但我喜欢它。当然,我会保留您的建议并尝试将它们应用到未来的项目中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多