Showing posts with label problem. Show all posts
Showing posts with label problem. 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 3, 2013

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:

 


Do the Point and Rectangle ever Overlap?

Problem :
Convert the following specification into code. Do the point and rectangle ever overlap?
A point starts at [10, 20]. It repeatedly changes position by [3, 0.7] — e.g., under button or timer control. Meanwhile, a rectangle stays in place. Its corners are at [50, 50] (upper left), [180, 50] (upper right), [180, 140] (lower right), and [50, 140] (lower left).
To check for overlap, i.e., collision, just run your code and check visually. You do not need to implement a point-rectangle collision test. However, we encourage you to think about how you would implement such a test.




CODE :

import simplegui

# initialize state
width = 200
height = 200
position = [10, 20]
radius = 2
velocity = [3,0.7]

# event handlers
def keydown(key):
    if key == simplegui.KEY_MAP['down']:
        position[1] = position[1] - velocity[1]
        position[0] = position[0] - velocity[0]
 

    elif key == simplegui.KEY_MAP['up']:
        position[1] = position[1] + velocity[1]
        position[0] = position[0] + velocity[0]
  
   
def draw(canvas):
    canvas.draw_circle(position, radius, 2, "red", "red")
    canvas.draw_line((50, 50), (50, 140), 2, "White")
    canvas.draw_line((50, 140), (180, 140), 2, "White")
    canvas.draw_line((180, 50), (50, 50), 2, "White")
    canvas.draw_line((180, 140), (180, 50), 2, "White")

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

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

# start frame
frame.start()



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

Output :