tic tac toe for python3 - python-3.x

how do I add a score counter to this tic tac toe game:
i need to be able to keep score of the tic tac toe games so that the users (its a 2 player game) can play mutable games in a row and the program will keep score for them.The program bellow already allows the users to continue to play so that they can play multiple games in a row however the program does not keep track of the score of player x and o or the number of ties. how to I add to this so that it will tray player x's wins, player o's wins, and the number on ties
def drawboard(board):
print(' | |')
print(' ' + str(board[7]) + ' | ' +str( board[8]) + ' | ' + str(board[9]))
print(' | |')
print('-----------')
print(' | |')
print(' ' + str(board[4]) + ' | ' + str(board[5]) + ' | ' + str(board[6]))
print(' | |')
print('-----------')
print(' | |')
print(' ' + str(board[1]) + ' | ' + str(board[2]) + ' | ' + str(board[3]))
print(' | |')
def draw(board):
print(board[7], board[8], board[9])
print(board[4], board[5], board[6])
print(board[1], board[2], board[3])
print()
def t(board):
while True:
try:
x = int(input())
if x in board:
return x
else:
print("\nSpace already taken. Try again")
except ValueError:
print("\nThat's not a number. enter a space 1-9")
def GO(win,board):
for x, o, b in win:
if board[x] == board[o] == board[b]:
print("Player {0} wins!\n".format(board[x]))
print("Congratulations!\n")
return True
if 9 == sum((pos == 'X' or pos == 'O') for pos in board):
print("The game ends in a tie\n")
return True
def tic_tac_toe():
board = [None] + list(range(1, 10))
win = [(1, 2, 3),(4, 5, 6),(7, 8, 9),(1, 4, 7),(2, 5, 8),(3, 6, 9),(1, 5, 9),(3, 5, 7),]
for player in 'XO' * 9:
drawboard(board)
if GO(win,board):
break
print("Player {0}".format(player))
board[t(board)] = player
print()
def main():
while True:
tic_tac_toe()
if input("Play again (y/n)\n") != "y":
break
main()

Seeing that the code is already a bit messy and still without answer, I would suggest a quick & dirty solution.
You can define a global variable outside of all the functions, like:
scoreboard = {"X": 0, "O": 0, "T": 0}
Then you simply increment the scores in your GO function.
def GO(win,board):
for x, o, b in win:
if board[x] == board[o] == board[b]:
print("Player {0} wins!\n".format(board[x]))
print("Congratulations!\n")
scoreboard[board[x]] += 1
return True
if 9 == sum((pos == 'X' or pos == 'O') for pos in board):
print("The game ends in a tie\n")
scoreboard["T"] += 1
return True
And just print the scores from scoreboard wherever you want.
However, I would recommend to learn how to make your code more readable. It will help you to write more difficult programs more easily. It will help to avoid quick and dirty solutions like this one and make a lot of difficult things fall into place without much effort.
In any case, congrats on writing a working TTT game, keep it up :)

def GO(win,board):
for x, o, b in win:
if board[x] == board[o] == board[b]:
print("Player {0} wins!\n".format(board[x]))
print("Congratulations!\n")
return True
if 9 == sum((pos == 'X' or pos == 'O') for pos in board):
print("The game ends in a tie\n")
# return False if there is no winner
return False
def tic_tac_toe():
board = [None] + list(range(1, 10))
win = [(1, 2, 3),(4, 5, 6),(7, 8, 9),(1, 4, 7),(2, 5, 8),(3, 6, 9),(1, 5, 9),(3, 5, 7),]
for player in 'XO' * 9:
drawboard(board)
if GO(win,board):
# returns the winner if there is one
return player
elif GO(win, board) is False:
# returns False if winner is a tie
return False
print("Player {0}".format(player))
board[t(board)] = player
print()
First, you should create unique output values for different game outcomes rather than only True. Then, you can keep score in your while loop based on the value of the function call.
def main():
count_x = 0
count_o = 0
while True:
score = tic_tac_toe()
if score == 'X':
count_x += 1
elif score == 'O':
count_o += 1
print("The running score is " + '('+ str(count_x), str(count_y) +')')
if input("Play again (y/n)\n") != "y":
break
main()

Related

Python Tuple Index Out of Range error after assignment to list

I jumped into some Python courses a little while ago and have gotten to a milestone project to make a simple tic-tac-toe game.
But I am running into a bit of a wall due to an index error that keeps happening and I cannot figure out why.
The code is the following:
#Tic Tac Toe
game_list = [' '] * 10
turn_counter = 0
game_on = True
def show_game(game_list):
print(' | |')
print(' ' + game_list[7] + ' | ' + game_list[8] + ' | ' + game_list[9])
print(' | |')
print('-----------')
print(' | |')
print(' ' + game_list[4] + ' | ' + game_list[5] + ' | ' + game_list[6])
print(' | |')
print('-----------')
print(' | |')
print(' ' + game_list[1] + ' | ' + game_list[2] + ' | ' + game_list[3])
print(' | |')
def choose_position():
# Initial Variables
within_range = False
acceptable_values = [1,2,3,4,5,6,7,8,9]
choice = 'WRONG'
# While loop that keeps asking for input
while choice.isdigit() == False or within_range == False:
choice = input("Please choose a number between 1-9 like a numpad: ")
# DIGIT CHECK
if choice.isdigit() == False:
print("Sorry, that is not a digit!")
# RANGE CHECK
if choice.isdigit() == True:
if int(choice) in acceptable_values:
within_range = True
else:
print("Sorry, you are out of the acceptable range (1-9)")
return int(choice)
def insert_choice(game_list, position, turn_counter):
print(type(position))
print(position)
# Place the character in the game_list
if turn_counter%2 == 0 or turn_counter == 0:
game_list[position] = 'X'
else:
game_list[position] = 'O'
return (game_list, position)
def gameon_choice():
choice = 'wrong'
while choice not in ['Y', 'N']:
choice = input("Keep playing? (Y or N) ")
if choice not in ['Y', 'N', 'R']:
print("sorry, I don't understand, please choose Y or N ")
if choice == 'Y':
return True
else:
return False
while game_on:
show_game(game_list)
position = choose_position()
game_list = insert_choice(game_list,position,turn_counter)
turn_counter += turn_counter
show_game(game_list)
game_on = gameon_choice()
And the error I get is:
Exception has occurred: IndexError
tuple index out of range
File "Desktop/Tictactoe.py", line 9, in show_game
print(' ' + game_list[7] + ' | ' + game_list[8] + ' | ' + game_list[9])
File "Desktop/Tictactoe.py", line 79, in <module>
show_game(game_list)
What I think is happening is that during the assignment in the insert_choice function:
game_list[position] = 'X'
the list is somehow converted to a tuple and the variables are appended instead of assigned, and then when trying to display the list again it only has two elements leading to an index error, but I cannot figure out /why/.
I hope someone can help.
Sincerely,
The insert_choice() method returns a tuple of your game_list and position:
return (game_list, position)
Thus, during your main loop, you store this tuple as the new game_list and try to access indices greater than 1 which leads to this index error.
You can either only return game_list or unpack the returned tuple as:
game_list, position = insert_choice(game_list,position,turn_counter)
Since you don't change the value of position, you probably want to do the former.

Number Guessing game Computer Playing

I have created this game. User is giving a number from 1 to 100. Computer is trying to guess it. User is giving hint to computer to go lower or go higher. I am open for any feedback.
Thank you in advance.
import os
import random
os.system('clear')
user = int(input("Please enter a number between 1-100: "))
print("Your Number is: " + str(user))
comp_list = list(range(1,101))
comp_selection = random.choice(comp_list)
count = 0
def game(num, a = 1, b = 100):
global count
print("I have chosen " + str(num) + "\nShould I go Higher or Lower or Correct? ")
user = input("Your Selection: ")
if user == "L":
count = count + 1
low_game(a, num)
elif user == "H":
count = count + 1
high_game(num, b)
else:
print("I have guessed correctly in " + str(count) + " tries")
def low_game(old_low, new_High):
x = new_High
new_comp_list = list(range(old_low, x))
new_comp_selection = random.choice(new_comp_list)
game(new_comp_selection, old_low, x)
def high_game(new_low, old_high):
x = new_low + 1
new_comp_list = list(range(x, old_high))
new_comp_selection = random.choice(new_comp_list)
game(new_comp_selection,x, old_high)
game(comp_selection)
I agree, you have over complicated the game with recursive functons.
Here is a much simplified game with penalties for player who does not answer correctly
or falsifies the answer:)
import sys, random
wins = 0
loss = 0
while 1:
user = input('Please enter a number between 1-100: (return or x = quit) > ' )
if user in [ '', 'x' ]:
break
elif user.isnumeric():
user = int( user )
if user < 1 or user > 100:
sys.stdout.write( 'Number must be between 1 and 100!!\n' )
else:
low, high, count = 1, 100, 0
while 1:
p = random.randint( low, high )
count += 1
while 1:
answer = input( f'Is your number {p}? Y/N > ').upper()
if answer in [ 'Y','N' ]:
break
else:
sys.stderr.write( 'Answer must be Y or N\n' )
if answer == 'N':
if p != user:
if input( f'Is my number (H)igher or (L)ower? > ').upper() == 'H':
if user < p:
high = p - 1
else:
sys.stderr.write( f'Wrong!! Your number was lower. You loss\n' )
loss =+ 1
break
else:
if user > p:
low = p + 1
else:
sys.stderr.write( f'Wrong!! Your number higher. You loss\n' )
loss =+ 1
break
else:
sys.stderr.write( f'Cheat!! Your number is {user}!! You loss\n')
loss =+ 1
break
else:
if user == p:
sys.stdout.write( f'I guessed Correctly in {count} guesses\n' )
wins += 1
else:
sys.stderr.write( f'Cheat!! This is not your number. You loss\n' )
loss =+ 1
break
print( f'Computer won = {wins} : You lost = {loss}' )
Happy coding.
You have really overly complicated the problem. The basic process flow is to have the computer guess a number within a fixed range of possible numbers. If the guess is incorrect, the user tells the computer how to adjust the list by either taking the guessed number as the low end or the high end of the guessing range. So to accomplish this, I would do the following:
from random import randint
# Function to request input and verify input type is valid
def getInput(prompt, respType= None):
while True:
resp = input(prompt)
if respType == str or respType == None:
break
else:
try:
resp = respType(resp)
break
except ValueError:
print('Invalid input, please try again')
return resp
def GuessingGame():
MAX_GUESSES = 10 # Arbritray Fixed Number of Guesses
# The Game Preamble
print('Welcome to the Game\nIn this game you will be asked to provide a number between 1 and 100 inclusive')
print('The Computer will attempt to guess your number in ten or fewer guesses, for each guess you will respond by telling the computer: ')
print('either:\n High - indicating the computer should guess higher\n Low - indicating the computer should guess lower, or')
print(' Yes - indicating the computer guessed correctly.')
# The Game
resp = getInput('Would You Like To Play?, Respond Yes/No ')
while True:
secret_number = None
if resp.lower()[0] == 'n':
return
guess_count = 0
guess_range = [0, 100]
secret_number = getInput('Enter an Integer between 1 and 100 inclusive', respType= int)
print(f'Your secret number is {secret_number}')
while guess_count <= MAX_GUESSES:
guess = randint(guess_range[0], guess_range[1]+1)
guess_count += 1
resp =getInput(f'The computer Guesses {guess} is this correct? (High?Low/Yes) ')
if resp.lower()[0] == 'y':
break
else:
if resp.lower()[0] == 'l':
guess_range[1] = guess - 1
else:
guess_range[0] = guess + 1
if guess == secret_number:
print (f'The Computer has Won by Guessing your secret number {secret_number}')
else:
print(f'The Computer failed to guess your secret number {secret_number}')
resp = getInput('Would You Like To Play Again?, Respond Yes/No ')

python program error while combine two program

i have wrote two program, one is tic tac toe,one is guest number, and it is fine when run separately and when i combine them( my aim is when to people win in the guest number game, the people can pick a box in tic tac toe)
It work normally and when it start to select to second box, the error occur
it is show asz follow
Traceback (most recent call last):
File "C:\Users\User\Desktop\try3.py", line 207, in
winner = single_game(options[choice-1])
File "C:\Users\User\Desktop\try3.py", line 125, in single_game
player_pos[cur_player].append(move)
KeyError: <main.Player object at 0x000001D6C01CC730>
can anyone see what wrong with my program. Thanks
import random
from random import randint
class Player():
def __init__(self, player_name):
self.name = player_name
self.score = 0
self.guess = 0
def enterGuess(self,rand, play):
if play == True:
self.guess = int(input(self.name+ " enter a guess 1-100:"))
if self.guess == rand:
print ("Correct Guess")
play = False
self.score = self.score + 1
elif self.guess < rand:
print ("Too low")
else:
print ("Too high")
return play
def playGame():
player1.score = 0
player1.guess = 0
player2.score = 0
player2.guess = 0
randNum = randint(1,100)
play = True
print ("\nNew game")
while play:
play=player1.enterGuess(randNum, play)
play=player2.enterGuess(randNum, play)
def coinToss():
flip = random.randint(0, 1)
if (flip == 0):
return("Head")
else:
return("Tail")
print(coinToss)
def print_tic_tac_toe(values):
print("\n")
print("\t | |")
print("\t {} | {} | {}".format(values[0], values[1], values[2]))
print('\t_____|_____|_____')
print("\t | |")
print("\t {} | {} | {}".format(values[3], values[4], values[5]))
print('\t_____|_____|_____')
print("\t | |")
print("\t {} | {} | {}".format(values[6], values[7], values[8]))
print("\t | |")
print("\n")
def print_scoreboard(score_board):
print("\t--------------------------------")
print("\t SCOREBOARD ")
print("\t--------------------------------")
players = list(score_board.keys())
print("\t ", players[0], "\t ", score_board[players[0]])
print("\t ", players[1], "\t ", score_board[players[1]])
print("\t--------------------------------\n")
def check_win(player_pos, cur_player):
soln = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [1, 4, 7], [2, 5, 8], [3, 6, 9], [1, 5, 9], [3, 5, 7]]
for x in soln:
if all(y in player_pos[cur_player] for y in x):
return True
return False
def check_draw(player_pos):
if len(player_pos['X']) + len(player_pos['O']) == 9:
return True
return False
def single_game(cur_player):
values = [' ' for x in range(9)]
player_pos = {'X':[], 'O':[]}
while True:
print_tic_tac_toe(values)
try:
print("The player ", cur_player, " turn. Which box? : ", end="")
move = int(input())
except ValueError:
print("Wrong Input!!! Try Again")
continue
if move < 1 or move > 9:
print("Wrong Input!!! Try Again")
continue
if values[move-1] != ' ':
print("Place already filled. Try again!!")
continue
values[move-1] = cur_player
player_pos[cur_player].append(move)
if check_win(player_pos, cur_player):
print_tic_tac_toe(values)
print( cur_player, " has won the game!!")
print("\n")
return cur_player
if check_draw(player_pos):
print_tic_tac_toe(values)
print("Game Drawn")
print("\n")
return 'D'
playGame()
if int(player1.score)>int(player2.score):
cur_player = player1
else:
cur_player = player2
if __name__ == "__main__":
print ("Player 1")
player1=Player(input("Enter name:"))
print ("Player 2")
player2=Player(input("Enter name:"))
playGame()
if int(player1.score)>int(player2.score):
cur_player = player1
else:
cur_player = player2
player_choice = {'X' : "", 'O' : ""}
options = ['X', 'O']
score_board = {player1: 0, player2: 0}
print_scoreboard(score_board)
while True:
print("Turn to choose for", cur_player)
print("Enter 1 for X")
print("Enter 2 for O")
print("Enter 3 to Quit")
try:
choice = int(input())
except ValueError:
print("Wrong Input!!! Try Again\n")
continue
if choice == 1:
player_choice['X'] = cur_player
if cur_player == player1:
player_choice['O'] = player2
else:
player_choice['O'] = player1
elif choice == 2:
player_choice['O'] = cur_player
if cur_player == player1:
player_choice['X'] = player2
else:
player_choice['X'] = player1
elif choice == 3:
print("Final Scores")
print_scoreboard(score_board)
break
else:
print("Wrong Choice!!!! Try Again\n")
winner = single_game(options[choice-1])
if winner != 'D' :
player_won = player_choice[winner]
score_board[player_won] = score_board[player_won] + 1
print_scoreboard(score_board)

Issues with 'movement' across multi-dimensional array, text-based game

