Pyscript game version

This commit is contained in:
Mr Finchum 2025-03-16 23:22:14 +00:00
parent 433984bfb2
commit 54cd9d838b
5 changed files with 257 additions and 79 deletions

View file

@ -1,103 +1,136 @@
import random
from pyscript import document
def rock(lst, n):
for _ in range(n):
lst.append("Rock")
return lst
class RPSGame:
def __init__(self, best_of = 3):
self.user_score = 0
self.ai_score = 0
self.deck = self.build_deck()
self.user_hand, self.ai_hand = self.give_cards()
self.rounds_to_win = (best_of // 2) + 1
self.update_ui()
def paper(lst, n):
for _ in range(n):
lst.append("Paper")
return lst
def build_deck(self):
cards = [self.rock, self.paper, self.scissors]
deck = []
def scissors(lst, n):
for _ in range(n):
lst.append("Scissors")
return lst
random.shuffle(cards)
for i in range(2):
n = random.randint(5, 20)
deck = cards[i](deck, n)
def build_deck():
cards = [rock, paper, scissors]
deck = []
missing_cards = 52 - len(deck)
deck = cards[2](deck, missing_cards)
random.shuffle(deck)
return deck
random.shuffle(cards)
for i in range(2):
n = random.randint(5, 20)
deck = cards[i](deck, n)
def rock(self, lst, n):
lst.extend(["Rock"] * n)
return lst
missing_cards = 52 - len(deck)
deck = cards[2](deck, missing_cards)
random.shuffle(deck)
return deck
def paper(self, lst, n):
lst.extend(["Paper"] * n)
return lst
def give_cards(deck):
"""Give 3 cards to both player and AI, removing them from the deck."""
return [deck.pop(0) for _ in range(3)], [deck.pop(0) for _ in range(3)]
def scissors(self, lst, n):
lst.extend(["Scissors"] * n)
return lst
def battle(user_card, ai_card):
"""Returns 1 if user wins, -1 if AI wins, 0 for a tie."""
if user_card == ai_card:
return 0
if (user_card == "Rock" and ai_card == "Scissors") or \
(user_card == "Paper" and ai_card == "Rock") or \
(user_card == "Scissors" and ai_card == "Paper"):
return 1
return -1
def give_cards(self):
return [self.deck.pop(0) for _ in range(3)], [self.deck.pop(0) for _ in range(3)]
def play_cards(user_hand, ai_hand):
"""Handles playing cards until a winner is determined or cards run out."""
while user_hand and ai_hand: # Keep playing until hands are empty
print(f"\nYour cards: {user_hand}")
def battle(self, user_card, ai_card):
if user_card == ai_card:
return 0
if (user_card == "Rock" and ai_card == "Scissors") or \
(user_card == "Paper" and ai_card == "Rock") or \
(user_card == "Scissors" and ai_card == "Paper"):
return 1
return -1
while True:
try:
user_choice = int(input(f"Select a card (1-{len(user_hand)}): ")) - 1
if 0 <= user_choice < len(user_hand):
break
except ValueError:
pass
print("Invalid choice. Try again.")
def refresh_hand(self):
self.user_hand, self.ai_hand = self.give_cards()
print("New cards")
print(f"AI cards: {self.ai_hand}")
user_card = user_hand.pop(user_choice)
ai_choice = random.randint(0, len(ai_hand) - 1)
ai_card = ai_hand.pop(ai_choice)
def play_card(self, event):
index = int(event.target.getAttribute("index"))
#print(f"Button {index} clicked!") # Debugging
if index >= len(self.user_hand):
return
print(f"You played: {user_card}, AI played: {ai_card}")
user_card = self.user_hand.pop(index)
ai_card = self.ai_hand.pop(random.randint(0, len(self.ai_hand) - 1))
result = battle(user_card, ai_card)
result = self.battle(user_card, ai_card)
if result == 1:
print("You win this round!")
return 1 # User wins
self.user_score += 1
round_result = f"You win! {user_card} beats {ai_card}."
self.refresh_hand()
elif result == -1:
print("AI wins this round!")
return -1 # AI wins
self.ai_score += 1
round_result = f"AI wins! {ai_card} beats {user_card}."
self.refresh_hand()
else:
print("It's a tie! Play again with remaining cards.")
round_result = "It's a tie! Try again"
print("No cards left, this round is a draw.")
return 0 # Round is a draw
if not self.user_hand or not self.ai_hand:
self.refresh_hand()
if self.user_score < self.rounds_to_win and self.ai_score < self.rounds_to_win:
pass
else:
if self.user_score < self.ai_score:
round_result = "You lost noob D:"
self.update_ui(round_result)
self.disable_buttons()
#self.reset_game()
return
else:
round_result = "You won great :D"
self.update_ui(round_result)
self.disable_buttons()
#self.reset_game()
return
def play_game(best_of = 3):
"""Main game loop."""
my_deck = build_deck()
user_score, ai_score = 0, 0
rounds_to_win = (best_of // 2) + 1
self.update_ui(round_result)
while user_score < rounds_to_win and ai_score < rounds_to_win and len(my_deck) >= 6:
user_hand, ai_hand = give_cards(my_deck)
def update_ui(self, result_text="Waiting for your move..."):
print("Update UI")
document.querySelector("#user-score").innerText = str(self.user_score)
document.querySelector("#ai-score").innerText = str(self.ai_score)
document.querySelector("#result").innerText = result_text
document.querySelector("#reset-game").disabled = False
for i in range(3):
btn = document.querySelector(f"#card-{i}")
if i < len(self.user_hand):
btn.innerText = self.user_hand[i]
btn.disabled = False
else:
btn.innerText = "?"
btn.disabled = True
round_result = play_cards(user_hand, ai_hand)
def disable_buttons(self):
for i in range(3):
btn = document.querySelector(f"#card-{i}")
btn.innerText = "?"
btn.disabled = True
if round_result == 1:
user_score += 1
elif round_result == -1:
ai_score += 1
def reset_game(self, event=None):
print("Game Reset")
self.user_score = 0
self.ai_score = 0
self.deck = self.build_deck()
self.user_hand, self.ai_hand = self.give_cards()
self.deck_overview()
self.update_ui("Game reset! Pick a card to start.")
print(f"Score - You: {user_score}, AI: {ai_score}")
if user_score > ai_score:
print("\n🎉 You won the match!")
else:
print("\n🤖 AI won the match!")
def deck_overview(self):
#print(f"{len(self.deck)} Cards left")
print(f"{self.deck.count('Rock')} Rock cards")
print(f"{self.deck.count('Paper')} Paper cards")
print(f"{self.deck.count('Scissors')} Scissors cards")
# Run the game
play_game(best_of = 5)
# Start the game
game = RPSGame(5)
game.deck_overview()