Lab Dates: Wednesday-Thursday, 24-25 April 2013
Today's lab looks at nested loops and indefinite loops from Chapter 8.
Today, we are going to write a simple game where the user tries to find our mystery point in the graphics window. Lets first go through the program section by section:
# Mystery point game for Lab 9 # Lehman College, CUNY, Fall 2012 from graphics import * from math import * from random import *
# Reuse the distance function we wrote for Lab 8: def dist(p1,p2): dist = sqrt((p1.getX()-p2.getX())**2 + (p1.getY() - p2.getY())**2) return dist
def main(): w = GraphWin("Target Practice",500,500) w.setCoords(-250,-250,250,250)
#Generate a mystery point (at a random location): x = randrange(-200,200) y = randrange(-200,200) print("x and y are:",x,y) mysteryPoint = Point(x,y)
#Text to tell the user what's happening: t = Text(Point(0,-210), "Click on the mystery point") t.setSize(16) t.draw(w)
#Get the point: p = w.getMouse() p.draw(w) d = dist(mysteryPoint, p) print("distance from mystery point is:", d)
#Keep going until they click close to the point: while d > 20: t.setText("Missed! Please click again!") p = w.getMouse() p.draw(w) d = dist(mysteryPoint, p) print("distance from mystery point is:", d)
t.setText("Congratulations! You found the mystery point!") #keep the window up until the user clicks w.getMouse() w.close() main()
Try running the program. How easy is it to win?
Could you find the point without peeking at the IDLE shell? To make the game a bit easier, we will add hints. The first hint will be to tell the user if they need to click more to the left (or right) to find the point. Here is the pseudocode:
if point clicked is to the left of mystery point give message "Too far left" else give message "Too far right"
How can you tell if the point clicked is to the left of the mystery point? The x-coordinate tells how far left or right a point is, so, we compare the x-coordinates of the two points:
if p.getX() < mysteryPoint.getX(): t.setText("Click again! You were too far left") else: t.setText("Click again! You were too far right")
Now, add in the code that will give a hint to move up (or down) depending on where they clicked with respect to the mystery point. Your completed program should have a "left/right" hint and an "low/high" hint to make the game possible to do without looking at our diagonostics on the python shell.
Hint: Before the loop, set up another Text object, t2 to display the message about being too low or too high:
t2 = Text(Point(0,-230), "") t2.setSize(16) t2.draw(w)
After completing your program, go to Labs in Blackboard and click on the link: Lab 9 and answer the questions (if you do not get the answers right the first time, try again until you do).