Programming Challenge #9 - writing a basic game - Overclock.net - An Overclocking Community

Forum Jump: 

Programming Challenge #9 - writing a basic game

Reply
 
Thread Tools
post #1 of 34 (permalink) Old 06-12-2013, 06:47 AM - Thread Starter
New to Overclock.net
 
Plan9's Avatar
 
Join Date: Nov 2011
Location: Planet Vegeta
Posts: 8,040
Rep: 574 (Unique: 277)
Let's have some fun: Write a Blackjack game

Next challenge: Fun With Cryptography.
Previous challenge: Create a crossword solver.

Rules of Blackjack:
I'm sure most of us have played blackjack before - be it in a casino or on our phones. But for those who haven't, the rules are very simple:
  • The player starts off with 2 cards
  • The player can "hit" (be dealt another card) or "stand" (stick with the cards dealt)
  • The aim is to get as close to 21 points as you can, without going over
  • If a player gets 22 or more, then they lose
  • Aces count as 11 or 1 (ie if the player has 21 or less, then ace is 11. If the player has more than 21, then ace is worth 1)
  • All other royalty is worth 10

There are more rules - but for the sake of simplicity, these are all we'll work with for now.

Specification:
I'm not bothered if you guys decide to bend the rules a little (or even a lot) to write this game. And this can be a console app or written in OpenGL - and everything in-between.

This challenge isn't about problem solving, it's just about creating something fun. So the solutions I'm listing below aren't set in stone. Basically if you're stuck for ideas, then pick a difficulty level, otherwise just write something fun smile.gif

Solutions:
Easiest:
  • deck is entirely random (ie you can draw the same card twice)
  • you don't need to assign each card a suit (ie clubs, diamonds, etc)
  • you can hard code the value of ace to be either 1 or 11

Easy:
  • you cannot draw the same card twice within the same game
  • each card must belong to a suit (ie clubs, diamonds, etc)
  • you can hard code the value of ace to be either 1 or 11

Medium:
  • you cannot draw the same card twice within the same game
  • each card must belong to a suit (ie clubs, diamonds, etc)
  • the value of ace changes dynamically based on total value of the cards in your hand

Hard:
  • you cannot draw the same card twice within the same game
  • each card must belong to a suit (ie clubs, diamonds, etc)
  • the value of ace changes dynamically based on total value of the cards in your hand
  • there is a computer opponent (the dealer) who tries to equal your value or beat it (while still remaining under 22). if the computer succeeds, it wins that round. if you get a higher value and remain under 22, then you win that round.

Hardest:

Footnote:

In the interest of keeping this thread tidy, can all code be posted inside code tags, that are inside spoiler tags. eg:

[SPOILER=Source code, written in C#]
[CODE]
// code be here
[/CODE]
[/SPOILER]
Plan9 is offline  
Sponsored Links
Advertisement
 
post #2 of 34 (permalink) Old 06-12-2013, 07:48 AM
Retired Staff
 
DizZz's Avatar
 
Join Date: Nov 2012
Location: 127.0.0.1
Posts: 6,516
Rep: 548 (Unique: 358)
Here is a quick version in python that I made. Not sure what level it is because I've included some aspects of each.

Source Code, Written in Python (Click to show)
Code:
#!/usr/bin/python

import random as r

deck = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]*4
dealer = []
player = []
z = 'y'

def clear():
    import os
    if os.name == 'posix':
        os.system('clear')
    
def showHand():
    hand = 0
    for i in player: hand += i 
    print "The dealer is showing a %d" % dealer[0]
    print "Your hand totals: %d (%s)" % (hand, player)

def setup():
    for i in range(2):
        dealDealer = deck[r.randint(1, len(deck)-1)]
        dealPlayer = deck[r.randint(1, len(deck)-1)]
        dealer.append(dealDealer)
        player.append(dealPlayer)
        deck.pop(dealDealer)
        deck.pop(dealPlayer)
setup()

while z != 'q':
    showHand()
    z = raw_input("[H]it [S]tand [Q]uit: ").lower()
    clear()
    if z == 'h':
        dealPlayer = deck[r.randint(1, len(deck)-1)]
        player.append(dealPlayer)
        deck.pop(dealPlayer)
        hand = 0
        for i in dealer: hand += i
        if not hand > 15:   
            dealDealer = deck[r.randint(1, len(deck)-1)]
            dealer.append(dealDealer)
            deck.pop(dealDealer)
        hand = 0
        for i in player: hand += i
        if hand > 21:
            print "BUST!"
            player = []    
            dealer = []    
            setup()         
        hand = 0
        for i in dealer: hand +=i
        if hand > 21:
            print "Dealer Busts!"
            player = []
            dealer = []
            setup()
    elif z == 's':
        dHand = 0           
        pHand = 0           
        for i in dealer: dHand += i
        for i in player: pHand += i
        if pHand > dHand:
            print "YOU WIN!"    
            dealer = []
            player = []
            setup()
        else:
            print "YOU LOSE!"    
            dealer = []
            player = []
            setup()
    else:
        if z == 'q':
            kk = raw_input("Goodbye. [Hit Enter]")
        else:
            print "Invalid choice."


DizZz is offline  
post #3 of 34 (permalink) Old 06-12-2013, 07:51 AM - Thread Starter
New to Overclock.net
 
Plan9's Avatar
 
Join Date: Nov 2011
Location: Planet Vegeta
Posts: 8,040
Rep: 574 (Unique: 277)
Quote:
Originally Posted by DizZz View Post

Here is a quick version in python that I made. Not sure what level it is because I've included some aspects of each. Warning: Spoiler! (Click to show)
Code:
#!/usr/bin/python

import random as r

deck = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]*4
dealer = []
player = []
c = 'y'

def clear():
    import os
    if os.name == 'posix':
        os.system('clear') #Pass clear to terminal
    
def showHand():
    hand = 0
    for i in player: hand += i #Tally up the total
    print "The dealer is showing a %d" % dealer[0]
    print "Your hand totals: %d (%s)" % (hand, player)

#Gives player and dealer their cards
def setup():
    for i in range(2):
        dealDealer = deck[r.randint(1, len(deck)-1)]
        dealPlayer = deck[r.randint(1, len(deck)-1)]
        dealer.append(dealDealer)
        player.append(dealPlayer)
        deck.pop(dealDealer)
        deck.pop(dealPlayer)
setup()

while c != 'q':
    showHand()
    c = raw_input("[H]it [S]tand [Q]uit: ").lower()
    clear()
    if c == 'h':
        dealPlayer = deck[r.randint(1, len(deck)-1)]
        player.append(dealPlayer)
        deck.pop(dealPlayer)
        hand = 0
        for i in dealer: hand += i
        if not hand > 15:   #Dealer strategy.
            dealDealer = deck[r.randint(1, len(deck)-1)]
            dealer.append(dealDealer)
            deck.pop(dealDealer)
        hand = 0
        for i in player: hand += i
        if hand > 21:
            print "BUST!"
            player = []     #Clear player hand
            dealer = []     #Clear dealer's hand
            setup()         #Run the setup again
        hand = 0
        for i in dealer: hand +=i
        if hand > 21:
            print "Dealer Busts!"
            player = []
            dealer = []
            setup()
    elif c == 's':
        dHand = 0           #Dealer's hand total
        pHand = 0           #Player's hand total
        for i in dealer: dHand += i
        for i in player: pHand += i
        if pHand > dHand:
            print "YOU WIN!"    
            dealer = []
            player = []
            setup()
        else:
            print "YOU LOSE!"    
            dealer = []
            player = []
            setup()
    else:
        if c == 'q':
            gb = raw_input("Goodbye. [Hit Enter]")
        else:
            print "Invalid choice."

Is that from a past exercise or tit you literally just bang that code out in the last hour?
If the latter, then I'm massively impressed.
Plan9 is offline  
Sponsored Links
Advertisement
 
post #4 of 34 (permalink) Old 06-12-2013, 08:02 AM
Retired Staff
 
DizZz's Avatar
 
Join Date: Nov 2012
Location: 127.0.0.1
Posts: 6,516
Rep: 548 (Unique: 358)
Quote:
Originally Posted by Plan9 View Post

Is that from a past exercise or tit you literally just bang that code out in the last hour?
If the latter, then I'm massively impressed.

Just did this in the last hour biggrin.gif It's a pretty simple game once you break it down into the different segments and python is incredibly fast and efficient for this type of exercise.


DizZz is offline  
post #5 of 34 (permalink) Old 06-12-2013, 08:14 AM - Thread Starter
New to Overclock.net
 
Plan9's Avatar
 
Join Date: Nov 2011
Location: Planet Vegeta
Posts: 8,040
Rep: 574 (Unique: 277)
Quote:
Originally Posted by DizZz View Post

Just did this in the last hour biggrin.gif It's a pretty simple game once you break it down into the different segments and python is incredibly fast and efficient for this type of exercise.
Yeah, I can't make the challenges too difficault because otherwise beginners wouldn't stand a chance and many of the more seasoned programmers might not have time. But all the same, that's some good work there mate smile.gif

If you fancy a tougher challenge then check out the hardest problem in my programming challenge #8:
https://www.overclock.net/t/1395543/programming-challenge-8-challenges-for-both-beginners-and-experts
Plan9 is offline  
post #6 of 34 (permalink) Old 06-12-2013, 08:27 AM
Retired Staff
 
DizZz's Avatar
 
Join Date: Nov 2012
Location: 127.0.0.1
Posts: 6,516
Rep: 548 (Unique: 358)
Quote:
Originally Posted by Plan9 View Post

Yeah, I can't make the challenges too difficault because otherwise beginners wouldn't stand a chance and many of the more seasoned programmers might not have time. But all the same, that's some good work there mate smile.gif

If you fancy a tougher challenge then check out the hardest problem in my programming challenge #8:
https://www.overclock.net/t/1395543/programming-challenge-8-challenges-for-both-beginners-and-experts

Just found these so I'll get right on it. Thanks for making these up they're a fun little challenge thumb.gif


DizZz is offline  
post #7 of 34 (permalink) Old 06-12-2013, 08:48 AM
New to Overclock.net
 
Jiiks's Avatar
 
Join Date: Jun 2010
Location: Finland
Posts: 396
Rep: 166 (Unique: 118)
Tried a 15min challenge with this.



Basic with c# winforms, missing hiding the first card of the dealer though rolleyes.gif
It's pretty terrible anyways redface.gif
Source code, written in C# (Click to show)
Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace BlackJack
{
    public partial class Form1 : Form
    {

        string[] Cards = new string[] { "1♥", "2♥", "3♥", "4♥", "5♥", "6♥", "7♥", "8♥", "9♥", "10♥", "11♥", "12♥", "13♥",
                                        "1♦", "2♦", "3♦", "4♦", "5♦", "6♦", "7♦", "8♦", "9♦", "10♦", "11♦", "12♦", "13♦",
                                        "1♣", "2♣", "3♣", "4♣", "5♣", "6♣", "7♣", "8♣", "9♣", "10♣", "11♣", "12♣", "13♣",
                                        "1♠", "2♠", "3♠", "4♠", "5♠", "6♠", "7♠", "8♠", "9♠", "10♠", "11♠", "12♠", "13♠"};

        List<int> CpuCards = new List<int>();
        List<int> PlayerCards = new List<int>();

        public Form1()
        {
            InitializeComponent();



        }


        private void btnDeal_Click(object sender, EventArgs e)
        {
            ShuffleDeck();
            DealCards();
        }


        private void ShuffleDeck()
        {

            lblResult.Text = "Result: N/A";
            Random r = new Random();
            for (int i = 0; i < Cards.Length; i++) 
            {
                int i2 = r.Next(i, Cards.Length);
                String s = Cards[i];
                Cards[i] = Cards[i2];
                Cards[i2] = s;    
            }
        }

        private void DealCards() 
        {
            btnDeal.Enabled = false;
            btnHit.Enabled = true;
            btnStay.Enabled = true;

            CpuCards.Clear();
            PlayerCards.Clear();

            Random r = new Random();

            int nextCard = r.Next(0, Cards.Length);


            while (PlayerCards.Count < 2) 
            {
                if (!PlayerCards.Contains(nextCard))
                    PlayerCards.Add(nextCard);
                nextCard = r.Next(0, Cards.Length);
            }

            while (CpuCards.Count < 2) 
            {
                if (!PlayerCards.Contains(nextCard) && !CpuCards.Contains(nextCard))
                    CpuCards.Add(nextCard);
                nextCard = r.Next(0, Cards.Length);
            }

            DisplayValues();

        }


        private void DisplayValues(bool hit = false, bool stay = false) 
        {
            lblPlayer.Text = "You: ";
            lblComputer.Text = "Comp: ";

            List<int> PlayerValues = new List<int>();
            List<int> CompValues = new List<int>();

            foreach (int i in PlayerCards) 
            {
                lblPlayer.Text += Cards[i];
                PlayerValues.Add(GetValue(Cards[i]));
            }

            foreach (int i in CpuCards) 
            {
                lblComputer.Text += Cards[i];
                CompValues.Add(GetValue(Cards[i]));
            }


            int PlayerTotal = 0;
            int CompTotal = 0;

            foreach (int i in PlayerValues) 
            {
                if (i == 1)
                {
                    PlayerTotal += 11;
                    if (PlayerTotal > 21)
                        PlayerTotal -= 10;
                }
                else 
                {
                    PlayerTotal += i;
                }
            }

            foreach (int i in CompValues) 
            {
                if (i == 1)
                {
                    CompTotal += 11;
                    if (CompTotal > 21)
                        CompTotal -= 10;
                }
                else 
                {
                    CompTotal += i;
                }
            }

            lblPlayer.Text += " Total: " + PlayerTotal.ToString();
            lblComputer.Text += " Total: " + CompTotal.ToString();

            if (PlayerTotal == 21 && CompTotal == 21)
            {
                Tie();
            }
            else 
            {
                if (PlayerTotal <= 21 && CompTotal <= 21)
                {
                    if (PlayerTotal == 21)
                        Win();
                    else if (CompTotal == 21)
                        Loss();
                }
                else 
                {
                    if (PlayerTotal > 21)
                        Loss();
                    else if (CompTotal > 21)
                        Win();
                    else
                      Tie();
                }
            }

            if (hit)
            {
                Random r = new Random();

                int nextCard = r.Next(0, Cards.Length);
                int curCount = PlayerCards.Count;

                while (PlayerCards.Count < curCount + 1)
                {
                    if (!PlayerCards.Contains(nextCard) && !CpuCards.Contains(nextCard))
                        PlayerCards.Add(nextCard);
                    nextCard = r.Next(0, Cards.Length);
                }

                DisplayValues();
            }

            if (stay) 
            {
                if (CompTotal < 17) 
                {
                    Random r = new Random();

                    int nextCard = r.Next(0, Cards.Length);
                    int curCount = CpuCards.Count;

                    while (CpuCards.Count < curCount + 1)
                    {
                        if (!PlayerCards.Contains(nextCard) && !CpuCards.Contains(nextCard))
                            CpuCards.Add(nextCard);
                        nextCard = r.Next(0, Cards.Length);
                    }

                    if (CompTotal < 17)
                        DisplayValues(false, true);
                    else
                        DisplayValues();
                }
            }

        }

        private void Tie() 
        {
            lblResult.Text = "Result: TIE!";
            btnDeal.Enabled = true;
            btnHit.Enabled = false;
            btnStay.Enabled = false;
         
        }

        private void Win() 
        {
            lblResult.Text = "Result: YOU WIN!";
            btnDeal.Enabled = true;
            btnHit.Enabled = false;
            btnStay.Enabled = false;
        }

        private void Loss() 
        {
            lblResult.Text = "Result: YOU LOSE!";
            btnDeal.Enabled = true;
            btnHit.Enabled = false;
            btnStay.Enabled = false;
        }


        private int GetValue(String s) 
        {
            if (s.Length > 2)
                return Convert.ToInt32(s.Substring(0, 2));
            else
                return Convert.ToInt32(s.Substring(0, 1));
        }

        private void btnHit_Click(object sender, EventArgs e)
        {
            DisplayValues(true, false);
        }

        private void btnStay_Click(object sender, EventArgs e)
        {
            DisplayValues(false, true);
        }


    }
}
Jiiks is offline  
post #8 of 34 (permalink) Old 06-12-2013, 08:58 AM - Thread Starter
New to Overclock.net
 
