将相同的功能与不同的参数组合在一起 - Python [英] Combine same function with different parameters - Python

查看:99
本文介绍了将相同的功能与不同的参数组合在一起 - Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想制作一个tic tac toe游戏,当用户输入一个数字1-9时,它会在网格上的相应空间上生成一个X.这里的功能是:

I want to make a tic tac toe game, and I am making it so when the user inputs a number 1 - 9, it makes an X on the corresponding space on the grid. here's the function for that:

def move(inp):
    if inp == 1:
        one = " X |\t|\n_____________\n   |\t|\n_____________\n   |\t|"
        print one
    elif inp == 2:
        two = "   | X |\n_____________\n   |\t|\n_____________\n   |\t|"
        print two
    elif inp == 3:
        three = "   |\t| X\n_____________\n   |\t|\n_____________\n   |\t|"
        print three
    elif inp == 4:
        four = "   |\t|\n____________\n X |\t|\n_____________\n   |\t|"
        print four
    elif inp == 5:
        five = "   |\t|\n_____________\n   | X  |\n_____________\n   |\t|"
        print five
    elif inp == 6:
        six = "   |\t|\n_____________\n   |\t| X \n_____________\n   |\t|"
        print six
    elif inp == 7:
        seven = "   |\t|\n_____________\n   |\t|\n_____________\n X |\t|"
        print seven
    elif inp == 8:
        eight = "   |\t|\n_____________\n   |\t|\n_____________\n   | X |"
        print eight
    elif inp == 9:
        nine = "   |\t|\n_____________\n   |\t|\n_____________\n   |\t| X "
        print nine

等等,网格出现在右边的X处地点。但接下来就会出现。我想让他们输入一个新号码,但保留原来的位置。我在想:是否有一种方法可以将这个函数与不同的参数结合起来,并让它们在网格中放置两个X?
所以,我的问题是,是否有一个这样的功能,如果没有,我该如何做到这一点。

and so, the grid shows up with the X at the right place. But then the next turn comes. And I want to have them enter a new number, but keep the old X where it was. I was thinking: is there a way to combine that function to itself with a different parameter and have them put two X's on the grid? So, my question is, is there a function for this, and if not, how would I do this.

推荐答案

<您可以这样做:

you could do this:

def make_square(inp):
    square = " {0} |{1}\t|{2}\n_____________\n  {3} | {4}\t|{5}\n_____________\n {6}  |{7}\t|{8}" # set {} brackets for 'X' format
    inp += -1 # rest because need take from 0 as the brackts indice
    for x in range(9): # range max of 'X'
        if x != inp:
            square = square.replace('{{{0}}}'.format(x),' ') # delete brackets without the number select by the user
            # {{ {0} }}  explication http://stackoverflow.com/a/5466478/4941927
    square = square.replace('{{{0}}}'.format(inp),'{0}') # convert current {number} into {0} for format
    square = square.format('X') # formatting brackets for the 'X'
    print square

make_square(2)

如果您需要帮助,我很乐意帮助
问候!

if you need help, I am happy to help Greetings!

这篇关于将相同的功能与不同的参数组合在一起 - Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