0% found this document useful (0 votes)
20 views8 pages

Game

Programming Document

Uploaded by

Meg Aera
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views8 pages

Game

Programming Document

Uploaded by

Meg Aera
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 8

RODELAS, ARRIZA V.

CS3B

1. Explain the code


import random
#Imports the random module to generate random symbols.

def spin_row():
"""
Creates a list of possible symbols.
Returns a list of three randomly chosen symbols.
"""

symbols = ['🍒', '🍉', '🍋', '🔔', '⭐']


return [random.choice(symbols) for _ in range(3)]

def print_row(row):
#Joins the symbols in the row with " | " and prints them.
print(' | '.join(row))

def get_payout(row, bet):


"""
Calculates the payout based on the row of symbols and the bet amount.
Checks if all three symbols in the row are the same.
Returns the payout based on the symbol and the bet amount.
"""
if row[0] == row[1] == row[2]:

if row[0] == '🍒':
return bet * 3

elif row[0] == '🍉':


return bet * 4

elif row[0] == '🍋':


return bet * 5

elif row[0] == '🔔':


return bet * 10

elif row[0] == '⭐':


return bet * 20
return 0
#If the symbols are not the same, returns 0.

def main():
"""
Main function to run the slot machine game.
"""
balance = 100
#Initializes the player's balance to $100.

print('Welcome to Python Game')

print('Symbols: 🍒 🍉 🍋 🔔 ⭐')
#Prints a welcome message and the symbols

# Main game loop


#Runs a loop until the player's balance is greater than 0.
while balance > 0:
print(f'Current Balance: ${balance}')

# Get bet amount from the player


bet = input('Place your bet amount: ')

# Check if the bet amount is a valid number


if not bet.isdigit():
print('Enter a valid number')
continue

bet = int(bet)

# Check if the bet is greater than the current balance


if bet > balance:
print('Insufficient funds')
continue

# Check if the bet is greater than 0


if bet <= 0:
print('Bet must be greater than 0')
continue

# Deduct the bet amount from the balance


balance -= bet

#Spins the slot machine and prints the result.


row = spin_row()
print('Spinning...\n')
print_row(row)

# Calculate payout
payout = get_payout(row, bet)

# Display the result


if payout > 0:
print(f'You won ${payout}')
else:
print('Sorry you lost this round')

# Calculates the payout and updates the balance.


balance += payout

# Ask the player if wants to play again


#Y means they play again, otherwise end the game
play_again = input('Do you want to spin again (Y/N)? ').upper()
if play_again != 'Y':
break

# Prints the final balance when the game is over.


print(f'Game over! Your final balance is ${balance}')

if __name__ == '__main__':
main()

2. Modify the code

I used OOP to encapsulate functionality and make the code more modular and maintainable.

import random

class SlotMachine:
def __init__(self):

self.symbols = ['🍒', '🍉', '🍋', '🔔', '⭐']

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)]

def print_row(self, row):


"""
Prints a row of symbols in a formatted way.
"""
print(' | '.join(row))

def get_payout(self, row, bet):


"""
Calculates the payout based on the row of symbols and the bet amount.
"""
if row[0] == row[1] == row[2]:

if row[0] == '🍒':
return bet * 3

elif row[0] == '🍉':


return bet * 4

elif row[0] == '🍋':


return bet * 5

elif row[0] == '🔔':


return bet * 10

elif row[0] == '⭐':


return bet * 20
return 0

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 update_balance(self, amount):


"""
Updates the player's balance by the specified amount.
"""
self.balance += amount

def get_balance(self):
"""
Returns the player's current balance.
"""
return self.balance

def main():
player = Player(balance=100)
slot_machine = SlotMachine()

print('Welcome to Python Slot Machine Game')

print('Symbols: 🍒 🍉 🍋 🔔 ⭐')

while player.get_balance() > 0:


print(f'Current Balance: ${player.get_balance()}')

bet = player.place_bet()
player.update_balance(-bet)

row = slot_machine.spin_row()

print('Spinning...\n')
slot_machine.print_row(row)

payout = slot_machine.get_payout(row, bet)

if payout > 0:
print(f'You won ${payout}')
else:
print('Sorry, you lost this round')

player.update_balance(payout)

play_again = input('Do you want to spin again (Y/N)? ').upper()


if play_again != 'Y':
break

print(f'Game over! Your final balance is ${player.get_balance()}')


if __name__ == '__main__':
main()

3. Create own Python Game program &


4. Explanation

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

def winner(self, square, letter):


# Check if the move made by the player is a winning move
# Check row
row_ind = square // 3
row = self.board[row_ind*3:(row_ind+1)*3]
if all([spot == letter for spot in row]):
return True

# 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

def play(game, x_player, o_player, print_game=True):


if print_game:
game.print_board_nums()

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'

# Check for tie


if game.empty_squares() == 0:
if print_game:
print('It\'s a tie!')
return 'Tie'

if __name__ == '__main__':
t = TicTacToe()
play(t, 'X', 'O', print_game=True)

You might also like