Hướng dẫn how do you make noughts and crosses in python? - làm thế nào để bạn tạo noughts và crosses trong python?

Có vẻ như nhiều người thích hướng dẫn về việc làm trò chơi. Vâng, hãy để tôi làm một cái quá! Hôm nay chúng ta sẽ triển khai trò chơi "Noughts và Crosses" huyền thoại trong 69 dòng mã Python! Tôi sẽ không quá nhiều vấn đề với OOP và tất cả những điều đó ... một vài chức năng sẽ làm.

Đầu tiên, hãy tạo 2 biến toàn cầu:

# GLOBAL VARIABLES M = [ ['_','_','_'], ['_','_','_'], ['_','_','_'] ] S = True C = 0

M lưu trữ trường 3 x 3 trò chơi của chúng tôi. Cổ điển. Đó là một ma trận 2D, vì vậy tôi gọi nó là M.

# MAIN def xo(): board_show() # FUNCTION NOT YET IMPLEMENTED! while C < 9: turn() # FUNCTION NOT YET IMPLEMENTED! if big_check(): # FUNCTION NOT YET IMPLEMENTED! print(f"{'X' if not S else 'O'} wins!", end="\n\n") break else: # if break not encountered, it must be a tie! print("It's a tie!", end="\n\n")

1 giữ bên: Khi

# MAIN def xo(): board_show() # FUNCTION NOT YET IMPLEMENTED! while C < 9: turn() # FUNCTION NOT YET IMPLEMENTED! if big_check(): # FUNCTION NOT YET IMPLEMENTED! print(f"{'X' if not S else 'O'} wins!", end="\n\n") break else: # if break not encountered, it must be a tie! print("It's a tie!", end="\n\n")

2, đến lượt X và ngược lại.

# MAIN def xo(): board_show() # FUNCTION NOT YET IMPLEMENTED! while C < 9: turn() # FUNCTION NOT YET IMPLEMENTED! if big_check(): # FUNCTION NOT YET IMPLEMENTED! print(f"{'X' if not S else 'O'} wins!", end="\n\n") break else: # if break not encountered, it must be a tie! print("It's a tie!", end="\n\n")

3 giữ số lượng di chuyển được thực hiện.

Bây giờ, hãy viết chức năng chính. Tôi gọi nó là

# MAIN def xo(): board_show() # FUNCTION NOT YET IMPLEMENTED! while C < 9: turn() # FUNCTION NOT YET IMPLEMENTED! if big_check(): # FUNCTION NOT YET IMPLEMENTED! print(f"{'X' if not S else 'O'} wins!", end="\n\n") break else: # if break not encountered, it must be a tie! print("It's a tie!", end="\n\n")

4 vì sự đơn giản. Nó phải:

  1. Hiển thị một bảng trống
  2. Bắt đầu vòng lặp

    # MAIN def xo(): board_show() # FUNCTION NOT YET IMPLEMENTED! while C < 9: turn() # FUNCTION NOT YET IMPLEMENTED! if big_check(): # FUNCTION NOT YET IMPLEMENTED! print(f"{'X' if not S else 'O'} wins!", end="\n\n") break else: # if break not encountered, it must be a tie! print("It's a tie!", end="\n\n")

    5 sẽ lặp lại cho đến khi

    # MAIN def xo(): board_show() # FUNCTION NOT YET IMPLEMENTED! while C < 9: turn() # FUNCTION NOT YET IMPLEMENTED! if big_check(): # FUNCTION NOT YET IMPLEMENTED! print(f"{'X' if not S else 'O'} wins!", end="\n\n") break else: # if break not encountered, it must be a tie! print("It's a tie!", end="\n\n")

    6
  3. Bên trong vòng lặp, nó phải
    1. Yêu cầu người dùng thực hiện một động thái
    2. Kiểm tra xem một trong hai người chơi đã thắng chưa và nếu có, chính

      # MAIN def xo(): board_show() # FUNCTION NOT YET IMPLEMENTED! while C < 9: turn() # FUNCTION NOT YET IMPLEMENTED! if big_check(): # FUNCTION NOT YET IMPLEMENTED! print(f"{'X' if not S else 'O'} wins!", end="\n\n") break else: # if break not encountered, it must be a tie! print("It's a tie!", end="\n\n")

      7
  4. Nếu vòng lặp

    # MAIN def xo(): board_show() # FUNCTION NOT YET IMPLEMENTED! while C < 9: turn() # FUNCTION NOT YET IMPLEMENTED! if big_check(): # FUNCTION NOT YET IMPLEMENTED! print(f"{'X' if not S else 'O'} wins!", end="\n\n") break else: # if break not encountered, it must be a tie! print("It's a tie!", end="\n\n")

    5 không gặp phải

    # MAIN def xo(): board_show() # FUNCTION NOT YET IMPLEMENTED! while C < 9: turn() # FUNCTION NOT YET IMPLEMENTED! if big_check(): # FUNCTION NOT YET IMPLEMENTED! print(f"{'X' if not S else 'O'} wins!", end="\n\n") break else: # if break not encountered, it must be a tie! print("It's a tie!", end="\n\n")

    7 trên đường đi, điều đó có nghĩa là 9 động tác được thực hiện, nhưng không ai thắng, vì vậy nó phải là một sự ràng buộc!