I'm currently messing around with the code right now to solve some issues in movement. Ideally, i want to be able to move the character to any spot in the array(worldMap) containing ' ', and marking the player's position with 'P'.
I'm lost to what the issue I am running into is, and some of the issues I am running into are as follows...
- when I move E it always goes to worldMap[3][3]
- N only moves up from worldMap[3][x] to worldMap [2][x]
- S doesn't work
Below is my current code...
import math
import random
import sys
import os
import time
gameplay= True
#world map lay out, X--> wall, player can't go that way. ' ', possible area for player to move, 'P', player indicator.
worldMap = [['X','X','X','X','X'],
['X',' ',' ',' ','X'],
['X',' ',' ',' ','X'],
['X','P',' ',' ','X'],
['X','X','X','X','X']]
west=str("w" or "W")
east=str("e" or "E")
north=str('n' or 'N')
south=str('s' or 'S')
for row in worldMap:
for column in row:
print(column, end=' ')
print()
while gameplay == True:
x=str((input("\nWhat direction would you like to move?\n ")))
if x==west:
for row in worldMap:
for i, column in enumerate(row):
if column == 'P':
if((i>0) and (i<4) and row[i-1]) == ' ':
row[i-1] = 'P'
row[i]=' '
else:
print("\nCan't do that.\n")
for row in worldMap:
for column in row:
print(column, end=' ')
print()
elif x==east:
for row in worldMap:
for i, column in enumerate(row):
if column == 'P':
if((i>0) and (i<4) and row[i+1]) == ' ':
row[i+1] = 'P'
row[i]=' '
else:
print("\nCan't do that.\n")
for row in worldMap:
for column in row:
print(column, end=' ')
print()
elif x == north: #move north
for column in worldMap:
for i, row in enumerate(column):
if row == 'P':
if((i>0) and (i<4) and column[i-1]) == ' ':
column[i-1] = 'P'
column[i]=' '
else:
print("\nCan't do that.\n")
for row in worldMap:
for column in row:
print(column, end=' ')
print()
elif x== south: #move south
for column in worldMap:
for i, row in enumerate(column):
if column == 'P':
if((i>0) and (i<4) and column[i+1]) == ' ':
column[i+1] = 'P'
column[i]=' '
else:
print("\nCan't do that.\n")
for row in worldMap:
for column in row:
print(column, end=' ')
print()
else:
for row in worldMap:
for column in row:
print(column, end=' ')
print()
print("\nCan't do that.\n")
I have tided up your code a bit. A good clue to needing to refactor your code is if you have written the same thing alot in your code. In those cases its better to write a function and then call the function from your code. The below code is just an example to help set you on the right path.
In this example instead of scanning the whole map for the player, i just keep track of the players position and calculate the new position and if its a space then move the player. We can easily move the player by adding or subtracting 1 to the x or y co-ordinate of the player.
I also cleaned up the print map function and its now only called at the start of each loop.
from random import randint
def generate_map(size):
# world map lay out, X--> wall, player can't go that way. ' ', possible area for player to move, 'P', player indicator.
world_map = [[wall for _ in range(size)]]
for i in range(1, size - 1):
world_map.append([wall])
for j in range(1, size - 1):
#generate random walls in our map (currently set to genearete spaces 90% of the time
if randint(1,100) < 90:
world_map[i].append(space)
else:
world_map[i].append(wall)
world_map[i].append(wall)
world_map.append([wall for _ in range(size)])
return world_map
def print_map():
for row in worldMap:
print(" ".join(row))
def move_player():
x, y = player_position
if direction == "W":
y -= 1
elif direction == "E":
y += 1
elif direction == "N":
x -= 1
elif direction == "S":
x += 1
if worldMap[x][y] == space:
worldMap[player_position[0]][player_position[1]] = space
worldMap[x][y] = player
player_position[0] = x
player_position[1] = y
else:
print("Cannot more there")
#Genearte a map and position the player
wall, space, player = "X", " ", "P"
map_size = 10
worldMap = generate_map(map_size)
player_position = [1, 1]
worldMap[player_position[0]][player_position[1]] = player
#Run the game
gameplay = True
while gameplay:
print_map()
direction = input("\nWhat direction would you like to move? ").upper()
if direction:
move_player()
else:
break

dice_values within a function aren't returning, could someone please explain my error

