Game
Game
CS3B
def spin_row():
"""
Creates a list of possible symbols.
Returns a list of three randomly chosen symbols.
"""
def print_row(row):
#Joins the symbols in the row with " | " and prints them.
print(' | '.join(row))
if row[0] == '🍒':
return bet * 3
def main():
"""
Main function to run the slot machine game.
"""
balance = 100
#Initializes the player's balance to $100.
print('Symbols: 🍒 🍉 🍋 🔔 ⭐')
#Prints a welcome message and the symbols
bet = int(bet)
# Calculate payout
payout = get_payout(row, bet)
if __name__ == '__main__':
main()
I used OOP to encapsulate functionality and make the code more modular and maintainable.
import random
class SlotMachine:
def __init__(self):
def spin_row(self):
"""
Spins the slot machine and returns a row of three random symbols.
"""
return [random.choice(self.symbols) for _ in range(3)]
if row[0] == '🍒':
return bet * 3
class Player:
def __init__(self, balance=100):
self.balance = balance
def place_bet(self):
"""
Prompts the player to place a bet and returns the bet amount.
"""
while True:
bet = input('Place your bet amount: ')
if not bet.isdigit():
print('Enter a valid number')
continue
bet = int(bet)
if bet > self.balance:
print('Insufficient funds')
elif bet <= 0:
print('Bet must be greater than 0')
else:
return bet
def get_balance(self):
"""
Returns the player's current balance.
"""
return self.balance
def main():
player = Player(balance=100)
slot_machine = SlotMachine()
print('Symbols: 🍒 🍉 🍋 🔔 ⭐')
bet = player.place_bet()
player.update_balance(-bet)
row = slot_machine.spin_row()
print('Spinning...\n')
slot_machine.print_row(row)
if payout > 0:
print(f'You won ${payout}')
else:
print('Sorry, you lost this round')
player.update_balance(payout)
How it function:
Manages the flow of the game, alternating between the player and the computer.
Computer’s turn (letter == 'O'), picks a random available move.
Player’s turn (letter == 'X'), the player input a move whereas 0 – 8 is the selection.
If number (place) is occupied, it will ask the player again to input a move.
Game continue until there are no empty squares.
import random
#Import the random module to allow the computer to make random moves
class TicTacToe:
def __init__(self):
# Initialize the board with empty spaces and no current winner
self.board = [' ' for _ in range(9)]
self.current_winner = None
def print_board(self):
# Print the current state of the board
for row in [self.board[i*3:(i+1)*3] for i in range(3)]:
print('| ' + ' | '.join(row) + ' |')
@staticmethod
def print_board_nums():
# Print the board with numbers indicating each position (0-8)
number_board = [[str(i) for i in range(j*3, (j+1)*3)] for j in range(3)]
for row in number_board:
print('| ' + ' | '.join(row) + ' |')
def available_moves(self):
# Return a list of available moves (positions that are still empty)
return [i for i, spot in enumerate(self.board) if spot == ' ']
def empty_squares(self):
# Check if there are any empty squares left on the board
return ' ' in self.board
def num_empty_squares(self):
# Return the number of empty squares
return self.board.count(' ')
def make_move(self, square, letter):
# Make a move on the board if the square is empty
if self.board[square] == ' ':
self.board[square] = letter
if self.winner(square, letter):
self.current_winner = letter
return True
return False
# Check column
col_ind = square % 3
column = [self.board[col_ind+i*3] for i in range(3)]
if all([spot == letter for spot in column]):
return True
# Check diagonals
if square % 2 == 0:
diagonal1 = [self.board[i] for i in [0, 4, 8]]
if all([spot == letter for spot in diagonal1]):
return True
diagonal2 = [self.board[i] for i in [2, 4, 6]]
if all([spot == letter for spot in diagonal2]):
return True
return False
letter = 'X'
while game.empty_squares():
if letter == 'O':
# Computer makes a random move
square = random.choice(game.available_moves())
else:
# Player makes a move
square = int(input(f"{letter}'s turn. Input move (0-8): "))
if game.make_move(square, letter):
if print_game:
print(letter + f' makes a move to square {square}')
game.print_board()
print('')
if game.current_winner:
if print_game:
print(letter + ' wins!')
return letter
# Switch players
letter = 'O' if letter == 'X' else 'X'
if __name__ == '__main__':
t = TicTacToe()
play(t, 'X', 'O', print_game=True)