Giter VIP home page Giter VIP logo

interactive-python's Introduction

An Introduction to Interactive Programming in Python

Our main focus will be on building simple interactive games such as Pong, Blackjack and Asteroids.

Space ship Game

For this mini-project, we will implement a working spaceship plus add a single asteroid and a single missile. We have provided art for our game so its look and feel is that of a more modern game. We should begin by loading the program template.The program template includes all necessary image and audio files. Unfortunately, no audio format is supported by all major browsers so we have decided to provided sounds in the mp3 format which is supported by Chrome (but not by Firefox on some systems). (ogg versions are also available.) We highly recommend using Chrome for the last two weeks of the class. We have found that Chrome typically has better performance on games with more substantial drawing requirements and standardization on a common browser will make peer assessing projects more reliable. Phase one - Spaceship

In this phase, we will implement the control scheme for the spaceship.This includes a complete Spaceship class and the appropriate keyboard handlers to control the spaceship. our spaceship should behave as follows:

The left and right arrows should control the orientation of our spaceship. While the left arrow is held down, our spaceship should turn counter-clockwise. While the right arrow is down, our spaceship should turn clockwise. When neither key is down, our ship should maintain its orientation. We will need to pick some reasonable angular velocity at which our ship should turn. The up arrow should control the thrusters of our spaceship. The thrusters should be on when the up arrow is down and off when it is up. When the thrusters are on, ou should draw the ship with thrust flames. When the thrusters are off, we should draw the ship without thrust flames. When thrusting, the ship should accelerate in the direction of its forward vector. This vector can be computed from the orientation/angle of the ship using the provided helper function angle_to_vector. We will need to experiment with scaling each component of this acceleration vector to generate a reasonable acceleration. Remember that while the ship accelerates in its forward direction, but the ship always moves in the direction of its velocity vector. Being able to accelerate in a direction different than the direction that we are moving is a hallmark of Asteroids. Our ship should always experience some amount of friction. (Yeah, we know, "Why is there friction in the vacuum of space?". Just trust us there is in this game.) This choice means that the velocity should always be multiplied by a constant factor less than one to slow the ship down. It will then come to a stop eventually after we stop the thrusters. Now, implement these behaviors above in order. Each step should require just a few lines of code. Here are some hints: Modify the draw method for the Ship class to draw the ship image (without thrust flames) instead of a circle. This method should incorporate the ship's position and angle. Note that the angle should be in radians, not degrees. Since a call to the ship's draw method already exists in the draw handler, we should now see the ship image. Experiment with different positions and angles for the ship. Implement an initial version of the update method for the ship. This version should update the position of the ship based on its velocity. Since a call to the update method also already exists in the draw handler, the ship should move in response to different initial velocities. Modify the update method for the ship to increment its angle by its angular velocity. Make our ship turn in response to the left/right arrow keys. Add keydown and keyup handlers that check the left and right arrow keys. Add methods to the Ship class to increment and decrement the angular velocity by a fixed amount. (There is some flexibility in how we structure these methods.) Call these methods in the keyboard handlers appropriately and verify that we can turn our ship as we expect. Modify the keyboard handlers to turn the ship's thrusters on/off. Add a method to the Ship class to turn the thrusters on/off (we can make it take a Boolean argument which is True or False to decide if they should be on or off). Modify the ship's draw method to draw the thrust image when it is on. (The ship image is tiled and contains both images of the ship.) Modify the ship's thrust method to play the thrust sound when the thrust is on. Rewind the sound when the thrust turns off. Add code to the ship's update method to use the given helper function angle_to_vector to compute the forward vector pointing in the direction the ship is facing based on the ship's angle. Next, add code to the ship's update method to accelerate the ship in the direction of this forward vector when the ship is thrusting. we will need to update the velocity vector by a small fraction of the forward acceleration vector so that the ship does not accelerate too fast. Then, modify the ship's update method such that the ship's position wraps around the screen when it goes off the edge (use modular arithmetic!). Up to this point, our ship will never slow down. Finally, add friction to the ship's update method as shown in the "Acceleration and Friction" video by multiplying each component of the velocity by a number slightly less than 1 during each update. we should now have a ship that flies around the screen,as we would like for RiceRocks. Adjust the constants as we would like to get it to fly how we want. Phase two - Rocks

To implement rocks, we will use the provided Sprite class. Note that the update method for the sprite will be very similar to the update method for the ship. The primary difference is that the ship's velocity and rotation are controlled by keys, whereas sprites have these set randomly when they are created. Rocks should screen wrap in the same manner as the ship.

In the template, the global variable a_rock is created at the start with zero velocity. Instead, we want to create version of a_rock once every second in the timer handler. Next week, we will add multiple rocks. This week, the ship will not die if it hits a rock. We'll add that next week. To implement rocks, we suggest the following:

Complete the Sprite class (as shown in the "Sprite class" video) by modifying the draw handler to draw the actual image and the update handler to make the sprite move and rotate. Rocks do not accelerate or experience friction, so the sprite update method should be simpler than the ship update method. Test this by giving a_rock different starting parameters and ensuring it behaves as we expect. Implement the timer handler rock_spawner. In particular, set a_rock to be a new rock on every tick. (Don't forget to declare a_rock as a global in the timer handler.) Choose a velocity, position, and angular velocity randomly for the rock. You will want to tweak the ranges of these random numbers, as that will affect how fun the game is to play. Make sure you generated rocks that spin in both directions and, likewise, move in all directions. Phase three - Missiles To implement missiles, we will use the same sprite class as for rocks. Missiles will always have a zero angular velocity. They will also have a lifespan (they should disappear after a certain amount of time or you will eventually have missiles all over the place), but we will ignore that this week. Also, for now, we will only allow a single missile and it will not yet blow up rocks. We'll add more next week.

Our missile should be created when you press the spacebar, not on a timer like rocks. They should screen wrap just as the ship and rocks do. Otherwise, the process is very similar:

Add a shoot method to our ship class. This should spawn a new missile (for now just replace the old missile in a_missile). The missile's initial position should be the tip of our ship's "cannon". Its velocity should be the sum of the ship's velocity and a multiple of the ship's forward vector. Modify the keydown handler to call this shoot method when the spacebar is pressed. Make sure that the missile sound is passed to the sprite initializer so that the shooting sound is played whenever you shoot a missile. Phase four - User interface Our user interface for RiceRocks simply shows the number of lives remaining and the score. This week neither of those elements ever change, but they will next week. Add code to the draw event handler to draw these on the canvas. Use the lives and score global variables as the current lives remaining and score.

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 below. Remember to run your program after each step to ensure that you implemented that step correctly. Add code to the program template that creates a frame with an input field whose handler has the name input_guess. You will use this input field to enter guesses. Add code to the event handler input_guess(guess) that takes the input string guess, converts it to an integer, and prints out a message of the form "Guess was 37" (or whatever the guess actually was). Hint: We have shown you how to convert strings to numbers in the lectures. Add code to the function new_game that initializes a global variable secret_number to be a random number in the range [0, 100). Remember to include a global statement. Hint: look at the functions in the random module to figure out how to easily select such a random number. Note that the call to new_game() at the bottom of the template ensures that secret_number is always initialized when the program starts running. 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. Add code to input_guess that compares the entered number to secret_number and prints out an appropriate message such as "Higher", "Lower", or "Correct". 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. 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: 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. 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.

Stopwatch

An application to start and stop a time on user interaction.

interactive-python's People

Contributors

fatemasaifee avatar

Watchers

James Cloos avatar  avatar

Forkers

abdullah008101

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.