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

Saturday, November 16, 2013

Mini-project # 5: Memory - Card Game

Mini-project development process

As usual, we suggest that you start from the program template for this mini-project.
  1. Model the deck of cards used in Memory as a list consisting of 16 numbers with each number lying in the range [0,8) and appearing twice. We suggest that you create this list by concatenating two list with range [0,8) together. Use the Docs to locate the list concatenation operator.
  2. Write a draw handler that iterates through the Memory deck using a for loop and uses draw_text to draw the number associated with each card on the canvas. The result should be a horizontal sequence of evenly-spaced numbers drawn on the canvas.
  3. Shuffle the deck using random.shuffle(). Remember to debug your canvas drawing code before shuffling to make debugging easier.
  4. Next, modify the draw handler to either draw a blank green rectangle or the card's value. To implement this behavior, we suggest that you create a second list called exposed. In the exposed list, the ith entry should be True if the ith card is face up and its value is visible or False if the ith card is face down and it's value is hidden. We suggest that you initialize exposed to some known values while testing your drawing code with this modification.
  5. Now, add functionality to determine which card you have clicked on with your mouse. Add an event handler for mouse clicks that takes the position of the mouse click and prints the index of the card that you have clicked on to the console. To make determining which card you have clicked on easy, we suggest sizing the canvas so that the sequence of cards entirely fills the canvas.
  6. Modify the event handler for mouse clicks to flip cards based on the location of the mouse click. If the player clicked on the ith card, you can change the value of exposed[i] from False to TrueIf the card is already exposed, you should ignore the mouseclick. At this point, the basic infrastructure for Memory is done.
  7. You now need to add game logic to the mouse click handler for selecting two cards and determining if they match. We suggest following the game logic in the example code discussed in the Memory video. State 0 corresponds to the start of the game. In state 0, if you click on a card, that card is exposed, and you switch to state 1. State 1 corresponds to a single exposed unpaired card. In state 1, if you click on an unexposed card, that card is exposed and you switch to state 2. State 2 corresponds to the end of a turn. In state 2, if you click on an unexposed card, that card is exposed and you switch to state 1.
  8. Note that in state 2, you also have to determine if the previous two cards are paired or unpaired. If they are unpaired, you have to flip them back over so that they are hidden before moving to state 1. We suggest that you use two global variables to store the index of each of the two cards that were clicked in the previous turn.
  9. Add a counter that keeps track of the number of turns and uses set_text to update this counter as a label in the control panel. (BTW, Joe's record is 12 turns.)  This counter should be incremented after either the first or second card is flipped during a turn.
  10. Finally, implement the new_game() function (if you have not already) so that the "Reset" button reshuffles the cards, resets the turn counter and restarts the game. All cards should start the game hidden.
  11. (Optional) You may replace the draw_text for each card by a draw_image that uses one of eight different images.
Once the run button is clicked in CodeSkulptor, the game should start. You should not have to hit the "Reset" button to start. Once the game is over, you should hit the "Reset" button to restart the game. 
While this project may seem daunting at first glance, our full implementation took well under 100 lines with comments and spaces. If you feel a little bit intimidated, focus on developing your project to step six. Our experience is that, at this point, you will begin to see your game come together and the going will get much easier.

CODE :

# mini-project #5 : Card game - Memory
import simplegui
import random
turns=0

# helper function to initialize globals
def new_game():
    global listOfCards,exposed,openedCard,clickCounter,turns
    listOfCards=[i for i in range(8)]+[i for i in range(8)]
    random.shuffle(listOfCards)
    exposed=[False for i in range(16)]
    openedCard=[]
    clickCounter=0
    turns=0
   
# define event handlers
def mouseclick(pos):
    global clickCounter,turns
    if clickCounter==0:
        openedCard.append(pos[0]//50)
        exposed[pos[0]//50]=True
        clickCounter+=1
        turns=1
        
    elif clickCounter==1:
        if not (pos[0]//50 in openedCard):
            openedCard.append(pos[0]//50)
            clickCounter+=1
        exposed[pos[0]//50]=True
       
    else:
        if not (pos[0]//50 in openedCard):
            if listOfCards[openedCard[-1]]!=listOfCards[openedCard[-2]]:
                exposed[openedCard[-1]]=False
                exposed[openedCard[-2]]=False
                openedCard.pop()
                openedCard.pop()
            clickCounter=1
            turns+=1
            exposed[pos[0]//50]=True
            openedCard.append(pos[0]//50)
                        
# cards are logically 50x100 pixels in size    
def draw(canvas):
        label.set_text("Turns = "+str(turns))
        for i in range(16):
            canvas.draw_line([50*(i%15+1),0], [50*(i%15+1),100], 2, "Green")
            if exposed[i]:
                canvas.draw_text(str(listOfCards[i]), [15+50*i,70], 40, "White")
         
# create frame and add a button and labels
frame = simplegui.create_frame("Memory", 800, 100)
frame.add_button("Restart", new_game) 
label=frame.add_label("Turns = 0")

# register event handlers
frame.set_mouseclick_handler(mouseclick)
frame.set_draw_handler(draw)

# get things rolling
new_game()
frame.start()

Output :




Sunday, November 10, 2013

Game- Pong!

Mini-project #4 - "Pong"

In this project, we will build a version of Pong, one of the first arcade video games (1972). While Pong is not particularly exciting compared to today's video games, Pong is relatively simple to build and provides a nice opportunity to work on the skills that you will need to build a game like Asteroids. As usual, we have provided a program template that can be used to guide your development of Pong.

Mini-project development process

  1. Add code to the program template that draws a ball moving across the Pong table. We recommend that you add the positional update for the ball to the draw handler as shown in the second part of the "Motion" video.
  2. Add code to the function spawn_ball that spawns a ball in the middle of the table and assigns the ball a fixed velocity (for now). Ignore the parameter direction at this point.
  3. Add a call to spawn_ball in the function new_game which starts a game of Pong. Note that the program templates includes an initial call to new_game in the main body of your program to get a game going immediately.
  4. Modify your code such that the ball collides with and bounces off of the top and bottom walls. Experiment with different hard-coded initial velocities to test your code.
  5. Add randomization to the velocity in spawn_ball(direction) The velocity of the ball should be upwards and towards the right ifdirection == RIGHT and upwards and towards the left if direction == LEFT. The exact values for the horizontal and vertical components of this velocity should be generated using random.randrange(). For the horizontal velocity, we suggest a speed of aroundrandom.randrange(120, 240) pixels per second. For the vertical velocity, we suggest a speed of around random.randrange(60, 180)pixels per second. (You will need to set the signs of velocities appropriately.)
  6. Add code to the draw handler that tests whether the ball touches/collides with the left and right gutters. (Remember that the gutters are offset from the left and right edges of the canvas by the width of the paddle as described in the "Pong" video.) When the ball touches a gutter, use either spawn_ball(LEFT) or spawn_ball(RIGHT) to respawn the ball in the center of the table headed towards the opposite gutter.
  7. Next, add code that draws the left and right paddles in their respective gutters. The vertical positions of these two paddles should depend on two global variables. (In the template, the variables were paddle1_pos and paddle2_pos.)
  8. Add code that modifies the values of these vertical positions via an update in the draw handler.  The update should reference two global variables that contain the vertical velocities of the paddles. (In the template, the variables were paddle1_vel and paddle2_vel.)
  9. Update the values of these two vertical velocities using key handlers. The "w" and "s" keys should control the vertical velocity of the left paddle while the "Up arrow" and "Down arrow" key should control the velocity of the right paddle. In our version of Pong, the left paddle moves up at a constant velocity if the "w" key is pressed and moves down at a constant velocity if the "s" is pressed and is motionless if neither is pressed. (The motion if both are pressed is up to you.) To achieve this effect, you will need to use both a keydown and a keyup handler to increase/decrease the vertical velocity in an appropriate manner.
  10. Restrict your paddles to stay entirely on the canvas by adding a check before you update the paddles' vertical positions in the draw handler. In particular, test whether the current update for a paddle's position will move part of the paddle off of the screen. If it does, don't allow the update.
  11. Modify your collision code for the left and right gutters in step 6 to check whether the ball is actually striking a paddle when it touches a gutter. If so, reflect the ball back into play. This collision model eliminates the possibility of the ball striking the edge of the paddle and greatly simplifies your collision/reflection code.
  12. To moderately increase the difficulty of your game, increase the velocity of the ball by 10% each time it strikes a paddle.
  13. Add scoring to the game as shown in the Pong video lecture. Each time the ball strikes the left or right gutter (but not a paddle), the opposite player receives a point and ball is respawned appropriately.
  14. Finally, add code to new_game which resets the score before calling spawn_ball. Add a "Restart" button that calls new_game to reset the score and relaunch the ball.

CODE :


#Mini-Project 4 : PONG

import simplegui
import random

# initialize globals - pos and vel encode vertical info for paddles
WIDTH = 600
HEIGHT = 400       
BALL_RADIUS = 20
PAD_WIDTH = 8
PAD_HEIGHT = 80
HALF_PAD_WIDTH = PAD_WIDTH / 2
HALF_PAD_HEIGHT = PAD_HEIGHT / 2

# helper function that spawns a ball by updating the 
# ball's position vector and velocity vector
# if right is True, the ball's velocity is upper right, else upper left
def ball_init(right):
    global ball_pos, ball_vel # these are vectors stored as lists
    
    ball_pos,ball_vel= [0, 0], [0, 0]
         
    if right == True:
        ball_pos = [WIDTH / 2, HEIGHT / 2]
        ball_vel = [random.randrange(2, 4), -random.randrange(1, 3)]
    if right == False:
        ball_pos = [WIDTH / 2, HEIGHT / 2]
        ball_vel = [-random.randrange(2, 4), -random.randrange(1, 3)]
# define event handlers

def new_game():
    global paddle1_pos, paddle2_pos, paddle1_vel, paddle2_vel  # these are floats
    global score1, score2  # these are ints
    global score1_string, score2_string
    score1_string = "0"
    score2_string = "0"
    
    paddle1_pos = [PAD_WIDTH / 2, HEIGHT / 2]
    paddle2_pos = [WIDTH - PAD_WIDTH / 2, HEIGHT / 2]
    paddle1_vel, paddle2_vel, score1, score2 = 0, 0, 0, 0
    ball_init(True)

# limit keeps the paddle on the screen
def limit():
    global paddle1_pos, paddle2_pos, paddle1_vel, paddle2_vel
   
    # check for paddle 1
    if paddle1_pos[1] < HALF_PAD_HEIGHT:
       paddle1_pos[1] = HALF_PAD_HEIGHT
       paddle1_vel = 0
    elif paddle1_pos[1] > HEIGHT - HALF_PAD_HEIGHT:
       paddle1_pos[1] = HEIGHT - HALF_PAD_HEIGHT
       paddle1_vel = 0
     
    # check for paddle 2    
    if paddle2_pos[1] < HALF_PAD_HEIGHT:
       paddle2_pos[1] = HALF_PAD_HEIGHT
       paddle2_vel = 0
    elif paddle2_pos[1] > HEIGHT - HALF_PAD_HEIGHT:
       paddle2_pos[1] = HEIGHT - HALF_PAD_HEIGHT
       paddle2_vel = 0
    
def draw(c):
    global score1, score2, paddle1_pos, paddle2_pos, ball_pos, ball_vel
    global score1_string, score2_string
    # update paddle's vertical position, keep paddle on the screen
    limit()
    paddle1_pos[1] += paddle1_vel 
    paddle2_pos[1] += paddle2_vel
    
    # draw mid line and gutters
    c.draw_line([WIDTH / 2, 0],[WIDTH / 2, HEIGHT], 1, "White")
    c.draw_line([PAD_WIDTH, 0],[PAD_WIDTH, HEIGHT], 1, "White")
    c.draw_line([WIDTH - PAD_WIDTH, 0],[WIDTH - PAD_WIDTH, HEIGHT], 1, "White")
    
    # draw paddles
    # paddle 1
    pad1top =  [paddle1_pos[0], paddle1_pos[1] - HALF_PAD_HEIGHT]
    pad1bot =  [paddle1_pos[0], paddle1_pos[1] + HALF_PAD_HEIGHT]
    c.draw_line(pad1top, pad1bot, PAD_WIDTH, "White")
    # paddle 2
    pad2top =  [paddle2_pos[0], paddle2_pos[1] - HALF_PAD_HEIGHT]
    pad2bot =  [paddle2_pos[0], paddle2_pos[1] + HALF_PAD_HEIGHT]
    c.draw_line(pad2top, pad2bot, PAD_WIDTH, "White")
     
    # update ball
    ball_pos[0] += ball_vel[0]
    ball_pos[1] += ball_vel[1]
    
    
    # collide and reflect off of left hand side of canvas
    # y directions
    if ball_pos[1] <= BALL_RADIUS:
        ball_vel[1] = - ball_vel[1]
    if ball_pos[1] > (HEIGHT - 1 - BALL_RADIUS):
        ball_vel[1] = - ball_vel[1]
    # x directions
    # paddle1
    if ball_pos[0] <= PAD_WIDTH + BALL_RADIUS:
        if ( pad1top[1] <= ball_pos[1] <= pad1bot[1] ):
            ball_vel[0] = - ball_vel[0] * 1.1
        else:
            ball_init(1)
            score2 += 1
            score2_string = str(score2) 
            
    # paddle2
    if ball_pos[0] >= WIDTH - PAD_WIDTH - BALL_RADIUS:
        if ( pad2top[1] <= ball_pos[1] <= pad2bot[1] ):
            ball_vel[0] = - ball_vel[0] * 1.1
        else:
            ball_init(0)
            score1 += 1
            score1_string = str(score1) 
       
    # draw ball and scores
    c.draw_circle(ball_pos, BALL_RADIUS, 1, "White", "White")
    c.draw_text(score2_string, (450, 50), 36, "White")
    c.draw_text(score1_string, (150, 50), 36, "White")

        
def keydown(key):
    acc = 1
    global paddle1_vel, paddle2_vel
    if key==simplegui.KEY_MAP["s"]:
        paddle1_vel += acc
    if key==simplegui.KEY_MAP["down"]:
        paddle2_vel += acc
   
def keyup(key):
    acc = 1
    global paddle1_vel, paddle2_vel
    if key==simplegui.KEY_MAP["w"]:
        paddle1_vel -= acc
    if key==simplegui.KEY_MAP["up"]:
        paddle2_vel -= acc

def restart():
    new_game()

def exit():
    frame.stop()

# create frame
frame = simplegui.create_frame("Pong", WIDTH, HEIGHT)
frame.set_draw_handler(draw)
frame.set_keydown_handler(keydown)
frame.set_keyup_handler(keyup)
frame.add_button("Restart", restart, 100)
frame.add_button("Exit ",exit,100)

# start frame
frame.start()
new_game()

Output :




Sunday, November 3, 2013

Stopwatch: The Game

Mini-project description - "Stopwatch: The Game"

Our mini-project for this week will focus on combining text drawing in the canvas with timers to build a simple digital stopwatch that keeps track of the time in tenths of a second. The stopwatch should contain "Start", "Stop" and "Reset" buttons. To help guide you through this project, we suggest that you download the provided program template for this mini-project and build your stopwatch program as follows:

Mini-project development process

  1. Construct a timer with an associated interval of 0.1 seconds whose event handler increments a global integer. (Remember thatcreate_timer takes the interval specified in milliseconds.) This integer will keep track of the time in tenths of seconds. Test your timer by printing this global integer to the console. Use the CodeSkulptor reset button in the blue menu bar to terminate your program and stop the timer and its print statements. Important: Do not use floating point numbers to keep track of tenths of a second! While it's certainly possible to get it working, the imprecision of floating point can make your life miserable. Use an integer instead, i.e., 12 represents 1.2 seconds.
  2. Write the event handler function for the canvas that draws the current time (simply as an integer, you should not worry about formatting it yet) in the middle of the canvas. Remember that you will need to convert the current time into a string using str before drawing it.
  3. Add "Start" and "Stop" buttons whose event handlers start and stop the timer. Next, add a "Reset" button that stops the timer and reset the current time to zero. The stopwatch should be stopped when the frame opens.
  4. Next, write a helper function format(t) that returns a string of the form A:BC.D where A, C and D are digits in the range 0-9 and Bis in the range 0-5. Test this function independent of your project. Note that the string returned by your helper function format should always correctly include leading zeros. For example
    • format(0) = 0:00.0
    • format(11) = 0:01.1
    • format(321) = 0:32.1
    • format(613) = 1:01.3
    Hint: Use integer division and remainder (modular arithmetic) to extract various digits for the formatted time from the global integer timer.
  5. Insert a call to the format function into your draw handler to complete the stopwatch. (Note that the stopwatch need only work correctly up to 10 minutes, beyond that its behavior is your choice.)
  6. Finally, to turn your stopwatch into a test of reflexes, add to two numerical counters that keep track of the number of times that you have stopped the watch and how many times you manage to stop the watch on a whole second (1.0, 2.0, 3.0, etc.). These counters should be drawn in the upper right-hand part of the stopwatch canvas in the form "x/y" where x is the number of successful stops and y is number of total stops. My best effort at this simple game is around a 25% success rate.
  7. Add code to ensure that hitting the "Stop" button when the timer is already stopped does not change your score. We suggest that you add a global Boolean variable that is True when the stopwatch is running and False when the stopwatch is stopped. You can then use this value to determine whether to update the score when the "Stop" button is pressed.
  8. Modify "Reset" so as to set these numbers back to zero when clicked.
Steps 1-3 and 5-7 above are relatively straightforward. However, step 4 requires some adept use of integer division and modular arithmetic. So, we again emphasize that you build and debug the helper function format(t) separately.

Code:


# Mini-Project 4: The Digital Stop Watch Game!

import simplegui

# Define global variables
mins, sec, count, x, y, z1, z2 = 0, 0, 0, 0, 0, 0, 0

# counting tenths of seconds into formatted string A:BC.D
def format(t):
    global count, sec, mins
    t = count    
    if (t == 10):
        sec += 1
        count = 0
    if (sec == 60):
        mins += 1
        sec = 0
        
# Event handlers for buttons; "Start", "Stop", "Reset" and "Exit"

def start_timer():
    global z1, z2
    if z1-z2 == 0:
        z1 += 1
        timer.start()

def stop_timer():
    global x, y, z1, z2
    if z1-z2 == 1:
        z2 += 1
        timer.stop()
        y += 1
        if count == 0 :
            x += 1
    
def reset_timer():
    global count, sec, mins, x, y, z1,z2
    timer.stop()
    mins, sec, count, x, y,z1,z2 = 0, 0, 0, 0, 0, 0, 0
    
def exit_timer():
    frame.stop()

# Event handler for timer with 0.1 sec interval
def timer_handler():
    global count
    count += 1
    
def draw_handler(canvas):
    global count, sec, min, x, y
    format(count)
    canvas.draw_text(str(x)+"/"+str(y), (135,30), 30, "Red")
    if (sec < 10):
        canvas.draw_text(str(mins)+":"+ "0"+str(sec)+"."+str(count),(60,100),30,"White")
    else:
        canvas.draw_text(str(mins)+":"+str(sec)+"."+str(count),(60,100),30,"White")
    

# create frame
frame = simplegui.create_frame("Digital Stopwatch Game! ",200,200)

# register event handlers
timer = simplegui.create_timer(100,timer_handler)
frame.add_button("Start",start_timer,100)
frame.add_button("Stop ",stop_timer,100)
frame.add_button("Reset",reset_timer,100)
frame.add_button("Exit ",exit_timer,100)
frame.set_draw_handler(draw_handler)

# start frame
frame.start()

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

Result :




Key handling problem

Write a Python program that initializes a global variable to 5. The keydown event handler updates this global variable by doubling it, while the keyup event handler updates it by decrementing it by 3.

What is the value of the global variable after 12 separate key presses, i.e., pressing and releasing one key at a time, and repeating this 12 times in total?

To test your code, the global variable's value should be 35 after 4 key presses.




CODE :

import simplegui
var, i = 5, 0
current_key=''

# event handlers
def keydown(key):
    global var,i, current_key
    current_key=chr(key)
    var*=2
def keyup(key):
    global var,i, current_key
    current_key= ''
    var-=3
    i+=1
      
def count():
    return str(i)

def result ():
    return str(var)
  
def draw(canvas):
    canvas.draw_text('Count'  , (30, 80), 25, 'White')
    canvas.draw_text('Result' , (110,80), 25, 'White')
    canvas.draw_text( count() , (50, 110), 30, 'Green')
    canvas.draw_text( result(), (110, 110), 30, 'Green')


# create frame
frame = simplegui.create_frame("Key Handling", 200, 200)

# register event handlers
frame.set_keydown_handler(keydown)
frame.set_keyup_handler(keyup)
frame.set_draw_handler(draw)

# start frame
frame.start()


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

Output: