Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
68 views
in Technique[技术] by (71.8m points)

python - Code doesn't work while put in main() definition

I am trying to refine my code for an automatic tic tac toe game where you can see if player1 has an advantage if he places the first move in the middle. I am now trying to refine my code as it is a bit messy but when I try to do this the program no longer works and I cannot see why.

Briefly about my program: When you start, you will be asked How many games do you want to simulate?, then you have to decide whether how big playing surface you would like on the question How big playing surface (3/5/7)? and finally you have to choose what scenario you would like to play on the question What scenario?, where 1 = player1 starts in the middle and all the other moves are automatic and 2 = all the moves are automatic. You will then get a histogram with the statistics from all game rounds.

The code I started with has the actual start of the program at the bottom without them being defined, ie the definition of my "games", "k" and "h", applies to all definitions. I wanted to change this so that the main() function started the game instead, so I put these under main(). And I also added "games", "k" and "h" as elements in all functions where they were needed. But now it only does one game even though I type 10 on the question How many games do you want to simulate? and it neither print the stats.

I will add both my codes, it is mostly the last main() function that I have made changes to, and also mark with comments about what I have changed. I hope that someone maybe can help me see why this doesn't work? It seems odd to me though I didn't add something I new to the code, only put the last code under a function. My first code:

import numpy as np
import random 
import matplotlib.pyplot as plt

# creating an empty board
def create_board(k):
    return np.zeros((k,k), dtype=int)

def possibilities(board): 
 
    lst = [] 
   
    for i in range(len(board)): 
        for j in range(len(board)): 
           
            if board[i][j] == 0: 
                lst.append((i, j)) 
    return(lst)

def first_move(board):
    l=[]
    
    for i in range(len(board)): 
         for j in range(len(board)): 
             
             if k == 3:
                 if board[i][j] == 0: 
                     l.append((1, 1)) 
             if k == 5:
                 if board[i][j] == 0: 
                     l.append((2, 2)) 
             if k == 7:
                 if board[i][j] == 0: 
                     l.append((3, 3)) 
    return(l) 

def random_place(board, player): 
    selection = possibilities(board) 
    current_loc = random.choice(selection)
    board[current_loc] = player 
    return(board) 

def first_place(board, player):
    
    player = 1
    selection = first_move(board) 
    current_loc = random.choice(selection) 
    board[current_loc] = player 
    return(board) 

def check_row(board, player):
    for x in range(len(board)): 
        win = True
      
        for y in range(len(board)): 
            if board[x, y] != player: 
                win = False
                continue
              
        if win == True: 
            return(win) 
    return(win) 

def check_column(board, player):
      for x in range(len(board)): 
        win = True
      
        for y in range(len(board)): 
            if board[y][x] != player: 
                win = False
                continue
              
        if win == True: 
            return(win) 
      return(win) 

def check_diagonal(board, player):
    win = True
    y = 0
    for x in range(len(board)): 
        if board[x, x] != player: 
            win = False
    if win: 
        return win 
    win = True
    if win: 
        for x in range(len(board)): 
            y = len(board) - 1 - x 
            if board[x, y] != player: 
                win = False
    return win 


def evaluate(board): 
    winner = 0
   
    for player in [1, 2]: 
        if (check_row(board, player) or
            check_column(board,player) or
            check_diagonal(board,player)): 
              
            winner = player 
           
    if np.all(board != 0) and winner == 0: 
        winner = -1
    return winner

def scenrio(h):
    if h == 1:
        
        board, winner, counter = create_board(k), 0, 1
      
        while winner == 0: 
            for player in [2, 1]:  
                board = first_place(board, player)
                board = random_place(board, player) 
                print("Board after " + str(counter) + " move") 
                print(board)  
                counter += 1
                winner = evaluate(board) 
                if winner != 0: 
                    break
        return(winner) 
        
        scenrio(h)
            
    if h == 2:
        board, winner, counter = create_board(k), 0, 1
      
        while winner == 0: 
            for player in [1, 2]:  
                board = random_place(board, player) 
                print("Board after " + str(counter) + " move") 
                print(board)  
                counter += 1
                winner = evaluate(board) 
                if winner != 0: 
                    break
        return(winner) 
    
def print_and_save_stats():
    
    player1wins=0
    player2wins=0
    ties=0 
    
    for game in range(games):
        result=main(k)
        if result==-1: ties+=1
        elif result==1: player1wins+=1
        else: player2wins+=1
        
        print('Player 1 wins:',player1wins)
        print('Player 2 wins:',player2wins)
        print('Tie:',ties)
 
    # Fake dataset
    height = [player1wins, player2wins, ties]
    bars = ('Player 1', 'Player 2', 'Tie')
    y_pos = np.arange(len(bars))
     
    # Create bars and choose color
    plt.bar(y_pos, height, color = (0.5,0.1,0.5,0.6))
     
    # Add title and axis names
    plt.title('My title')
    plt.xlabel('')
    plt.ylabel('')
     
    # Limits for the Y axis
    plt.ylim(0,games)
     
    # Create names
    plt.xticks(y_pos, bars)
     
    # Show graphic
    plt.show()
    

