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
.
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.
# 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"]
Bây giờ, hãy viết chức năng chính. Tôi gọi nó là
4 vì sự đơn giản. Nó 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"]
- Hiển thị một bảng trống
- Bắt đầu vòng lặp
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# 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"]
- Bên trong vòng lặp, nó phải
- Yêu cầu người dùng thực hiện một động thái
- Kiểm tra xem một trong hai người chơi đã thắng chưa và nếu có, chính
7# 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"]
- Nếu vòng lặp
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"]
# 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à
0. Chỉ cần in ra ma trận nhỏ của chúng tôi
def board_show[]: print[] for y in range[3]: print[" ", end=""] for x in range[3]: print[M[y][x], end=" "] print[] print[]
M
. Đừng quên đặt một số 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[]
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
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:
def board_show[]: print[] for y in range[3]: print[" ", end=""] for x in range[3]: print[M[y][x], end=" "] print[] print[]
- Hỏi người chơi nơi anh ấy/cô ấy muốn đặt dấu ấn của mình
- 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
1Tate và# 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"]
0 để chứng minh kết quảdef board_show[]: print[] for y in range[3]: print[" ", end=""] for x in range[3]: print[M[y][x], end=" "] print[] print[]
- 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
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:
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àngdef board_show[]: print[] for y in range[3]: print[" ", end=""] for x in range[3]: print[M[y][x], end=" "] print[] print[]
0thdef 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ộtdef 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!"]
2def 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éodef 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!"]
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
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 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!"]
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
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 board_show[]: print[] for y in range[3]: print[" ", end=""] for x in range[3]: print[M[y][x], end=" "] print[] print[]
7, toàn bộ hàm
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 phải trả về
def board_show[]: print[] for y in range[3]: print[" ", end=""] for x in range[3]: print[M[y][x], end=" "] print[] print[]
7!
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!"]
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 = 0 and c