簡體   English   中英

放入 main() 定義時代碼不起作用

[英]Code doesn't work while put in main() definition

我正在嘗試為自動井字游戲改進我的代碼,您可以在其中查看 player1 如果他將第一步放在中間是否具有優勢。 我現在正在嘗試改進我的代碼,因為它有點亂,但是當我嘗試這樣做時,程序不再工作,我不明白為什么。

簡單介紹一下我的程序:開始的時候會問How many games do you want to simulate? ,那么你必須在How big playing surface (3/5/7)? 最后你必須選擇你想在什么場景下玩What scenario? ,其中 1 = player1 從中間開始,所有其他動作都是自動的,2 = 所有動作都是自動的。 然后,您將獲得包含所有游戲回合統計數據的直方圖。

我開始的代碼在底部有程序的實際啟動,沒有定義它們,即我的“游戲”、“k”和“h”的定義適用於所有定義。 我想改變這一點,以便 main() function 開始游戲,所以我把它們放在 main() 下。 我還在所有需要它們的功能中添加了“游戲”、“k”和“h”作為元素。 但是現在即使我在“ How many games do you want to simulate? 它既不打印統計數據。

我將添加我的兩個代碼,它主要是我已更改的最后一個 main() function,並且還標記了關於我已更改的內容的注釋。 我希望有人可以幫我看看為什么這不起作用? 雖然我沒有在代碼中添加新的東西,但對我來說似乎很奇怪,只是將最后一個代碼放在 function 下。 我的第一個代碼:

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()

我的精煉代碼是:

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

看起來你已經定義了一個main() function,但你沒有調用它。

調用它的通常方法是將其放在腳本的底部

if __name__ == '__main__':
    main()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM