简体   繁体   English

放入 main() 定义时代码不起作用

[英]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.我正在尝试为自动井字游戏改进我的代码,您可以在其中查看 player1 如果他将第一步放在中间是否具有优势。 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?简单介绍一下我的程序:开始的时候会问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)? ,那么你必须在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?最后你必须选择你想在什么场景下玩What scenario? , where 1 = player1 starts in the middle and all the other moves are automatic and 2 = all the moves are automatic. ,其中 1 = player1 从中间开始,所有其他动作都是自动的,2 = 所有动作都是自动的。 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.我开始的代码在底部有程序的实际启动,没有定义它们,即我的“游戏”、“k”和“h”的定义适用于所有定义。 I wanted to change this so that the main() function started the game instead, so I put these under main().我想改变这一点,以便 main() function 开始游戏,所以我把它们放在 main() 下。 And I also added "games", "k" and "h" as elements in all functions where they were needed.我还在所有需要它们的功能中添加了“游戏”、“k”和“h”作为元素。 But now it only does one game even though I type 10 on the question How many games do you want to simulate?但是现在即使我在“ 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.我将添加我的两个代码,它主要是我已更改的最后一个 main() function,并且还标记了关于我已更改的内容的注释。 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.虽然我没有在代码中添加新的东西,但对我来说似乎很奇怪,只是将最后一个代码放在 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

looks like you have defined a main() function, but you don't call it.看起来你已经定义了一个main() function,但你没有调用它。

The usual way to call it is to put this at the bottom of your script调用它的通常方法是将其放在脚本的底部

if __name__ == '__main__':
    main()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM