Programming-Challenges/25 Create a magic square/exercise-01.py

172 lines
5.5 KiB
Python

import random
class Board:
def __init__(self, rows, columns):
self.rows = rows
self.columns = columns
self.grid = [["O" for i in range(columns)] for j in range(rows)]
self.player_location = (7, 0) # bottom left
self.previous_location = None
self.magic_square_location = None
def format_grid(self):
header = " " + " ".join(f"{j:>2}" for j in range(self.columns)) + "\n"
result = header
for i in range(self.rows):
row_cells = []
for j in range(self.columns):
if (i, j) == self.player_location:
row_cells.append(" *")
elif (i, j) == self.magic_square_location:
row_cells.append(" X")
else:
row_cells.append(f" {self.grid[i][j]}")
result += f"{i:>2} " + " ".join(row_cells) + "\n"
return result
def create_magic_square_location(self):
self.magic_square_location = (
random.randint(0, self.rows - 1),
random.randint(0, self.columns - 1)
)
print(f"Magic square created at location: {self.magic_square_location}")
def check_magic_square(self):
if self.player_location == self.magic_square_location:
print(f"🎉 You found the magic square at {self.magic_square_location}!")
return True
return False
def move(self, x, y):
row, col = self.player_location
vertical_direction = self._get_vertical_movement()
vertical_magnitude = self._get_number_of_squares()
new_row = self._check_vertical_move(row, vertical_direction, vertical_magnitude)
if new_row is None:
print("Invalid Y move: the game is over")
return None
horizontal_direction = self._get_horizontal_movement()
horizontal_magnitude = self._get_number_of_squares()
new_col = self._check_horizontal_move(col, horizontal_direction, horizontal_magnitude)
if new_col is None:
print("Invalid X move: the game is over")
return None
self.previous_location = (row, col)
self.grid[row][col] = "O"
self.grid[new_row][new_col] = "*"
self.player_location = (new_row, new_col)
print(f"Previous location: {self.previous_location} now shows 'O'")
print(self.format_grid())
return self.player_location
def _get_vertical_movement(self):
while True:
direction = input("Vertical direction (u for up, d for down): ").strip().lower()
if direction in ["u", "d"]:
return direction
print("Invalid direction. Please enter 'u' or 'd'.")
def _get_horizontal_movement(self):
while True:
direction = input("Horizontal direction (l for left, r for right): ").strip().lower()
if direction in ["l", "r"]:
return direction
print("Invalid direction. Please enter 'l' or 'r'.")
def _get_number_of_squares(self):
while True:
try:
magnitude = int(input("Number of squares to move: "))
if magnitude > 0:
return magnitude
print("Please enter a positive number.")
except ValueError:
print("Invalid input. Please enter a number.")
def _check_vertical_move(self, current_row, direction, magnitude):
if direction == "u":
new_row = current_row - magnitude
else:
new_row = current_row + magnitude
if 0 <= new_row <= self.rows - 1:
return new_row
else:
return None
def _check_horizontal_move(self, current_col, direction, magnitude):
if direction == "r":
new_col = current_col + magnitude
else:
new_col = current_col - magnitude
if 0 <= new_col <= self.columns - 1:
return new_col
else:
return None
def ask_to_continue():
while True:
response = input("\nDo you want to continue playing? (Y/N): ").strip().upper()
if response == "Y":
return True
elif response == "N":
return False
else:
print("Invalid input. Please enter 'Y' or 'N'.")
def main():
board = Board(8, 8)
print(board.format_grid())
game_running = True
round_number = 0
while game_running:
round_number += 1
print(f"\n{'='*50}")
print(f"ROUND {round_number}")
print(f"{'='*50}")
board.create_magic_square_location()
print(board.format_grid())
moves_made = 0
max_moves = 5
round_won = False
while moves_made < max_moves:
print(f"\nMove {moves_made + 1} of {max_moves}:")
move = board.move(0, 0)
if move is None:
print("Game Over! You made an invalid move.")
break
if board.check_magic_square():
round_won = True
break
moves_made += 1
if round_won:
print(f"\n✓ You won this round!")
elif moves_made == max_moves:
print(f"\nYou completed {max_moves} moves without finding the magic square.")
game_running = ask_to_continue()
print("\nThanks for playing! Game ended.")
if __name__ == "__main__":
main()