I'm doing an assignment that requires me to simulate a dice roll game.
My problem is that when I roll the dice whithin my function and then later call it,
when I display try to display the die1, die2, die3 value from another function the values ar empty, unless I use global values, but I want to understand how the functions work and what i'm doing wrong rather than work around with global. :)
#importing the random library to make the random.randint function available
import random
#Making declrations for variable values
total_games = (0)
chip_balance = 100
total_chips = ()
games_won = 0
games_lost = 0
even_stevens = 0
games_draw = 0
play_game = 0
die1 = ()
die2 = ()
die3 = ()
#defining the dice roll function and logic
def die_roll(die1, die2, die3):
#Global Statements to make the die values available to the pre_display_dice function and the display_dice function.
die1 = random.randint (1, 12)
die2 = random.randint (1, 12)
die3 = random.randint (1, 12)
return die1, die2, die3
#defining the authorship details in this function
def display_details():
print('File : tobxz001_inbetween.py')
#defining the get_play_game_function to set the loop
def get_play_game():
global play_game
play_game = input('Would you like to play in-between [y|n]?')
while play_game != 'y' and play_game != 'n':
play_game = input("please enter either 'y' or 'n': ")
play_game = play_game.lower()
return play_game
#defining the Play_again function
def play_again():
global play_game
play_game = input('Would you like to play again squire?')
while play_game != 'y' and play_game != 'n':
play_game = input("please enter either 'y' or 'n' :")
play_game = play_game.lower()
#Defining the dice display here. Only two values are displayed before the bet is made
def pre_display_dice():
print('Dice rolled:')
print('+-------------------------------------+')
print('| Die 1 | | Die 2 |')
print('| ',die1,' | 0 | ',die2, ' |')
print('+-------------------------------------+')
#Defining the final dice roll display with all values of the roll displayed after the bet is made
def display_dice():
print('Dice rolled:')
print('+-------------------------------------+')
print('| Die 1 | | Die 2 |')
print('| ',die1,' | ',die3, ' | ',die2, ' |')
print('+-------------------------------------+')
#Defining the game summary here. Wins, Loses, and draws are called from this function at the end of the game
def game_summary():
print('\n')
print('Game Summary')
print('============')
print('\n')
print('You played',total_games,'Games:')
print('|--> Games Won:', games_won)
print('|--> Games Lost', games_lost)
print('|--> Even-Stevens:', even_stevens)
display_details()
get_play_game()
while play_game == 'y':
die_roll(die1, die2, die3)
temp = int()
winner = ()
loser = (0)
bet_result = ()
#Code for swapping the dice around to always display the lower value on the left
if (die1 >= die2):
temp = die1
die1 = die2
die2 = temp
else:
die1 = die1
die2 = die2
if die1 == die2:
total_games = total_games + 1
print('\n')
print('You hit the post')
print("Even-Stevens! Let\'s play again!")
print('\n')
get_play_game
pre_display_dice()
print('\n')
print("Number of Chips : ", chip_balance)
bet = input("Place your bet: ")
while bet == '':
bet = input("Can't be an empty bet please try again ")
while bet.isalpha():
bet = input("Must be a numerical value entered \n \n Place You're bet:")
bet = int(bet)
while bet > chip_balance:
print('Sorry, you may only bet what you have ')
bet = input("Place your bet: ")
while bet == '':
bet = input("Can't be an empty bet please try again ")
while bet.isalpha() or bet == '':
bet = input("Must be a numerical value entered \n \n Place You're bet:")
bet = int(bet)
chip_balance = chip_balance - bet
if die1 < die3 & die3 < die2:
winner = (bet * 2) + chip_balance
chip_balance = winner
else:
chip_balance
#Code to compare if the results are even or not STAGE 3, if they aren't Die3 will be rolled
if die1 == die2:
print('\n')
display_dice()
print('You hit the post')
print("Even-Stevens! Let\'s play again!")
print('\n')
even_stevens = even_stevens + 1
total_games = total_games + 1
else:
print('\n')
display_dice()
print('\n')
#Winning and Losing logic
#Winning conditions
if die1 < die3 & die3 < die2:
print("***You Win!***")
print("You now have", chip_balance, "Chips")
print('\n')
games_won = games_won + 1
total_games = total_games + 1
#Evaluate to see if any of the dice' match is done here
elif die1 == die3 or die3 == die2:
print('\n')
print("***You hit the post - You Lose! ***")
print("You now have", chip_balance, "chips left")
print('\n')
games_lost = games_lost + 1
total_games = total_games + 1
#Losing Logic
else:
print("*** Sorry - You Lose! ***")
print('\n')
print("You now have", chip_balance, "chips left!")
games_lost = games_lost + 1
total_games = total_games + 1
#Chip balance check, if it's zero, game is over, otherwise keep playing
if chip_balance == 0:
print('\n')
print('You\'re all out of chips! \n ***GAME OVER***')
play_game = 'n'
else:
play_again()
if play_game == 'n':
game_summary()
if play_game == 'n':
print('\n')
print('No worries... another time perhaps...:)')

Resources