Showing posts with label Interactive Python. Show all posts
Showing posts with label Interactive Python. Show all posts

Wednesday, July 23, 2014

Fun with Python : Interactive Python - "Stopwatch: The Game"

Mini-project description - "Stopwatch: The Game"

Let's 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.

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 represent 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. 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

Answer: Access my code here 

Tuesday, June 3, 2014

Fun with Python : Interactive Python - “Guess The Number” Game

“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
A basic template for this mini-project here (http://www.codeskulptor.org/#examples-guess_the_number_template.py). 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).
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 guess 50. 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.
Grading — 11 pts total
Here is a break down of the scoring:
1 pt — The game starts immediately when the “Run” button in CodeSkulptor is pressed.
1 pt — A game is always in progress. Finishing one game immediately starts another in the same range.
1 pt — The game reads guess from the input field and correctly prints it out.
3 pts — The game correctly plays “Guess the number” with the range [0, 100) and prints understandable output messages to the console. Play three complete games: 1 pt for each correct game.
2 pts — The game includes two buttons that allow the user to select the range [0, 100) or the range [0, 1000) for the secret number. These buttons correctly change the range and print an appropriate message. (1 pt per button.)
2 pts — The game restricts the player to a finite number of guesses and correctly terminates the game when these guesses are exhausted. Award 1 pt if the number of remaining guesses is printed, but the game does not terminate correctly.
1 pt — The game varies the number of allowed guesses based on the range of the secret number — seven guesses for range [0, 100), ten guesses for range [0, 1000).
To help aid you in gauging what a full credit project might look like, the video lecture on the “Guess the number” project includes a demonstration of our implementation of this project. You do not need to validate that the input number is in the correct range. (For this game, that responsibility should fall on the player.)

Answer :  Access my code here

Sunday, May 18, 2014

Fun with Python: Rock-Paper-Scissors-Lizard-Spock


Rock-paper-scissors is a hand game that is played by two people. The players count to three in unison and simultaneously 'throw' one of three hand signals that correspond to rock, paper or scissors. The winner is determined by the rules:
·         Rock smashes scissors
·         Scissors cuts paper
·         Paper covers rock
Rock-paper-scissors is a surprisingly popular game that many people play seriously (see the Wikipedia article for details). Due to the fact that a tie happens around 1/3 of the time, several variants of Rock-Paper-Scissors exist that include more choices to make ties more unlikely.
Rock-paper-scissors-lizard-Spock (RPSLS) is a variant of Rock-paper-scissors that allows five choices. Each choice wins against two other choices, loses against two other choices and ties against itself. Much of RPSLS's popularity is that it has been featured in 3 episodes of the TV series "The Big Bang Theory". The Wikipedia entry for RPSLS gives the complete description of the details of the game.
In our first mini-project, we will build a Python function rpsls(name) that takes as input the string name, which is one of "rock","paper""scissors""lizard", or "Spock". The function then simulates playing a round of Rock-paper-scissors-lizard-Spock by generating its own random choice from these alternatives and then determining the winner using a simple rule that we will next describe.
While Rock-paper-scissor-lizard-Spock has a set of ten rules that logically determine who wins a round of RPSLS, coding up these rules would require a large number (5x5=25) of if/elif/else clauses in your mini-project code. A simpler method for determining the winner is to assign each of the five choices a number:
·         0 — rock
·         1 — Spock
·         2 — paper
·         3 — lizard
·         4 — scissors
In this expanded list, each choice wins against the preceding two choices and loses against the following two choices.
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 of if/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 final else clause that catches cases whenname does not match any of the five correct input strings and prints an appropriate error message.
2.    Next, you should build a second helper function number_to_name(num) 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.
3. Build the first part of the main function rpsls(name) that converts name into the number player_number between 0 and 4 using the helper function name_to_number.
4.    Build the second part of rpsls(name) that generates a random number comp_number between 0 and 4 using the functionrandom.randrange(). I 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.
5.    Build the last part of rpsls(name) that determines and prints out the winner. This test is actually very simple if you use the remainder operation (% in Python) to the difference between comp_number and player_number. If this is not immediately obvious to you, I would suggest reviewing the "More operations"  and "RPSLS" videos on remainders and modular arithmetic as well as experimenting with the remainder operator % in a separate CodeSkulptor window to understand its behavior.
6.    Using the helper function number_to_name, you should produce four print statements; print a blank line, print out the player's choice, print out the computer's choice and print out the winner.

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 your rpsls 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!