Programming-Challenges/Practice Assignment 5/main.py

91 lines
3.1 KiB
Python

import random
import os
def load_board(filepath="board.txt"):
snakes, ladders = {}, {}
try:
with open(filepath, "r") as f:
for line in f:
if line.startswith("Snakes:"):
pairs = line.replace("Snakes:", "").strip().split(", ")
snakes = {int(p.split(":")[0]): int(p.split(":")[1]) for p in pairs if ":" in p}
elif line.startswith("Ladders:"):
pairs = line.replace("Ladders:", "").strip().split(", ")
ladders = {int(p.split(":")[0]): int(p.split(":")[1]) for p in pairs if ":" in p}
except FileNotFoundError:
print("Warning: board.txt not found. Loading standard board layout.")
snakes = {12: 2, 14: 11, 17: 4, 31: 19, 35: 22}
ladders = {3: 16, 5: 7, 15: 25, 18: 20, 21: 32}
return snakes, ladders
def load_messages(filepath="messages.txt"):
msgs = {
"ladder": "A ladder moved you up to square {pos}!",
"snake": "A snake caught you! Slid down to square {pos}.",
"win": "Congratulations {player}! You won the game with {score} points!"
}
try:
with open(filepath, "r") as f:
for line in f:
if "=" in line:
k, v = line.strip().split("=", 1)
msgs[k.strip()] = v.strip()
except FileNotFoundError:
pass
return msgs
def display_board(p1_pos, p2_pos):
print("\n" + "=" * 42)
for row in range(5, -1, -1):
line = ""
for col in range(1, 7):
sq = row * 6 + col
tokens = []
if sq == p1_pos: tokens.append("P1")
if sq == p2_pos: tokens.append("P2")
label = "/".join(tokens) if tokens else f"{sq:02d}"
line += f"[{label:^5}]"
print(line)
print("=" * 42)
def main():
snakes, ladders = load_board()
msgs = load_messages()
p1 = input("Enter Player 1 name: ").strip() or "Player 1"
p2 = input("Enter Player 2 name: ").strip() or "Player 2"
positions = {p1: 1, p2: 1}
turns = {p1: 0, p2: 0}
players = [p1, p2]
turn_idx = 0
while True:
curr = players[turn_idx]
input(f"\n{curr}'s turn (Square {positions[curr]}). Press Enter to roll dice...")
d1, d2 = random.randint(1, 6), random.randint(1, 6)
roll = d1 + d2
turns[curr] += 1
print(f"{curr} rolled {d1} and {d2} (Total: {roll})")
new_pos = positions[curr] + roll
if new_pos in ladders:
new_pos = ladders[new_pos]
print(msgs["ladder"].format(pos=new_pos))
elif new_pos in snakes:
new_pos = snakes[new_pos]
print(msgs["snake"].format(pos=new_pos))
positions[curr] = min(new_pos, 36)
display_board(positions[p1], positions[p2])
if positions[curr] >= 36:
score = max(100 - (turns[curr] * 5), 10)
print(msgs["win"].format(player=curr, score=score))
break
turn_idx = (turn_idx + 1) % 2
if __name__ == "__main__":
main()