среда, 28 мая 2014 г.

Mini-project # 5 - Memory

An Introduction to Interactive Programming in Python

Mini-project # 5 - Memory

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 theexposed 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] fromFalse to True. If 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 codediscussed 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.


SOLUTION
# implementation of card game - Memory

import simplegui
import random
list1 = range(0, 8)
list2 = range(0, 8)
lists = list1 + list2
numOpen = []
turns = 0
select = [-1, -1]
status = 0

# helper function to initialize globals
def new_game():
    global lists, numOpen, turns, select, status
    numOpen = [0] * 16
    turns = 0
    select = [-1, -1]
    status = 0
    label.set_text("Turns = 0")
    random.shuffle(lists) 
     
# define event handlers
def mouseclick(pos):
    global select, status, turns
    index = int(pos[0] / 50)
    if(status == 0):
        if(numOpen[index] == 0):
            if(lists[select[0]] != lists[select[1]]):
                numOpen[select[0]] = 0
                numOpen[select[1]] = 0
            numOpen[index] = 1
            status = 1
            select[0] = index
    elif status == 1:
        if(numOpen[index] == 0):
            status = 0
            numOpen[index] = 1
            select[1] = index
            turns += 1   
            label.set_text("Turns = " + str(turns))
            if not(0 in numOpen):
                print "The game end. "+str(turns)+" turns"
                      
# cards are logically 50x100 pixels in size    
def draw(canvas):
    for simbol in range(0,len(lists)):
        if(numOpen[simbol]==0):
            canvas.draw_polygon([(simbol * 50, 0),
                         (simbol * 50 + 50, 0),
                         (simbol * 50 + 50, 100),
                         (simbol * 50, 100)], 1, "Black", "Green")
        else:
            canvas.draw_text(str(lists[simbol]), [simbol * 50 + 10, 70], 48, "White")