def main(playing_surface_size):

   k = playing_surface_size

   board, winner, counter = create_board(k), 0, 1
    
   return scenrio(h)

games=int(input("How many games do you want to simulate? "))
k = int(input("How big playing surface (3/5/7)? "))
h = int(input('What scenario? '))

print_and_save_stats()

And my refined code is:

import numpy as np
import random 
import matplotlib.pyplot as plt

# creating an empty board
def create_board(k):
    return np.zeros((k,k), dtype=int)

def possibilities(board): 
 
    lst = [] 
   
    for i in range(len(board)): 
        for j in range(len(board)): 
           
            if board[i][j] == 0: 
                lst.append((i, j)) 
    return(lst)

def first_move(board, k): # here I added k as an element in the def
    l=[]
    
    for i in range(len(board)): 
         for j in range(len(board)): 
             
             if k == 3:
                 if board[i][j] == 0: 
                     l.append((1, 1)) 
             if k == 5:
                 if board[i][j] == 0: 
                     l.append((2, 2)) 
             if k == 7:
                 if board[i][j] == 0: 
                     l.append((3, 3)) 
    return(l) 

def random_place(board, player): 
    selection = possibilities(board) 
    current_loc = random.choice(selection)
    board[current_loc] = player 
    return(board) 

def first_place(board, player, k): # here I added k as an element in the def
    
    player = 1
    selection = first_move(board, k) 
    current_loc = random.choice(selection) 
    board[current_loc] = player 
    return(board) 

def check_row(board, player):
    for x in range(len(board)): 
        win = True
      
        for y in range(len(board)): 
            if board[x, y] != player: 
                win = False
                continue
              
        if win == True: 
            return(win) 
    return(win) 

def check_column(board, player):
      for x in range(len(board)): 
        win = True
      
        for y in range(len(board)): 
            if board[y][x] != player: 
                win = False
                continue
              
        if win == True: 
            return(win) 
      return(win) 

def check_diagonal(board, player):
    win = True
    y = 0
    for x in range(len(board)): 
        if board[x, x] != player: 
            win = False
    if win: 
        return win 
    win = True
    if win: 
        for x in range(len(board)): 
            y = len(board) - 1 - x 
            if board[x, y] != player: 
                win = False
    return win 


def evaluate(board): 
    winner = 0
   
    for player in [1, 2]: 
        if (check_row(board, player) or
            check_column(board,player) or
            check_diagonal(board,player)): 
              
            winner = player 
           
    if np.all(board != 0) and winner == 0: 
        winner = -1
    return winner

def scenrio(h, k): # here I added k as an element in the def
    if h == 1:
        
        board, winner, counter = create_board(k), 0, 1
      
        while winner == 0: 
            for player in [2, 1]:  
                board = first_place(board, player, k) # here I added k as an element
                board = random_place(board, player) 
                print("Board after " + str(counter) + " move") 
                print(board)  
                counter += 1
                winner = evaluate(board) 
                if winner != 0: 
                    break
        return(winner) 
            
    if h == 2:
        board, winner, counter = create_board(k), 0, 1
      
        while winner == 0: 
            for player in [1, 2]:  
                board = random_place(board, player) 
                print("Board after " + str(counter) + " move") 
                print(board)  
                counter += 1
                winner = evaluate(board) 
                if winner != 0: 
                    break
        return(winner) 
    
def print_and_save_stats(games): # here I added games as an element in the def
    
    player1wins=0
    player2wins=0
    ties=0 
    
    for game in range(games): 
        result=main() # here I removed k as an element in main()
        if result==-1: ties+=1
        elif result==1: player1wins+=1
        else: player2wins+=1
        
        print('Player 1 wins:',player1wins)
        print('Player 2 wins:',player2wins)
        print('Tie:',ties)
 
    # Fake dataset
    height = [player1wins, player2wins, ties]
    bars = ('Player 1', 'Player 2', 'Tie')
    y_pos = np.arange(len(bars))
     
    # Create bars and choose color
    plt.bar(y_pos, height, color = (0.5,0.1,0.5,0.6))
     
    # Add title and axis names
    plt.title('My title')
    plt.xlabel('')
    plt.ylabel('')
     
    # Limits for the Y axis
    plt.ylim(0,games)
     
    # Create names
    plt.xticks(y_pos, bars)
     
    # Show graphic
    plt.show()
    

def main(): # here i made a main() function that starts the game and removed playing_surface_size
    
   games=int(input("How many games do you want to simulate? "))
   k = int(input("How big playing surface (3/5/7)? "))
   h = int(input('What scenario? '))
   
   return scenrio(h, k)
   
   return print_and_save_stats(games)

   board, winner, counter = create_board(k), 0, 1

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

looks like you have defined a main() function, but you don't call it.

The usual way to call it is to put this at the bottom of your script

if __name__ == '__main__':
    main()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...