Showing posts with label Program. Show all posts
Showing posts with label Program. Show all posts

Wednesday, December 4, 2013

Mini Project Spaceship!

Mini-project description - Spaceship

In our last two mini-projects, we will build a 2D space game RiceRocks that is inspired by the classic arcade game Asteroids (1979). Asteroids is a relatively simple game by today's standards, but was still immensely popular during its time. (Joe spent countless quarters playing it.) In the game, the player controls a spaceship via four buttons: two buttons that rotate the spaceship clockwise or counterclockwise (independent of its current velocity), a thrust button that accelerates the ship in its forward direction and a fire button that shoots missiles. Large asteroids spawn randomly on the screen with random velocities. The player's goal is to destroy these asteroids before they strike the player's ship. In the arcade version, a large rock hit by a missile split into several fast moving small asteroids that themselves must be destroyed. Occasionally, a flying saucer also crosses the screen and attempts to destroy the player's spaceship. Searching for "asteroids arcade" yields links to multiple versions of Asteroids that are available on the web (including an updated version by Atari, the original creator of Asteroids).

Mini-project development process

For this mini-project, you will implement a working spaceship plus add a single asteroid and a single missile. We have provided art for your game so its look and feel is that of a more modern game. You should begin by loading the program template.The program template includes all necessary image and audio files. Unfortunately, no audio format is supported by all major browsers so we have decided to provided sounds in the mp3 format which is supported by Chrome (but not by Firefox on some systems). (ogg versions are also available.) We highly recommend using Chrome for the last two weeks of the class. We have found that Chrome typically has better performance on games with more substantial drawing requirements and standardization on a common browser will make peer assessing projects more reliable.

Phase one - Spaceship
In this phase, you will implement the control scheme for the spaceship.This includes a complete Spaceship class and the appropriate keyboard handlers to control the spaceship. Your spaceship should behave as follows:
  • The left and right arrows should control the orientation of your spaceship. While the left arrow is held down, your spaceship should turn counter-clockwise. While the right arrow is down, your spaceship should turn clockwise. When neither key is down, your ship should maintain its orientation. You will need to pick some reasonable angular velocity at which your ship should turn.
  • The up arrow should control the thrusters of your spaceship. The thrusters should be on when the up arrow is down and off when it is up. When the thrusters are on, you should draw the ship with thrust flames. When the thrusters are off, you should draw the ship without thrust flames.
  • When thrusting, the ship should accelerate in the direction of its forward vector. This vector can be computed from the orientation/angle of the ship using the provided helper function angle_to_vector. You will need to experiment with scaling each component of this acceleration vector to generate a reasonable acceleration.
  • Remember that while the ship accelerates in its forward direction, but the ship always moves in the direction of its velocity vector. Being able to accelerate in a direction different than the direction that you are moving is a hallmark of Asteroids.
  • Your ship should always experience some amount of friction. (Yeah, we know, "Why is there friction in the vacuum of space?". Just trust us there is in this game.) This choice means that the velocity should always be multiplied by a constant factor less than one to slow the ship down. It will then come to a stop eventually after you stop the thrusters.
Now, implement these behaviors above in order. Each step should require just a few lines of code. Here are some hints:
  1. Modify the draw method for the Ship class to draw the ship image (without thrust flames) instead of a circle. This method should incorporate the ship's position and angle. Note that the angle should be in radians, not degrees. Since a call to the ship's draw method already exists in the draw handler, you should now see the ship image. Experiment with different positions and angles for the ship.
  2. Implement an initial version of the update method for the ship. This version should update the position of the ship based on its velocity. Since a call to the update method also already exists in the draw handler, the ship should move in response to different initial velocities.
  3. Modify the update method for the ship to increment its angle by its angular velocity.
  4. Make your ship turn in response to the left/right arrow keys. Add keydown and keyup handlers that check the left and right arrow keys. Add methods to the Ship class to increment and decrement the angular velocity by a fixed amount. (There is some flexibility in how you structure these methods.) Call these methods in the keyboard handlers appropriately and verify that you can turn your ship as you expect.
  5. Modify the keyboard handlers to turn the ship's thrusters on/off. Add a method to the Ship class to turn the thrusters on/off (you can make it take a Boolean argument which is True or False to decide if they should be on or off).
  6. Modify the ship's draw method to draw the thrust image when it is on. (The ship image is tiled and contains both images of the ship.)
  7. Modify the ship's thrust method to play the thrust sound when the thrust is on. Rewind the sound when the thrust turns off.
  8. Add code to the ship's update method to use the given helper function angle_to_vector to compute the forward vector pointing in the direction the ship is facing based on the ship's angle.
  9. Next, add code to the ship's update method to accelerate the ship in the direction of this forward vector when the ship is thrusting. You will need to update the velocity vector by a small fraction of the forward acceleration vector so that the ship does not accelerate too fast.
  10. Then, modify the ship's update method such that the ship's position wraps around the screen when it goes off the edge (use modular arithmetic!).
  11. Up to this point, your ship will never slow down. Finally, add friction to the ship's update method as shown in the "Acceleration and Friction" video by multiplying each component of the velocity by a number slightly less than 1 during each update.
You should now have a ship that flies around the screen,as you would like for RiceRocks. Adjust the constants as you would like to get it to fly how you want.

Phase two - Rocks

To implement rocks, we will use the provided Sprite class. Note that the update method for the sprite will be very similar to the update method for the ship. The primary difference is that the ship's velocity and rotation are controlled by keys, whereas sprites have these set randomly when they are created. Rocks should screen wrap in the same manner as the ship.
In the template, the global variable a_rock is created at the start with zero velocity. Instead, we want to create version of a_rock once every second in the timer handler. Next week, we will add multiple rocks. This week, the ship will not die if it hits a rock. We'll add that next week. To implement rocks, we suggest the following:
  1. Complete the Sprite class (as shown in the "Sprite class" video) by modifying the draw handler to draw the actual image and the update handler to make the sprite move and rotate. Rocks do not accelerate or experience friction, so the sprite update method should be simpler than the ship update method. Test this by giving a_rock different starting parameters and ensuring it behaves as you expect.
  2. Implement the timer handler rock_spawner. In particular, set a_rock to be a new rock on every tick. (Don't forget to declare a_rock as a global in the timer handler.) Choose a velocity, position, and angular velocity randomly for the rock. You will want to tweak the ranges of these random numbers, as that will affect how fun the game is to play. Make sure you generated rocks that spin in both directions and, likewise, move in all directions.
Phase three - Missiles

To implement missiles, we will use the same sprite class as for rocks. Missiles will always have a zero angular velocity. They will also have a lifespan (they should disappear after a certain amount of time or you will eventually have missiles all over the place), but we will ignore that this week. Also, for now, we will only allow a single missile and it will not yet blow up rocks. We'll add more next week.
Your missile should be created when you press the spacebar, not on a timer like rocks. They should screen wrap just as the ship and rocks do. Otherwise, the process is very similar:
  1. Add a shoot method to your ship class. This should spawn a new missile (for now just replace the old missile in a_missile). The missile's initial position should be the tip of your ship's "cannon". Its velocity should be the sum of the ship's velocity and a multiple of the ship's forward vector.
  2. Modify the keydown handler to call this shoot method when the spacebar is pressed.
  3. Make sure that the missile sound is passed to the sprite initializer so that the shooting sound is played whenever you shoot a missile.
Phase four - User interface
Our user interface for RiceRocks simply shows the number of lives remaining and the score. This week neither of those elements ever change, but they will next week. Add code to the draw event handler to draw these on the canvas. Use the lives and score global variables as the current lives remaining and score.

CODE :

# program template for Spaceshipimport simpleguiimport mathimport random
# globals for user interfaceWIDTH = 800HEIGHT = 600score = 0lives = 3time = 0.5
class ImageInfo:    def __init__(self, center, size, radius = 0, lifespan = None, animated = False):        self.center = center        self.size = size        self.radius = radius        if lifespan:            self.lifespan = lifespan        else:            self.lifespan = float('inf')        self.animated = animated
    def get_center(self):        return self.center
    def get_size(self):        return self.size
    def get_radius(self):        return self.radius
    def get_lifespan(self):        return self.lifespan
    def get_animated(self):        return self.animated

# debris images - debris1_brown.png, debris2_brown.png, debris3_brown.png, debris4_brown.png#                 debris1_blue.png, debris2_blue.png, debris3_blue.png, debris4_blue.png, debris_blend.pngdebris_info = ImageInfo([320, 240], [640, 480])debris_image = simplegui.load_image("http://commondatastorage.googleapis.com/codeskulptor-assets/lathrop/debris2_blue.png")
# nebula images - nebula_brown.png, nebula_blue.pngnebula_info = ImageInfo([400, 300], [800, 600])nebula_image = simplegui.load_image("http://commondatastorage.googleapis.com/codeskulptor-assets/lathrop/nebula_blue.f2013.png")
# splash imagesplash_info = ImageInfo([200, 150], [400, 300])splash_image = simplegui.load_image("http://commondatastorage.googleapis.com/codeskulptor-assets/lathrop/splash.png")
# ship imageship_info = ImageInfo([45, 45], [90, 90], 35)ship_image = simplegui.load_image("http://commondatastorage.googleapis.com/codeskulptor-assets/lathrop/double_ship.png")
# missile image - shot1.png, shot2.png, shot3.pngmissile_info = ImageInfo([5,5], [10, 10], 3, 50)missile_image = simplegui.load_image("http://commondatastorage.googleapis.com/codeskulptor-assets/lathrop/shot2.png")
# asteroid images - asteroid_blue.png, asteroid_brown.png, asteroid_blend.pngasteroid_info = ImageInfo([45, 45], [90, 90], 40)asteroid_image = simplegui.load_image("http://commondatastorage.googleapis.com/codeskulptor-assets/lathrop/asteroid_blue.png")
# animated explosion - explosion_orange.png, explosion_blue.png, explosion_blue2.png, explosion_alpha.pngexplosion_info = ImageInfo([64, 64], [128, 128], 17, 24, True)explosion_image = simplegui.load_image("http://commondatastorage.googleapis.com/codeskulptor-assets/lathrop/explosion_alpha.png")
# sound assets purchased from sounddogs.com, please do not redistributesoundtrack = simplegui.load_sound("http://commondatastorage.googleapis.com/codeskulptor-assets/sounddogs/soundtrack.mp3")missile_sound = simplegui.load_sound("http://commondatastorage.googleapis.com/codeskulptor-assets/sounddogs/missile.mp3")missile_sound.set_volume(.5)ship_thrust_sound = simplegui.load_sound("http://commondatastorage.googleapis.com/codeskulptor-assets/sounddogs/thrust.mp3")explosion_sound = simplegui.load_sound("http://commondatastorage.googleapis.com/codeskulptor-assets/sounddogs/explosion.mp3")
# helper functions to handle transformationsdef angle_to_vector(ang):    return [math.cos(ang), math.sin(ang)]
def dist(p,q):    return math.sqrt((p[0] - q[0]) ** 2+(p[1] - q[1]) ** 2)

# Ship classclass Ship:    def __init__(self, pos, vel, angle, image, info):        self.pos = [pos[0],pos[1]]        self.vel = [vel[0],vel[1]]        self.thrust = False        self.angle = angle        self.angle_vel = 0        self.image = image        self.image_center = info.get_center()        self.image_size = info.get_size()        self.radius = info.get_radius()            def draw(self,canvas):        if self.thrust:            self.image_center[0]=135        else:            self.image_center[0]=45        canvas.draw_image(self.image, self.image_center, self.image_size, self.pos, self.image_size,self.angle)
    def update(self):        self.vel[0]*=0.98        self.vel[1]*=0.98        self.pos[0]+=self.vel[0]        self.pos[0]%=WIDTH        self.pos[1]+=self.vel[1]        self.pos[1]%=HEIGHT        self.angle+=self.angle_vel        if self.thrust:            ship_thrust_sound.play()        else:            ship_thrust_sound.rewind()                    if self.thrust:            foward=angle_to_vector(self.angle)            self.vel[0]+=foward[0]/10            self.vel[1]+=foward[1]/10                def shoot(self):        global a_missile        foward=angle_to_vector(self.angle)        tmppos=[self.pos[0]+45*foward[0],self.pos[1]+45*foward[1]]        tmpvel=[self.vel[0]+foward[0]*3,self.vel[1]+foward[1]*3]        a_missile = Sprite(tmppos, tmpvel, 0, 0, missile_image, missile_info, missile_sound)        missile_sound.play()       # Sprite classclass Sprite:    def __init__(self, pos, vel, ang, ang_vel, image, info, sound = None):        self.pos = [pos[0],pos[1]]        self.vel = [vel[0],vel[1]]        self.angle = ang        self.angle_vel = ang_vel        self.image = image        self.image_center = info.get_center()        self.image_size = info.get_size()        self.radius = info.get_radius()        self.lifespan = info.get_lifespan()        self.animated = info.get_animated()        self.age = 0        if sound:            sound.rewind()            sound.play()       def draw(self, canvas):        canvas.draw_image(self.image, self.image_center, self.image_size, self.pos, self.image_size,self.angle)        def update(self):        self.pos[0]+=self.vel[0]        self.pos[0]%=WIDTH        self.pos[1]+=self.vel[1]        self.pos[1]%=HEIGHT        self.angle+=self.angle_vel
           def draw(canvas):    global time        # animiate background    time += 1    wtime = (time / 4) % WIDTH    center = debris_info.get_center()    size = debris_info.get_size()    canvas.draw_image(nebula_image, nebula_info.get_center(), nebula_info.get_size(), [WIDTH / 2, HEIGHT / 2], [WIDTH, HEIGHT])    canvas.draw_image(debris_image, center, size, (wtime - WIDTH / 2, HEIGHT / 2), (WIDTH, HEIGHT))    canvas.draw_image(debris_image, center, size, (wtime + WIDTH / 2, HEIGHT / 2), (WIDTH, HEIGHT))
    # draw ship and sprites    my_ship.draw(canvas)    a_rock.draw(canvas)    a_missile.draw(canvas)        canvas.draw_text('Lives : '+str(lives), (40, 50), 30, "White")    canvas.draw_text('Score : '+str(score), (650, 50), 30, "White")
    # update ship and sprites    my_ship.update()    a_rock.update()    a_missile.update()            # timer handler that spawns a rock    def rock_spawner():    global a_rock    a_rock = Sprite([random.random()*WIDTH, random.random()*HEIGHT], [random.random(), random.random()], random.random()*2*math.pi, random.random()*0.1, asteroid_image, asteroid_info)    def keydown(key):    if key==simplegui.KEY_MAP['left']:        my_ship.angle_vel=-0.1    elif key==simplegui.KEY_MAP['right']:        my_ship.angle_vel=0.1    elif key==simplegui.KEY_MAP['up']:        my_ship.thrust=True    elif key==simplegui.KEY_MAP['space']:        my_ship.shoot()        def keyup(key):    if key==simplegui.KEY_MAP['left']:        my_ship.angle_vel=0    elif key==simplegui.KEY_MAP['right']:        my_ship.angle_vel=0    elif key==simplegui.KEY_MAP['up']:        my_ship.thrust=False# initialize frameframe = simplegui.create_frame("Asteroids", WIDTH, HEIGHT)
# initialize ship and two spritesmy_ship = Ship([WIDTH / 2, HEIGHT / 2], [0, 0], 0, ship_image, ship_info)a_rock = Sprite([WIDTH / 3, HEIGHT / 3], [1, 1], 0, 0, asteroid_image, asteroid_info)a_missile = Sprite([2 * WIDTH / 3, 2 * HEIGHT / 3], [-1,1], 0, 0, missile_image, missile_info, missile_sound)
def exit():    frame.stop()
# register handlersframe.set_draw_handler(draw)frame.set_keydown_handler(keydown)  frame.set_keyup_handler(keyup)  frame.add_button("Exit", exit, 100)timer = simplegui.create_timer(1000.0, rock_spawner)# get things rollingtimer.start()frame.start()

http://www.codeskulptor.org/#user27_52XpOclvA4xgm25.py

Tuesday, November 26, 2013

Mini-Project : Blackjack

Mini-project description - Blackjack

Blackjack is a simple, popular card game that is played in many casinos. Cards in Blackjack have the following values: an ace may be valued as either 1 or 11 (player's choice), face cards (kings, queens and jacks) are valued at 10 and the value of the remaining cards corresponds to their number. During a round of Blackjack, the players plays against a dealer with the goal of building a hand (a collection of cards) whose cards have a total value that is higher than the value of the dealer's hand, but not over 21.  (A round of Blackjack is also sometimes referred to as a hand.)
The game logic for our simplified version of Blackjack is as follows. The player and the dealer are each dealt two cards initially with one of the dealer's cards being dealt faced down (his hole card). The player may then ask for the dealer to repeatedly "hit" his hand by dealing him another card. If, at any point, the value of the player's hand exceeds 21, the player is "busted" and loses immediately. At any point prior to busting, the player may "stand" and the dealer will then hit his hand until the value of his hand is 17 or more. (For the dealer, aces count as 11 unless it causes the dealer's hand to bust). If the dealer busts, the player wins. Otherwise, the player and dealer then compare the values of their hands and the hand with the higher value wins.The dealer wins ties in our version.

Mini-project development process

We suggest you develop your Blackjack game in two phases. The first phase will concentrate on implementing the basic logic of Blackjack while the second phase will focus on building a more full-featured version. In phase one, you will use buttons to control the game and print the state of the game to the console using print statements. In the second phase, you will replace the print statements by drawing images and text on the canvas and add some extra game logic.
In phase one, we will provide testing templates for four of the steps. The templates are designed to check whether your class implementations work correctly. You should copy your class definition into the testing template and compare the console output generated by running the template with the provided output. If the output matches, it is likely that your implementation of the class is correct. DO NOT PROCEED TO THE NEXT STEP UNTIL YOUR CODE WORKS WITH THE PROVIDED TESTING TEMPLATE. Debugging code that uses incorrectly implemented classes is extremely difficult. Avoid this problem by using our provided testing templates.
Phase one
  1. Download the program template for this mini-project and review the class definition for the Card class. This class is already implemented so your task is to familiarize yourself with the code. Start by pasting the Card class definition into the provided testing template and verifying that our implementation works as expected.
  2. Implement the methods __init__, __str__, add_card for the Hand class. We suggest modeling a hand as a list of cards. For help in implementing the __str__ method for hands, refer back to practice exercise number four from last week. Remember to use the string method for cards to convert each card object into a string. Once you have implemented the Hand class, test it using the provided testing template.
  3. Implement the methods for the Deck class listed in the mini-project template. We suggest modeling a deck of cards as list of cards. You can generate this list using a pair of nested for loops or a list comprehension. Remember to use the Card initializer to create your cards. Userandom.shuffle() to shuffle this deck of cards. Once you have implemented the Deck class, test your Deck class using the provided testing template. Remember that the deck is randomized after shuffling, so the output of the testing template should match the output in the comments in form but not in exact value.
  4. Implement the handler for a "Deal" button that shuffles the deck and deals the two cards to both the dealer and the player. The event handlerdeal for this button should shuffle the deck (stored as a global variable), create new player and dealer hands (stored as global variables), and add two cards to each hand. To transfer a card from the deck to a hand, you should use the deal_card method of the Deck class and theadd_card method of Hand class in combination. The resulting hands should be printed to the console with an appropriate message indicating which hand is which.
  5. Implement the get_value method for the Hand class. You should use the provided VALUE dictionary to look up the value of a single card in conjunction with the logic explained in the video lecture for this project to compute the value of a hand. Once you have implemented theget_value method, test it using the provided testing template 
  6. Implement the handler for a "Hit" button. If the value of the hand is less than or equal to 21, clicking this button adds an extra card to player's hand. If the value exceeds 21 after being hit, print "You have busted".
  7. Implement the handler for a "Stand" button. If the player has busted, remind the player that they have busted. Otherwise, repeatedly hit the dealer until his hand has value 17 or more (using a while loop). If the dealer busts, let the player know. Otherwise, compare the value of the player's and dealer's hands. If the value of the player's hand is less than or equal to the dealer's hand, the dealer wins. Otherwise the player has won.Remember the dealer wins ties in our version.
In our version of Blackjack, a hand is automatically dealt to the player and dealer when the program starts. In particular, the program template includes a call to the deal() function during initialization. At this point, we would suggest testing your implementation of Blackjack extensively.
Phase two
In the second phase of your implementation, you will add five features. For those involving drawing with global variables, remember to initialize these variables to appropriate values (like creating empty hands for the player and dealer) just before starting the frame.  
  1. Implement your own draw method for the Hand class using the draw method of the Card class. We suggest drawing a hand as a horizontal sequence of cards where the parameter pos is the position of the upper left corner of the leftmost card. To simplify your code, you may assume that only the first five cards of a player's hand need to be visible on the canvas.
  2. Replace printing in the console by drawing text messages on the canvas. We suggest adding a global outcome string that is drawn in the draw handler using draw_text. These messages should prompt the player to take some require action and have a form similar to "Hit or stand?" and "New deal?". Also, draw the title of the game, "Blackjack", somewhere on the canvas.
  3. Add logic using the global variable in_play that keeps track of whether the player's hand is still being played. If the round is still in play, you should draw an image of the back of a card (provided in the template) over the dealer's first (hole) card to hide it. Once the round is over, the dealer's hole card should be displayed.
  4. Add a score counter that keeps track of wins and losses for your Blackjack session. In the simplest case (see our demo), the program displays wins minus losses. However, you are welcome to implement a more sophisticated betting/scoring system.
  5. Modify the logic for the "Deal" button to create and shuffle a new deck (or restock and shuffle an existing deck) each time the "Deal" button is clicked. This change avoids the situation where the deck becomes empty during play.
  6. Finally, modify the deal function such that, if the "Deal" button is clicked during the middle of a round, the program reports that the player lost the round and updates the score appropriately.
Congratulations! You have just built Blackjack. To wrap things up, please review the demo of our version of Blackjack in the Blackjack video lecture to ensure that your version has full functionality.

CODE :

# Mini-project #6 - Blackjack

import simplegui
import random

# load card sprite - 949x392 - source: jfitz.com
CARD_SIZE = (73, 98)
CARD_CENTER = (36.5, 49)
card_images = simplegui.load_image("http://commondatastorage.googleapis.com/codeskulptor-assets/cards.jfitz.png")

CARD_BACK_SIZE = (71, 96)
CARD_BACK_CENTER = (35.5, 48)
card_back = simplegui.load_image("http://commondatastorage.googleapis.com/codeskulptor-assets/card_back.png")

# initialize global variables
in_play = False
message = ""
outcome = ""
score = 0
popped = []
player = []
dealer = []
deck = []

# define globals for cards
SUITS = ('C', 'S', 'H', 'D')
RANKS = ('A', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K')
VALUES = {'A':1, '2':2, '3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9':9, 'T':10, 'J':10, 'Q':10, 'K':10}

# Card class. Hand class calls this draw method for rendering card images onto canvas
class Card:
    def __init__(self, suit, rank):
        if (suit in SUITS) and (rank in RANKS):
            self.suit = suit
            self.rank = rank
        else:
            self.suit = None
            self.rank = None

    def __str__(self):
        return self.suit + self.rank

    def get_suit(self):
        return self.suit

    def get_rank(self):
        return self.rank

    def draw(self, canvas, pos):
        card_loc = (CARD_CENTER[0] + CARD_SIZE[0] * RANKS.index(self.rank), 
                    CARD_CENTER[1] + CARD_SIZE[1] * SUITS.index(self.suit))
        canvas.draw_image(card_images, card_loc, CARD_SIZE, [pos[0] + CARD_CENTER[0], pos[1] + CARD_CENTER[1]], CARD_SIZE)
        
# Hand class used for adding card objects from Deck() and for getting the value of hands
class Hand:
    def __init__(self):
        self.player_hand = []

    def __str__(self):
        s = ''
        for c in self.player_hand:
            s = s + str(c) + ' '
        return s

    def add_card(self, card):
        self.player_hand.append(card)
        return self.player_hand

    def get_value(self):
        value = 0
        for card in self.player_hand:
            rank = card.get_rank()
            value = value + VALUES[rank]
        for card in self.player_hand:
            rank = card.get_rank()    
            if rank == 'A' and value <= 11:
                value += 10
        return value
    
    def draw(self, canvas, p):
        pos = p
        for card in self.player_hand:
            card.draw(canvas, p)
            pos[0] = pos[0] + 90
        if in_play == True:
            canvas.draw_image(card_back, CARD_BACK_CENTER, CARD_BACK_SIZE, [115.5,184], CARD_BACK_SIZE)
        
# Deck class used for re-shuffling between hands and giving card objects to Hand as called
class Deck:
    def __init__(self):
        popped = []
        self.cards = [Card(suit, rank) for suit in SUITS for rank in RANKS]
        self.shuffle()
        
    def __str__(self):
        s = ''
        for c in self.cards:
            s = s + str(c) + ' '
        return s

    def shuffle(self):
        random.shuffle(self.cards)

    def deal_card(self):
        popped = self.cards.pop(0)
        return popped
    
def deal():
    # deal function deals initial hands and adjusts message.
    global in_play, player, dealer, deck, message, score, outcome
    if in_play == True:
        # if player clicks Deal button during a hand, player loses hand in progress
        message = "Here is the new hand"
        score -= 1
        deck = Deck()
        player = Hand()
        dealer = Hand()
        player.add_card(deck.deal_card())
        dealer.add_card(deck.deal_card())
        player.add_card(deck.deal_card())
        dealer.add_card(deck.deal_card())
    if in_play == False:
        # starts a new hand
        deck = Deck()
        player = Hand()
        dealer = Hand()
        player.add_card(deck.deal_card())
        dealer.add_card(deck.deal_card())
        player.add_card(deck.deal_card())
        dealer.add_card(deck.deal_card())
        message = "New Hand. Hit or Stand?"
    in_play = True
    outcome = ""

def hit():
    # deals player a new hand and ends hand if it causes a bust.
    global in_play, score, message
    if in_play == True:
        player.add_card(deck.deal_card())
        message = "Hit or Stand?"
        if player.get_value() > 21:
            in_play = False
            message = "Player busted! You Lose! Play again?"
            score -= 1
            outcome = "Dealer: " + str(dealer.get_value()) + "  Player: " + str(player.get_value())

def stand():
    # hits dealer until >=17 or busts. Determines winner of hand and adjusts score, game state, and messages
    global in_play, score, message, outcome
    if in_play == False:
        message = "The hand is already over. Deal again."
    else:
        while dealer.get_value() < 17:
            dealer.add_card(deck.deal_card())
        if dealer.get_value() > 21:
            message = "Dealer busted. You win! Play again?"
            score += 1
            in_play = False
            
        elif dealer.get_value() > player.get_value():
            message = "Dealer wins! Play again?"
            score -= 1
            in_play = False
        
        elif dealer.get_value() == player.get_value():
            message = "Tie! Dealer wins! Play again?"
            score -= 1
            in_play = False
        
        elif dealer.get_value() < player.get_value():
            message = "You win! Play again?"
            score += 1
            in_play = False
            
        outcome = "Dealer: " + str(dealer.get_value()) + "  Player: " + str(player.get_value())
        
def exit():
    frame.stop()
    
# draw handler
def draw(canvas):
    canvas.draw_text("Blackjack", [270,50], 48, "Yellow")
    canvas.draw_text("Score : " + str(score), [80,520], 36, "Black")
    canvas.draw_text("Dealer :", [80,110], 30, "Black")
    canvas.draw_text("Player :", [80,300], 30, "Black")
    canvas.draw_text(message, [200,480], 26, "Black")
    canvas.draw_text(outcome, [80,560], 28, "White")
    dealer.draw(canvas, [80,135])
    player.draw(canvas, [80,325])
    

# initialization frame
frame = simplegui.create_frame("Blackjack", 700, 600)
frame.set_canvas_background("Green")

# buttons and canvas callback
frame.add_button("Deal", deal, 200)
frame.add_button("Hit", hit, 200)
frame.add_button("Stand", stand, 200)
frame.add_button("Exit", exit, 200)
frame.set_draw_handler(draw)

# deals initial hand
deal()

# get things rolling
frame.start()


OUTPUT :