Design a simple two-player strategy game in Python.
- User
Design a simple two-player strategy game in Python.
- Assistant
Design a simple two-player strategy game in Python.
Sure! Let's design a simple two-player strategy game in Python called "Grid Conquest."
Grid Conquest is a turn-based strategy game played on a 5x5 grid. Each player has a set of tokens that they place on the grid. The objective is to align three of your tokens horizontally, vertically, or diagonally before your opponent does. Players take turns placing their tokens on empty cells. If a player cannot place a token, they pass their turn. The first player to align three tokens wins. If the grid is filled without any player aligning three tokens, the game ends in a draw.
Setup:
Gameplay:
Winning Conditions:
Starting the Game:
Taking Turns:
Winning the Game:
Below is the Python code for Grid Conquest. The game uses the console for interaction.
import sys
class GridConquest:
def __init__(self, size=5, win_length=3):
self.size = size
self.win_length = win_length
self.grid = [[' ' for _ in range(size)] for _ in range(size)]
self.tokens = {}
self.players = []
self.current_player_idx = 0
self.moves_left = size * size
def setup_players(self):
print("Welcome to Grid Conquest!")
player1 = input("Enter Player 1 name: ")
player2 = input("Enter Player 2 name: ")
self.players = [
{'name': player1, 'token': 'X'},
{'name': player2, 'token': 'O'}
]
print(f"\n{self.players[0]['name']} is '{self.players[0]['token']}'")
print(f"{self.players[1]['name']} is '{self.players[1]['token']}'\n")
def display_grid(self):
print("\nCurrent Grid:")
header = ' ' + ' '.join(str(i+1) for i in range(self.size))
print(header)
for idx, row in enumerate(self.grid):
row_display = f"{idx+1} " + ' | '.join(row)
print(row_display)
if idx < self.size -1:
print(" " + "---+" * (self.size -1) + "---")
print()
def get_move(self, player):
while True:
try:
move = input(f"{player['name']} ({player['token']}), enter your move as 'row,col': ")
row, col = map(int, move.strip().split(','))
if 1 <= row <= self.size and 1 <= col <= self.size:
if self.grid[row-1][col-1] == ' ':
return row-1, col-1
else:
print("Cell is already occupied. Choose another one.")
else:
print(f"Please enter numbers between 1 and {self.size}.")
except ValueError:
print("Invalid input format. Please enter as 'row,col' (e.g., 2,3).")
def place_token(self, row, col, token):
self.grid[row][col] = token
self.moves_left -= 1
def check_win(self, row, col, token):
# Check all directions: horizontal, vertical, diagonal, anti-diagonal
directions = [
(0, 1), # Horizontal
(1, 0), # Vertical
(1, 1), # Diagonal
(1, -1) # Anti-diagonal
]
for dr, dc in directions:
count = 1
# Check in the positive direction
r, c = row + dr, col + dc
while 0 <= r < self.size and 0 <= c < self.size and self.grid[r][c] == token:
count += 1
r += dr
c += dc
# Check in the negative direction
r, c = row - dr, col - dc
while 0 <= r < self.size and 0 <= c < self.size and self.grid[r][c] == token:
count += 1
r -= dr
c -= dc
if count >= self.win_length:
return True
return False
def play(self):
self.setup_players()
self.display_grid()
while self.moves_left > 0:
current_player = self.players[self.current_player_idx]
row, col = self.get_move(current_player)
self.place_token(row, col, current_player['token'])
self.display_grid()
if self.check_win(row, col, current_player['token']):
print(f"Congratulations {current_player['name']}! You have won the game!")
return
# Switch to the other player
self.current_player_idx = 1 - self.current_player_idx
print("The game is a draw! No more moves left.")
if __name__ == "__main__":
game = GridConquest()
game.play()
Class GridConquest:
__init__: Initializes the game with a 5x5 grid and sets up other necessary variables.setup_players: Prompts users to enter their names and assigns tokens ('X' and 'O') to players.display_grid: Displays the current state of the grid in the console.get_move: Prompts the current player to enter their move in the format 'row,col' and validates the input.place_token: Places the player's token on the specified cell.check_win: Checks whether the current move leads to a win by checking all possible directions from the last placed token.play: The main game loop that manages turns, checks for wins, and declares the outcome.Game Flow:
Prerequisites:
Steps:
grid_conquest.py.grid_conquest.py.python grid_conquest.py
Welcome to Grid Conquest!
Enter Player 1 name: Alice
Enter Player 2 name: Bob
Alice is 'X'
Bob is 'O'
Current Grid:
1 2 3 4 5
1 | | | |
---+---+---+---+---
2 | | | |
---+---+---+---+---
3 | | | |
---+---+---+---+---
4 | | | |
---+---+---+---+---
5 | | | |
Alice (X), enter your move as 'row,col': 1,1
Current Grid:
1 2 3 4 5
1 X | | | |
---+---+---+---+---
2 | | | |
---+---+---+---+---
3 | | | |
---+---+---+---+---
4 | | | |
---+---+---+---+---
5 | | | |
Bob (O), enter your move as 'row,col': 1,2
Current Grid:
1 2 3 4 5
1 X | O | | |
---+---+---+---+---
2 | | | |
---+---+---+---+---
3 | | | |
---+---+---+---+---
4 | | | |
---+---+---+---+---
5 | | | |
... (game continues)
Congratulations Alice! You have won the game!
pygame or tkinter for a better user experience.This simple implementation provides a foundation for a two-player strategy game in Python. You can enhance and expand it further based on your preferences and creativity!