2016-04-28 9 views
5

Chcę zrobić grę w kółko i krzyżyk, a robię to, gdy użytkownik wprowadza liczbę 1 - 9, tworzy znak X na odpowiednim polu na siatce. oto funkcja:Połączyć tę samą funkcję z różnymi parametrami - Python

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 

i tak, siatka pojawia się z X w odpowiednim miejscu. Ale potem nadchodzi kolejna tura. Chcę, żeby wprowadzili nowy numer, ale zachowaj stare X tam, gdzie było. Pomyślałem: czy istnieje sposób na połączenie tej funkcji z innym parametrem i umieszczenie dwóch X na planszy? Moje pytanie brzmi: czy jest w tym funkcja, a jeśli nie, w jaki sposób to zrobię.

Odpowiedz

2

można to zrobić:

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) 

jeśli potrzebujesz pomocy, jestem szczęśliwy, aby pomóc Pozdrowienia!

2

Podczas programowania, jeśli okaże się, że wklejasz ten sam kod w kółko, coś jest nie tak. Powinieneś przemyśleć to wszystko od samego początku. Co powiesz na to?

board = [' '] * 9 # the 9 cells, empty at first 

def show(board): 
    for row in range(3): 
     print '|', 
     for col in range(3): 
      print board[row*3 + col], '|', 
     print # newline 

def move(inp): 
    board[inp-1] = 'X' # user input is 1-based, Python is 0-based 
    show(board) 
Powiązane problemy