# Python Game Challenge #2 [Beginner]

Hello again! Today’s game is called HEADS or TAILS, but with a twist… You have money and bets!

In other words, you input how much money you have and how much you’re willing bet.
You either bet HEADS or TAILS (duh…), if you win, you’ll multiply the money you bet by two and add to your existing money; if you fail, you lose the money you bet.

Simple, right?

I chose to polish up my program (even though it has some bugs) to add more syntactical clarity , but you can simply code a quick, functional program.

As always, feel free to post your code in other languages!

Happy Coding!

``````from random import randint

def game():
mon = int(raw_input('\n[*] How much money do you have? > '))
while mon > 0:
r = randint(0,1) #generates either 0 or 1.  1 = 'heads'; 0 = 'tails'
bet = int(raw_input('[*] Place your bet > '))
if bet > mon:
print "\n[!] You don't have that much money!"

elif mon == 0:
print '\n[!] You are out of money!\n'

else:
hd = raw_input('\n[*] All right, the million dollar question, HEADS or TAILS? > ')
if (hd == 'heads' and r == 1) or (hd == 'tails' and r == 0):
print '\n[!] You won!\n'
mon += bet * 2
print '> You now have %s!\n' % (mon)

elif (hd == 'heads' and r == 0) or (hd == 'tails' and r == 1):
print '\n[!] You lost...\n'
mon -= bet
print '> You now have %s!\n' % (mon)

else:

def main():
print '#----------------#'
print '| HEADS OR TAILS |'
print '|    by n3xUs_   |'
print '#----------------#'

print '\n[*] This game is simple. You either choose HEADS or TAILS.\n'
print '[*] If you win, you multiply the money you bet, if you lose, you lose the money.\n'
print '[*] Simply input how much money you have and how much you want to bet.'
raw_input('\n[*] Press ENTER to begin...')
game()

main()

``````
5 Likes

Here’s some C++ this time:

``````#include <iostream>
#include <string>
#include <algorithm>

void game() {
std::cout << "[*] How much money do you have? ";
int user_money; std::cin >> user_money;

int user_bet, user_guess, toss;
while (user_money > 0) {
std::cout << "[*] Place a bet. ";
std::cin >> user_bet;
if (user_bet > user_money) {
std::cout << "Your bet was too large! Try again..." << std::endl;
continue;
}
while (true) {
std::cout << "Guess: 0 for heads, 1 for tails. ";
std::cin >> user_guess;

toss = rand() % 2;

if (user_guess >= 0 && user_guess <= 1) {
std::cout << "You guessed " << (user_guess == 0 ? "heads" : "tails")
<< " and were ";
if (toss == user_guess) {
std::cout << "correct!";
user_money += user_bet;
} else {
std::cout << "incorrect!";
user_money -= user_bet;
}
std::cout << std::endl;
break;
} else {
std::cout << "Invalid guess. Try again...";
}
}

std::cout << "You now have \$" << user_money << ".\n";
}

std::cout << "You're out of money." << std::endll;
}

int main() {
std::cout << "[*] Heads or Tails [*]" << std::endl
<< "You will bet on the outcome of a coin toss." << std::endl
<< "You can only bet as much as you have." << std::endl;

game();

return 0;
}
``````

Pastebin here

2 Likes

A implementation on C… with some macro abuse and debug traces

``````#include <stdio.h>
#include <stdlib.h>

#ifdef DEBUG
#define PDEBUG(fmt, arg...) fprintf (stderr, "DEBUG:" fmt, ##arg)
#else
#define PDEBUG(fmt, args...)
#endif

#define read_int(str, var) printf (str); scanf("%d", &var);

char *msg[] = {"Incorrect!", "Correct!"};

int
main (void)
{
int i, c, g, m, b;

/* OK. I skip the introduction in here :P */
read_int ("Enter the money? ", m);
do
{
printf ("You have %d. ", m);

if (b > m)
{
printf ("Bet too high!\n");
continue;
}
c = rand() % 2;
PDEBUG ("%d\n", c);

if (g < 0 || g > 1)
{
printf ("Invalid guess\n");
continue;
}
i = (g == c);
PDEBUG ("Result %d\n", i);
printf ("%s\n", msg[i]);
m += ((i * 2 - 1) * b);

} while (m > 0);
printf ("Out of money\n");
}

``````
2 Likes

TFW we’re just porting to different languages.

1 Like
``````from random import randint

def __init__(self):
self.balance = 100
def flipCoin(self, bet, prediction):
flip = randint(0, 1)
if (prediction == 'heads' and flip == 0) or (prediction == 'tails' and flip == 1):
print '[*] You won!\n'
self.balance += bet*2
else:
print '[*] You lost!\n'
self.balance -= bet
def getBet(self):
if self.balance == 0:
print '[!] You Busted!\n'
return
try:
predict = raw_input('[*] Heads or Tails: ').lower()
if predict != 'heads' and predict != 'tails':
print '[!] Invalid Selection\n'
return
bet = int(raw_input('[*] Enter Bet Amount: '))
if bet > self.balance:
print '[!] You can\'t bet that much!'
return
return (bet, predict)
except Exception:
print '[!] Failed to Take Input\n'
return
except KeyboardInterrupt:
print '[!] User Interrupted Input\n'
return
def getInfo(self):
print '[*] Current Balance: %s\n' %(self.balance)
return

if __name__ == '__main__':
import sys
while 1:
print "Menu:\n1. Play\n2. Check Balance\n3. Exit\n"
try:
choice = raw_input('> ')
except KeyboardInterrupt:
pass
if choice == '1':
try:
userbets = userGame.getBet()
if len(userbets) == 0:
raise Exception
userGame.flipCoin(userbets[0], userbets[1])
except Exception:
pass
elif choice == '2':
userGame.getInfo()
elif choice == '3':
sys.exit('[*] Thanks for playing!')
else:
print '[!] Invalid Option\n'
pass
``````

I went a bit overboard.

-Defalt

3 Likes

Hey @Defalt! Nice to have you back!
Also, there’s no such thing as overboard…

Lol exception handling. That could be considered “overboard.”

2 Likes

Also, great code @Defalt, might change my own based on yours.
You can really see the difference between a beginner/intermediate (me) and an advanced coder like yourself!

Thank you for the compliment. It means a lot to me.

-Defalt

3 Likes
``````#! /usr/bin/ruby

\$balance = 100

def flipCoin(bet, predict)
if ((bet == 0) or (bet > \$balance))
puts '[!] Invalid Bet!'
return
end
return if (predict != 'heads' and predict != 'tails')
result = Random.new().rand(2)
if ((result == 0 and predict == 'heads') or (result == 1 and predict == 'tails'))
puts '[*] You won!'
\$balance += bet*2
else
puts '[*] You lost!'
\$balance -= bet
end
end

def getBet()
begin
print "[*] Enter Bet: "
bet = gets.chomp.to_i
print "[*] Heads or Tails: "
predict = gets.chomp.downcase
return [bet, predict]
rescue
end
end

while true
print "Menu:\n1. Play\n2. Check Balance\n3. Exit\n"
print "> "
choice = gets.chomp
begin
case choice
when "1"
userBet = getBet()
flipCoin(userBet[0], userBet[1])
when "2"
puts "[*] Balance: #{\$balance}"
when "3"
exit
end
rescue
end
end
``````

I got bored so here it is in Ruby.

-Defalt

3 Likes

This topic was automatically closed after 30 days. New replies are no longer allowed.