# MAIN def xo(): board_show() # FUNCTION NOT YET IMPLEMENTED! while C < 9: turn() # FUNCTION NOT YET IMPLEMENTED! if big_check(): # FUNCTION NOT YET IMPLEMENTED! print(f"{'X' if not S else 'O'} wins!", end="\n\n") break else: # if break not encountered, it must be a tie! print("It's a tie!", end="\n\n")

Chức năng dễ dàng nhất để thực hiện là

def board_show(): print() for y in range(3): print(" ", end="") for x in range(3): print(M[y][x], end=" ") print() print()

0. Chỉ cần in ra ma trận nhỏ của chúng tôi M. Đừng quên đặt một số

def board_show(): print() for y in range(3): print(" ", end="") for x in range(3): print(M[y][x], end=" ") print() print()

2 trống cho mục đích khoảng cách!

def board_show(): print() for y in range(3): print(" ", end="") for x in range(3): print(M[y][x], end=" ") print() print()

Bây giờ, chức năng

def board_show(): print() for y in range(3): print(" ", end="") for x in range(3): print(M[y][x], end=" ") print() print()

3 khó khăn hơn một chút, nhưng cũng không quá phức tạp. Chúng tôi muốn:

  1. Hỏi người chơi nơi anh ấy/cô ấy muốn đặt dấu ấn của mình
  2. Kiểm tra xem hình vuông đã chọn có miễn phí không và nếu là, hãy đặt X hoặc O vào nó, thay đổi

    # MAIN def xo(): board_show() # FUNCTION NOT YET IMPLEMENTED! while C < 9: turn() # FUNCTION NOT YET IMPLEMENTED! if big_check(): # FUNCTION NOT YET IMPLEMENTED! print(f"{'X' if not S else 'O'} wins!", end="\n\n") break else: # if break not encountered, it must be a tie! print("It's a tie!", end="\n\n")

    1Tate và

    def board_show(): print() for y in range(3): print(" ", end="") for x in range(3): print(M[y][x], end=" ") print() print()

    0 để chứng minh kết quả
  3. Nếu nó không trống, chúng tôi muốn cho người dùng biết rằng việc di chuyển không hợp lệ và khiến anh ta lặp lại nó

def turn(): global S, C # allows us to reference S that is not assigned in this scope pos = [ ( int(i) - 1 ) for i in input("Your move: ").split() ] # this produces a list of two int values X and Y # it reduces each one by 1 since computer (unlike human) starts counting from 0 x, y = pos[0], pos[1] # save x and y separately for clearance if M[y][x] == '_': M[y][x] = 'X' if S else 'O' S = not S C += 1 # increment move counter C by 1 only if the move is valid board_show() else: print("Invalid move!")

Không thể suy ra loại mime hình ảnh

Bây giờ chúng ta có chức năng

def board_show(): print() for y in range(3): print(" ", end="") for x in range(3): print(M[y][x], end=" ") print() print()

3 của chúng ta tốt đẹp và tỏa sáng, chúng ta chỉ cần hàm

def board_show(): print() for y in range(3): print(" ", end="") for x in range(3): print(M[y][x], end=" ") print() print()

7, chỉ có điều không dễ dàng.

def board_show(): print() for y in range(3): print(" ", end="") for x in range(3): print(M[y][x], end=" ") print() print()

7 không được gọi là lớn mà không có lý do - nó bao gồm ba chức năng khác:

  1. def board_show(): print() for y in range(3): print(" ", end="") for x in range(3): print(M[y][x], end=" ") print() print()

    9 Kiểm tra hàng

    def turn(): global S, C # allows us to reference S that is not assigned in this scope pos = [ ( int(i) - 1 ) for i in input("Your move: ").split() ] # this produces a list of two int values X and Y # it reduces each one by 1 since computer (unlike human) starts counting from 0 x, y = pos[0], pos[1] # save x and y separately for clearance if M[y][x] == '_': M[y][x] = 'X' if S else 'O' S = not S C += 1 # increment move counter C by 1 only if the move is valid board_show() else: print("Invalid move!")

    0th
  2. def turn(): global S, C # allows us to reference S that is not assigned in this scope pos = [ ( int(i) - 1 ) for i in input("Your move: ").split() ] # this produces a list of two int values X and Y # it reduces each one by 1 since computer (unlike human) starts counting from 0 x, y = pos[0], pos[1] # save x and y separately for clearance if M[y][x] == '_': M[y][x] = 'X' if S else 'O' S = not S C += 1 # increment move counter C by 1 only if the move is valid board_show() else: print("Invalid move!")

    1 Kiểm tra cột

    def turn(): global S, C # allows us to reference S that is not assigned in this scope pos = [ ( int(i) - 1 ) for i in input("Your move: ").split() ] # this produces a list of two int values X and Y # it reduces each one by 1 since computer (unlike human) starts counting from 0 x, y = pos[0], pos[1] # save x and y separately for clearance if M[y][x] == '_': M[y][x] = 'X' if S else 'O' S = not S C += 1 # increment move counter C by 1 only if the move is valid board_show() else: print("Invalid move!")

    2
  3. def turn(): global S, C # allows us to reference S that is not assigned in this scope pos = [ ( int(i) - 1 ) for i in input("Your move: ").split() ] # this produces a list of two int values X and Y # it reduces each one by 1 since computer (unlike human) starts counting from 0 x, y = pos[0], pos[1] # save x and y separately for clearance if M[y][x] == '_': M[y][x] = 'X' if S else 'O' S = not S C += 1 # increment move counter C by 1 only if the move is valid board_show() else: print("Invalid move!")

    3 Kiểm tra cả hai đường chéo

Nhưng đây khá đơn giản và bạn sẽ thấy tại sao trong một giây. Điều duy nhất chúng ta cần làm là kiểm tra xem cả ba vị trí có cùng

def turn(): global S, C # allows us to reference S that is not assigned in this scope pos = [ ( int(i) - 1 ) for i in input("Your move: ").split() ] # this produces a list of two int values X and Y # it reduces each one by 1 since computer (unlike human) starts counting from 0 x, y = pos[0], pos[1] # save x and y separately for clearance if M[y][x] == '_': M[y][x] = 'X' if S else 'O' S = not S C += 1 # increment move counter C by 1 only if the move is valid board_show() else: print("Invalid move!")

4 trong đó không phải là

def turn(): global S, C # allows us to reference S that is not assigned in this scope pos = [ ( int(i) - 1 ) for i in input("Your move: ").split() ] # this produces a list of two int values X and Y # it reduces each one by 1 since computer (unlike human) starts counting from 0 x, y = pos[0], pos[1] # save x and y separately for clearance if M[y][x] == '_': M[y][x] = 'X' if S else 'O' S = not S C += 1 # increment move counter C by 1 only if the move is valid board_show() else: print("Invalid move!")

5 mặc định hay không.

def check_hr(y): return M[y][0] == M[y][1] == M[y][2] != '_' def check_vr(x): return M[0][x] == M[1][x] == M[2][x] != '_' def check_dig(): return M[0][0] == M[1][1] == M[2][2] != '_' or \ M[0][2] == M[1][1] == M[2][0] != '_'

Bây giờ, chúng ta hãy đến với

def board_show(): print() for y in range(3): print(" ", end="") for x in range(3): print(M[y][x], end=" ") print() print()

7. Những gì về cơ bản là nó kiểm tra mọi hàng, cột và đường chéo bằng cách sử dụng các chức năng mà chúng tôi vừa viết và nếu ít nhất một trong số các hàm đó trả về

