Hacking Course: Explore a vast array of courses spanning different subjects, from technology and arts to business and personal development. Our expert instructors curate each course to ensure you receive top-notch, up-to-date content.
Please click on ads
Please click on ads
Tuesday, 4 July 2023
python game
To create a simple tic-tac-toe game using Python, you can use the following code:
```python
def print_board(board):
print("---------")
for row in board:
print("|", end="")
for cell in row:
print(" " + cell + " ", end="|")
print("\n---------")
def check_winner(board):
# Check rows
for row in board:
if row[0] == row[1] == row[2] != " ":
return row[0]
# Check columns
for col in range(3):
if board[0][col] == board[1][col] == board[2][col] != " ":
return board[0][col]
# Check diagonals
if board[0][0] == board[1][1] == board[2][2] != " ":
return board[0][0]
if board[0][2] == board[1][1] == board[2][0] != " ":
return board[0][2]
return None
def play_game():
board = [[" ", " ", " "], [" ", " ", " "], [" ", " ", " "]]
current_player = "X"
while True:
print_board(board)
row = int(input("Enter the row (0-2): "))
col = int(input("Enter the column (0-2): "))
if board[row][col] != " ":
print("Invalid move. Please try again.")
continue
board[row][col] = current_player
winner = check_winner(board)
if winner:
print_board(board)
print("Player", winner, "wins!")
break
if " " not in board[0] and " " not in board[1] and " " not in board[2]:
print_board(board)
print("It's a tie!")
break
current_player = "O" if current_player == "X" else "X"
play_game()
```
When you run this program, it will prompt players to enter the row and column for their moves, and it will display the current state of the board after each move. It will determine the winner or declare a tie when appropriate. The "X" player always goes first, and the "O" player goes second.
You can modify or enhance this code according to your needs.
Subscribe to:
Post Comments (Atom)
-
https://drive.google.com/drive/u/0/my-drive
-
click here
No comments:
Post a Comment