Plan9's Avatar
 
Join Date: Nov 2011
Location: Planet Vegeta
Posts: 8,040
Rep: 574 (Unique: 277)
Guys, would you mind putting your code in inside spoilers please:

[SPOILER=Source code, written in C#]
[CODE]
// code be here
[/CODE]
[/SPOILER]
Plan9 is offline  
post #9 of 34 (permalink) Old 06-12-2013, 09:24 AM
New to Overclock.net
 
Jiiks's Avatar
 
Join Date: Jun 2010
Location: Finland
Posts: 396
Rep: 166 (Unique: 118)
Quote:
Originally Posted by Plan9 View Post

Guys, would you mind putting your code in inside spoilers please:

[SPOILER=Source code, written in C#]
[CODE]
// code be here
[/CODE]
[/SPOILER]

Sure thumb.gif
Jiiks is offline  
post #10 of 34 (permalink) Old 06-12-2013, 10:31 AM
 
Join Date: Sep 2011
Posts: 264
Well I am going all out, all I have to do today is sit for a TB or two of files to be parsed.

EDIT: Did everyone elses' buttons to include, URL, images, formatting etc etc disappear?
Thereoncewasamaninparis is offline  
Reply

Quick Reply
Message:
Options

Register Now

In order to be able to post messages on the Overclock.net - An Overclocking Community forums, you must first register.
Please enter your desired user name, your email address and other required details in the form below.
User Name:
If you do not want to register, fill this field only and the name will be used as user name for your post.
Password
Please enter a password for your user account. Note that passwords are case-sensitive.
Password:
Confirm Password:
Email Address
Please enter a valid email address for yourself.
Email Address:

Log-in



Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Show Printable Version Show Printable Version
Email this Page Email this Page


Forum Jump: 

Posting Rules  
You may post new threads
You may post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are Off
Pingbacks are Off
Refbacks are Off