def turn(): global S, C # allows us to reference S that is not assigned in this scope pos = [ ( int(i) - 1 ) for i in input("Your move: ").split() ] # this produces a list of two int values X and Y # it reduces each one by 1 since computer (unlike human) starts counting from 0 x, y = pos[0], pos[1] # save x and y separately for clearance if M[y][x] == '_': M[y][x] = 'X' if S else 'O' S = not S C += 1 # increment move counter C by 1 only if the move is valid board_show() else: print("Invalid move!")

7, toàn bộ hàm

def board_show(): print() for y in range(3): print(" ", end="") for x in range(3): print(M[y][x], end=" ") print() print()

7 phải trả về

def turn(): global S, C # allows us to reference S that is not assigned in this scope pos = [ ( int(i) - 1 ) for i in input("Your move: ").split() ] # this produces a list of two int values X and Y # it reduces each one by 1 since computer (unlike human) starts counting from 0 x, y = pos[0], pos[1] # save x and y separately for clearance if M[y][x] == '_': M[y][x] = 'X' if S else 'O' S = not S C += 1 # increment move counter C by 1 only if the move is valid board_show() else: print("Invalid move!")

7!

def big_check(): win = False for i in range(3): if check_hr(i) or check_vr(i): win = True if check_dig(): win = True return win

"Bây giờ chúng tôi có tất cả mọi thứ! Nó đã hoàn thành!" - Một người mới sẽ nói, nhưng không, nó thực sự không. Có một chút cuối cùng của nó cuối cùng sẽ làm cho nó hoạt động - dòng thứ 69:

xo() # invoke the xo() function

Tôi đã làm hết sức mình để bình luận về lý do tại sao tôi làm mọi thứ và tại sao tôi gỡ bỏ mọi thứ. Tôi hy vọng ví dụ này giúp bạn thấy lý do tại sao không thể sử dụng các lớp khi làm việc với Python. Tôi đã thêm một số tính năng khác mà tôi nghĩ có thể giúp bạn khi bạn tiếp tục học lập trình

import random

# Lets put all these functions into a class
class Game:

    # Lets set up the game
    def __init__(self, player_one="X", player_two="O"):

        self.player_one = player_one
        self.player_two = player_two

        # Where the game board is stored
        # Using periods instead of spaces so the players can see the possible moves
        self.game_board = [
                            [".", ".", "."],
                            [".", ".", "."],
                            [".", ".", "."]
                          ]


        # This value is to check if the game is still going
        self.running = True

        # Whos turn is it?
        self.active_player = ""

        # The tasks we HAVE to do to make the game work
        self.start_player()
        self.run_game()

    # The function is part of the Game class so we have to pass self into it.
    def start_player(self):

        # Randomly Choose a starting player
        startplayer = random.randint(1,2)

        if startplayer == 1:
            # We declared the string values in the __init__ function
            player = self.player_one
            print("Player One ({}) will start the game.".format(player))
        else:
            startplayer == 2
            player = self.player_two
            print("Player Two ({}) will start the game.".format(player))

        # Set the initial player
        self.active_player = player

    def get_move(self):
        # Seems silly to have them enter the rows and columns one by one
        #row = int(input("Please enter a number between 0 and 2: "))
        #column = int(input("Please enter a number between 0 and 2: "))

        # Show the player whos turn it is
        input_data = input("Player ({}) please choose a Column and a Row: ".format(self.active_player))

        # Default values that aren't in the game, if they arent changed they will be caught
        row = -1
        column = -1

        # Users entry all types of funky data, lets make sure its right
        try:    
            r, c = input_data.split(" ")

            r = int(r)
            c = int(c)

            if r >= 0 and r <= 3:
                row = int(r)

            if c >= 0 and c <= 3:
                column = int(c)
        except:
            print("Enter only two numbers (0, 1, or 2) seperated by a space")

        return row, column

        # This check for the grid should be its own function
        #while grid[row][column] != "":
        #   print("Invalid move.")
        #   row = int(input("Please enter a number between 0 and 2: "))
        #   column = int(input("Please enter a number between 0 and 2: ")) 

    def check_move(self, row, column):

        if row == -1 or column == -1:
            return False

        # If the space is blank return True
        if self.game_board[row][column] == ".":
            return True
        print("{} {} is an invalid move, try again".format(row, column))
        return False

    # Add another function to print out the board for us
    def show_board(self):
        for row in self.game_board:
            row_string = ""
            for cell in row:
                row_string = "{} {} ".format(row_string, cell)
            print(row_string)


    #def mainturn(row, column):

    # Try to avoid using globals. We'll store these in our class

    #global countmove
    #countmove = countmove + 1
    #global symbol
    #grid[row][column] = symbol

    #for y in range(0,(len(grid))):
    #    print(grid[y])
    #if symbol == 'X':
    #    symbol = 'O'
    #elif symbol == 'O':
    #    symbol = 'X'
    #return countmove

    # This is one heck of an if statement. Lets turn it into a function
    # if (grid[0][0] and grid[0][1] and grid[0][2] == symbol) or (grid[1][0] and grid[1][1] and grid[1][2] == symbol) or (grid[2][0] and grid[2][1] and grid[2][2] == symbol) or (grid[0][0] and grid[1][0] and grid[2][0] == symbol) or (grid[0][1] and grid[1][1] and grid[2][1] == symbol)or (grid[0][2] and grid[1][2] and grid[2][2] == symbol)or (grid[0][0] and grid[1][1] and grid[2][2] == symbol) or (grid[2][0] and grid[1][1] and grid[0][2] == symbol):

    def check_win(self, symbol):
        combinations = [
            # horizontal
            [(0,0), (1,0), (2,0)],
            [(0,1), (1,1), (2,1)],
            [(0,2), (1,2), (2,2)],
            # vertical
            [(0,0), (0,1), (0,2)],
            [(1,0), (1,1), (1,2)],
            [(2,0), (2,1), (2,2)],
            # crossed
            [(0,0), (1,1), (2,2)],
            [(2,0), (1,1), (0,2)]
            ]

        for coordinates in combinations:
            letters = [self.game_board[x][y] for x, y in coordinates]

            # If all the letters match
            if "." not in letters:
                if len(set(letters)) <= 1:
                    # returns corresponding letter for winner (X/O)
                    print("Well done {}!  You won the game!".format(symbol))
                    self.running = False
                    return True

        return False

    # Lets try another method of checking if the board is full
    #elif countmove == 9:
    #    print("Board Full. Game over.")
    #main program
    def board_full(self):
        for row in self.game_board:
            if "." in row:
                return False
        print("The game is a draw :( ")

        # Stop the game
        self.running = False

        return True

    def run_game(self):
        # While the game is not over
        while self.running != False:

            # Show the player the board
            self.show_board()

            row, column = self.get_move()

            # Is the move valid?
            if self.check_move(row, column):
                self.game_board[row][column] = self.active_player

                # Did they win?
                self.check_win(self.active_player)  

                # Change Players
                if self.active_player == self.player_one:
                    self.active_player = self.player_two
                else:
                    self.active_player = self.player_one
        # Print the winning game board
        self.show_board()

g = Game("X", "O")
    # Handled this in the class
    #grid = [["","",""],["","",""],["","",""]]

    #countmove = 0

    #win = 'false'

    # Turned this code into the show_board function
    #for y in range(0,(len(grid))):

    #print(grid[y])
    #symbol = start_player()

    #while countmove != 9 or win == 'false':

        # Shouldnt reset the countmove inside of the loop thats checking the countmove
        #countmove = 0

        #row, column = getmove()

        #mainturn(row,column)

        #win = check_win(row,column, symbol)

Ví dụ đầu ra:

Player One (X) will start the game.
 .  .  . 
 .  .  . 
 .  .  . 
Player (X) please choose a Column and a Row: 0 1
 .  X  . 
 .  .  . 
 .  .  . 
Player (O) please choose a Column and a Row: 2 2
 .  X  . 
 .  .  . 
 .  .  O 
Player (X) please choose a Column and a Row: 0 0
 X  X  . 
 .  .  . 
 .  .  O 
Player (O) please choose a Column and a Row: 2 1
 X  X  . 
 .  .  . 
 .  O  O 
Player (X) please choose a Column and a Row: 0 2
Well done X!  You won the game!
 X  X  X 
 .  .  . 
 .  O  O