# create frame and add a button and labels
frame = simplegui.create_frame("Memory", 800, 100)
frame.add_button("Reset", 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()


# Always remember to review the grading rubric

The code reference (CodeSkulptor )

Mini-project # 4 - "Pong"

An Introduction to Interactive Programming in Python

Mini-project # 4 - "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 if direction == 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 around random.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.
Your final version of Pong should be remarkably similar to the original arcade Pong game. Our full implementation of Pong took a little more than 100 lines of code with comments.


SOLUTION
# Implementation of classic arcade game 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
ball_pos = [WIDTH/2,HEIGHT/2]
ball_vel = [-random.randrange(60, 180)/60,random.randrange(120, 240)/60]
paddle1_pos = HEIGHT/2
paddle2_pos = HEIGHT/2

# initialize ball_pos and ball_vel for new bal in middle of table
# if direction is RIGHT, the ball's velocity is upper right, else upper left
def spawn_ball(direction):
    global ball_pos, ball_vel # these are vectors stored as lists
    ball_pos = [WIDTH/2,HEIGHT/2]
    ball_vel[1] = -random.randrange(60, 180)/60
    if direction == "RIGHT":
        ball_vel[0] = random.randrange(120, 240)/60
    else:
        ball_vel[0] = -random.randrange(120, 240)/60

# define event handlers
def new_game():
    global paddle1_pos, paddle2_pos, paddle1_vel, paddle2_vel 
    global score1, score2
    paddle1_pos = HEIGHT/2
    paddle2_pos = HEIGHT/2
    paddle1_vel = 0
    paddle2_vel = 0
    score1 = 0
    score2 = 0
    if random.randrange(0,11) % 2 == 0:
        spawn_ball("RIGHT")
    else:
        spawn_ball("LEFT")

def draw(canvas):
    global score1, score2, paddle1_vel, paddle2_vel, paddle1_pos, paddle2_pos, ball_pos, ball_vel
    
    # draw mid line and gutters
    canvas.draw_line([WIDTH / 2, 0],[WIDTH / 2, HEIGHT], 1, "White")
    canvas.draw_line([PAD_WIDTH, 0],[PAD_WIDTH, HEIGHT], 1, "White")
    canvas.draw_line([WIDTH - PAD_WIDTH, 0],[WIDTH - PAD_WIDTH, HEIGHT], 1, "White")
    
    # draw ball
    canvas.draw_circle(ball_pos, BALL_RADIUS, 2, "Red", "White")
    
    # draw paddles
    canvas.draw_polygon([(0, paddle1_pos - HALF_PAD_HEIGHT), (0, paddle1_pos + HALF_PAD_HEIGHT), (PAD_WIDTH - 2, paddle1_pos + HALF_PAD_HEIGHT), (PAD_WIDTH - 2, paddle1_pos - HALF_PAD_HEIGHT)], PAD_WIDTH - 1, "Green", "Green")
    canvas.draw_polygon([(WIDTH, paddle2_pos - HALF_PAD_HEIGHT), (WIDTH, paddle2_pos + HALF_PAD_HEIGHT), (WIDTH - PAD_WIDTH + 2, paddle2_pos + HALF_PAD_HEIGHT), (WIDTH - PAD_WIDTH + 2, paddle2_pos - HALF_PAD_HEIGHT)], PAD_WIDTH - 1, "Magenta", "Magenta")
    
    # draw scores
    canvas.draw_text(str(score1),[150, 40], 48, "Magenta")
    canvas.draw_text(str(score2),[450, 40], 48, "Green") 
    
    # update paddle's vertical position, keep paddle on the screen
    if paddle1_pos < (HALF_PAD_HEIGHT) and paddle1_vel < 0:
        paddle1_vel = 0
    if paddle2_pos < (HALF_PAD_HEIGHT) and paddle2_vel < 0:
        paddle2_vel = 0
    if paddle1_pos > (HEIGHT - (HALF_PAD_HEIGHT)) and paddle1_vel > 0:
        paddle1_vel = 0
    if paddle2_pos > (HEIGHT - (HALF_PAD_HEIGHT)) and paddle2_vel > 0:
        paddle2_vel = 0    
    paddle1_pos += paddle1_vel
    paddle2_pos += paddle2_vel        
    
    # update ball
    ball_pos[0] += ball_vel[0]
    ball_pos[1] += ball_vel[1]
    if ball_pos[1] >= (HEIGHT - BALL_RADIUS) or ball_pos[1] <= (BALL_RADIUS):
        ball_vel[1] = -ball_vel[1]
    if ball_pos[0] <= (PAD_WIDTH + BALL_RADIUS):
        if ball_pos[1] < (paddle1_pos - HALF_PAD_HEIGHT) or ball_pos[1] > (paddle1_pos + HALF_PAD_HEIGHT):
            spawn_ball("RIGHT")
            score2 += 1
        else:
            ball_vel[0] = -ball_vel[0] * 1.1
            
    if  ball_pos[0] >= (WIDTH - PAD_WIDTH - BALL_RADIUS):
        if ball_pos[1] < (paddle2_pos - HALF_PAD_HEIGHT) or ball_pos[1] > (paddle2_pos + HALF_PAD_HEIGHT):
            spawn_ball("LEFT")
            score1 += 1
        else:
            ball_vel[0] = -ball_vel[0] * 1.1
      
def keydown(key):
    global paddle1_vel, paddle2_vel
    if key == simplegui.KEY_MAP['w']:
        paddle1_vel = -4
    if key == simplegui.KEY_MAP['s']:
        paddle1_vel = 4
    if key == simplegui.KEY_MAP['up']:
        paddle2_vel = -4
    if key == simplegui.KEY_MAP['down']:
        paddle2_vel = 4
   
def keyup(key):
    global paddle1_vel, paddle2_vel
    if key == simplegui.KEY_MAP['w'] or key == simplegui.KEY_MAP['s']:
        paddle1_vel = 0
    if key == simplegui.KEY_MAP['up'] or key == simplegui.KEY_MAP['down']:
        paddle2_vel = 0
    
# 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", new_game, 100)


# start frame
new_game()
frame.start()

The code reference (CodeSkulptor )

Mini-project # 3 - "Stopwatch: The Game"

An Introduction to Interactive Programming in Python

Mini-project description - "Stopwatch: The Game"

Mini-project development process

  1. Construct a timer with an associated interval of 0.1 seconds whose event handler increments a global integer. (Remember that create_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 B is in the range 0-5. Test this function independent of your project using this testing template http://www.codeskulptor.org/#examples-format_template.py. (Just cut and paste your definition of  format into the template.) 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 xis 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 Truewhen 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 following the tips in the Code Clinic thread. Following this process will save you time. For an example of a full implementation, we suggest that you watch the video lecture on this mini-project.


SOLUTION
# template for "Stopwatch: The Game"

# define global variables
import simplegui

watch = 0
attempt = 0
win = 0
score = "0/0"
work_timer = True

# define helper function format that converts time
# in tenths of seconds into formatted string A:BC.D
def format(t):
    A = str(t // 600)
    B = str(t // 100 % 6 )
    C = str(t % 100 / 10)
    D = str(t % 10)
    return A + ":" + B + C + "." + D
    
# define event handlers for buttons; "Start", "Stop", "Reset"
def start_handler():
    global work_timer
    timer.start()
    work_timer = True
        
def stop_handler():
    global attempt, win, score, work_timer
    timer.stop()
    if work_timer == True:
        attempt += 1
        win_template = '.0'
        if win_template in format(watch):
            win += 1
        score = str(win) + '/' + str(attempt)
    work_timer = False
        
def reset_handler():
    global watch, attempt, win, score, work_timer
    timer.stop()
    watch = 0
    attempt = 0
    win = 0
    score = str(win) + '/' + str(attempt)
    work_timer = False

# define event handler for timer with 0.1 sec interval
def timer_handler():
    global watch
    if watch < 5999:
        watch += 1
    
# define draw handler
def draw_handler(canvas):
    canvas.draw_text(format(watch), (200 // 2 - 55, 200 // 2 + 15), 48, 'Red')
    canvas.draw_text(score, (200 // 2 + 45 , 200 // 2 - 70), 24, 'Green')
    
# create frame
f = simplegui.create_frame("Stopwatch: The Game", 200, 200)
f.add_button('Start', start_handler, 100)
f.add_button('Stop', stop_handler, 100)
f.add_button('Reset', reset_handler, 100)
f.set_draw_handler(draw_handler)

# register event handlers
timer = simplegui.create_timer(100, timer_handler)

# start frame
f.start()
# Please remember to review the grading rubric

The code reference (CodeSkulptor )

Mini-project # 2— “Guess the number” game

An Introduction to Interactive Programming in Python

Mini-project description — “Guess the number” game

One of the simplest two-player games is “Guess the number”. The first player thinks of a secret number in some known range while the second player attempts to guess the number. After each guess, the first player answers either “Higher”, “Lower” or “Correct!” depending on whether the secret number is higher, lower or equal to the guess. In this project, you will build a simple interactive program in Python where the computer will take the role of the first player while you play as the second player.
You will interact with your program using an input field and several buttons. For this project, we will ignore the canvas and print the computer's responses in the console. Building an initial version of your project that prints information in the console is a development strategy that you should use in later projects as well. Focusing on getting the logic of the program correct before trying to make it display the information in some “nice” way on the canvas usually saves lots of time since debugging logic errors in graphical output can be tricky.

Mini-project development process

We have provided a basic template for this mini-project here . Our suggested development strategy for the basic version of “Guess the number” is:
  1. Decide on a set of global variables that contain the state of the game. For example, one obvious choice is the secret number that has been generated by the program. You will need other global variables, especially to accommodate later extensions to the basic game.
  2. Figure out how to generate a random secret number in a given range, low to high. When discussing ranges, we will follow the standard Python convention of including the low end of the range and excluding the high end of the range, which can be expressed mathematically as [low, high). So, [0, 3) means all of the numbers starting at 0 up to, but not including 3. In other words 0, 1, and 2. We suggest using the range [0, 100) in your first implementation. Hint: look at the functions in the random module to figure out how to easily select such a random number. We suggest testing this in a separate CodeSkulptor tab before adding code to your project.
  3. Figure out how to create an input text box using the simplegui module. You will use this input to get the guess from the user. For all variants of the game, this input field should always be active (in other words, a game should always be in progress). Again, test in a separate CodeSkulptor tab before adding code to your project.
  4. Write the event handler input_guess(guess) that takes the input guess, compares it to the secret number and prints out the appropriate response. Remember that guess is a string so you will need to convert it into a number before testing it against the secret number. Hint: We have showed you how to convert strings to numbers in the lectures.
  5. Test your code by playing multiple games of “Guess the number” with a fixed range. At this point, you will need to re-run your program between each game (using the CodeSkulptor “Run” button).  You are also welcome to use this testing template http://www.codeskulptor.org/#examples-gtn_testing_template.py. The bottom of the template contains a sequence of calls to input_guess() for three games of "Guess the number". Uncomment each sequence of calls and check whether the output in the console matches that provided in the comments below. Note that your output doesn't have to be identical, just of a similar form.
  6. Fill in your new_game() function so the generation of the secret number is now done inside this function. That is, calling new_game() should compute a random secret number and assign it to a global variable. You can now call the function new_game() in the body of your code right before you start your frame.
From this minimal working version of “Guess the number”, the rest of this project consists of adding extra functionality to your project. There are two improvements that you will need to make to get full credit:
  1. Using function(s) in the simplegui module, add buttons to restart the game so that you don't need to repeatedly click “Run” in CodeSkulptor to play multiple games. You should add two buttons: “Range: 0 - 100” and “Range: 0 - 1000” that allow the player to choose different ranges for the secret number. Using either of these buttons should restart the game and print out an appropriate message. They should work at any time during the game. In our implementation, the event handler for each button set the desired range for the secret number (as a global variable) and then call new_game to reset the secret number in the desired range.
    As you play “Guess the number”, you might notice that a good strategy is to maintain an interval that consists of the highest guess that is “Lower” than the secret number and the lowest guess that is “Higher” than the secret number. A good choice for the next guess is the number that is the average of these two numbers. The answer for this new guess then allows you to figure a new interval that contains the secret number and that is half as large. For example, if the secret number is in the range [0, 100), it is a good idea to guess50. If the answer is "Higher", the secret number must be in the range [51, 100). It is then a good idea to guess 75 and so on. This technique of successively narrowing the range corresponds to a well-known computer algorithm known as binary search.
  2. Your final addition to “Guess the number” will be to restrict the player to a limited number of guesses. After each guess, your program should include in its output the number of remaining guesses. Once the player has used up those guesses, they lose, the game prints out an appropriate message, and a new game immediately starts.
    Since the strategy above for playing “Guess the number” approximately halves the range of possible secret numbers after each guess, any secret number in the range [low, high)can always be found in at most n guesses where n is the smallest integer such that 2 ** n >= high - low + 1. For the range [0, 100), n is seven. For the range [0, 1000),n is ten. In our implementation, the function new_game() set the number of allowed guess to seven when the range is [0, 100) or to ten when the range is [0, 1000). For more of a challenge, you may compute n from low and high using the functions math.log and math.ceil in the math module.
When your program starts, the game should immediately begin in range [0, 100). When the game ends (because the player either wins or runs out of guesses), a new game with the same range as the last one should immediately begin by calling new_game(). Whenever the player clicks one of the range buttons, the current game should stop and a new game with the selected range should begin.


SOLUTION
# template for "Guess the number" mini-project
# input will come from buttons and an input field
# all output for the game will be printed in the console

import simplegui
import random
import math

# initialize global variables used in your code
num_range = 100

# helper function to start and restart the game
def new_game():
    """ Define global variables, generate secret_number, calculate number of attempts """
    global count, secret_number
    secret_number = random.randrange(num_range)
    print "New game. Range is from 0 to %s." % num_range
    count = int(math.ceil(math.log(num_range + 1)/math.log(2)))
    print "Number of remaining guesses is %s." % count

# define event handlers for control panel
def range100():
    # button that changes range to range [0,100) and restarts
    global num_range
    num_range = 100
    print
    new_game()
    
def range1000():
    # button that changes range to range [0,1000) and restarts
    global num_range
    num_range = 1000
    print
    new_game()
    
def input_guess(guess):
    # main game logic goes here 
    global count, secret_number
    guess = int(guess)
    count -= 1
    print
    print "Guess was %s." % guess
    print "Number of remaining guesses is %s." % count
    if count > 0 and guess < secret_number: 
            print "Higher!"
    elif count > 0 and guess > secret_number: 
            print "Lower!"
    elif count >= 0 and guess == secret_number: 
        print "Correct! \n"
        new_game()
    else:
        print "You ran out of guess. The number was %s.\n" % secret_number
        new_game()
    
# create frame
frame = simplegui.create_frame("Guess the number", 200, 200)

# register event handlers for control elements
frame.add_button("Range: 0 - 100", range100, 150)
frame.add_button("Range: 0 - 1000", range1000, 150)
frame.add_input("Enter a guess", input_guess, 150) 

# call new_game and start frame
new_game()
frame.start()

# always remember to check your completed program against the grading rubric

The code reference (CodeSkulptor )

Mini-project # 1— Rock-paper-scissors-lizard-Spock

An Introduction to Interactive Programming in Python

Mini-project description — Rock-paper-scissors-lizard-Spock

Mini-project development process

  1. Build a helper function name_to_number(name) that converts the string name into a number between 0 and 4 as described above. This function should use a sequence ofif/elif/else clauses. You can use conditions of the form name == 'paper', etc. to distinguish the cases. To make debugging your code easier, we suggest including a finalelse clause that catches cases when name does not match any of the five correct input strings and prints an appropriate error message. You can test your implementation ofname_to_number() using this name_to_number testing template. (Also available in the Code Clinic tips thread).
  2. Next, you should build a second helper function number_to_name(number) that converts a number in the range 0 to 4 into its corresponding name as a string. Again, we suggest including a final else clause that catches cases when number is not in the correct range. You can test your implementation of number_to_name() using this number_to_name testing template.
  3. Implement the first part of the main function rpsls(player_choice). Print out a blank line (to separate consecutive games) followed by a line with an appropriate message describing the player's choice. Then compute the number player_number between 0 and 4 corresponding to the player's choice by calling the helper function name_to_number() usingplayer_choice.
  4. Implement the second part of rpsls() that generates the computer's guess and prints out an appropriate message for that guess. In particular, compute a random numbercomp_number between 0 and 4 that corresponds to the computer's guess using the function random.randrange(). We suggest experimenting with randrange in a separate CodeSkulptor window before deciding on how to call it to make sure that you do not accidently generate numbers in the wrong range. Then compute the name comp_namecorresponding to the computer's number using the function number_to_name() and print an appropriate message with the computer's choice to the console.
  5. Implement the last part of rpsls() that determines and prints out the winner. Specifically, compute the difference between comp_number and player_number taken modulo five. Then write an if/elif/else statement whose conditions test the various possible values of this difference and then prints an appropriate message concerning the winner. If you have trouble deriving the conditions for the clauses of this if/elif/else statement, we suggest reviewing the "RPSLS" video which describes a simple test for determine the winner of RPSLS.
This will be the only mini-project in the class that is not an interactive game. Since we have not yet learned enough to allow you to play the game interactively, you will simply call yourrpsls function repeatedly in the program with different player choices. You will see that we have provided five such calls at the bottom of the template. Running your program repeatedly should generate different computer guesses and different winners each time. While you are testing, feel free to modify those calls, but make sure they are restored when you hand in your mini-project, as your peer assessors will expect them to be there.
The output of running your program should have the following form:
Player chooses rock
Computer chooses scissors
Player wins!

Player chooses Spock
Computer chooses lizard
Computer wins!

Player chooses paper
Computer chooses lizard
Computer wins!

Player chooses lizard
Computer chooses scissors
Computer wins!

Player chooses scissors
Computer chooses Spock
Computer wins!
Note that, for this initial mini-project, we will focus only on testing whether your implementation of rpsls() works correctly on valid input.


SOLUTION
# Rock-paper-scissors-lizard-Spock template

# The key idea of this program is to equate the strings
# "rock", "paper", "scissors", "lizard", "Spock" to numbers
# as follows:
#
# 0 - rock
# 1 - Spock
# 2 - paper
# 3 - lizard
# 4 - scissors

import random
def name_to_number(name):
    """ Convert name to number """
    if name == "rock":
        number = 0
    elif name == "Spock":
        number = 1
    elif name == "paper":
        number = 2
    elif name == "lizard":
        number = 3
    elif name == "scissors":
        number = 4
    return number

def number_to_name(number):
    """ Convert number to a name """
    if number == 0:
        name = "rock"
    elif number == 1:
        name = "Spock"
    elif number == 2:
        name = "paper"
    elif number == 3:
        name = "lizard"
    elif number == 4:
        name = "scissors"
    return name
    
def rpsls(player_choice): 
    # print a blank line to separate consecutive games
    print
    
    # print out the message for the player's choice
    print "Player chooses " + player_choice

    # convert the player's choice to player_number using the function name_to_number()
    player_number = name_to_number(player_choice)

    # compute random guess for comp_number using random.randrange()
    comp_number = random.randrange(0, 5)

    # convert comp_number to comp_choice using the function number_to_name()
    comp_choice = number_to_name(comp_number)
    
    # print out the message for computer's choice
    print "Computer chooses " + comp_choice
    
    # compute difference of comp_number and player_number modulo five
    result = (comp_number - player_number) % 5
    
    # determine winner, print winner message
    if result == 1 or result == 2:
        print "Computer wins!"
    elif result == 3 or result == 4:
        print "Player wins!"
    else:
        print "Player and computer tie!"
    
# test your code - LEAVE THESE CALLS IN YOUR SUBMITTED CODE
rpsls("rock")
rpsls("Spock")
rpsls("paper")
rpsls("lizard")
rpsls("scissors")

The code reference (CodeSkulptor )