Learn how to make a simple game with Python! This is a post by Tutorial Team Member, a 13-year-old python developer.
You can find him on and. Have you ever wondered how video games are created? It’s not as complicated as you might think! In this tutorial, you’ll create a simple game called Bunnies and Badgers, where the hero, the bunny, has to defend a castle against an attacking horde of badgers.:O To write this game, you’ll use Python.
No, I’m not talking about a big snake!: Python is a computer programming language. We chose Python for this tutorial because it’s a simple language to start out with, and is fun and easy to learn. If you are new to Python, before you begin check out this book:. That should get you up to speed. Then dive back here and get ready – there’s a war coming on between the bunnies and the badgers. Keep reading to jump into the fray! Getting Started: Installing Python If you want to try this tutorial on a Windows PC, you need to install.
Make sure you grab the 2.7.3 version and NOT the 3.3.0 version! After running the installer, you should have IDLE in your All Programs folder in your start menu. Launch IDLE to get started. If you are on a Mac, you already have Python installed!
Just open Terminal (/Applications/Utilities/Terminal.app), type in python and press Enter. Note: If you want to exit the Python prompt (the triple angle brackets, ), you can either type exit at the Python prompt and press Return or you can press Control+D. Once you are at the Python prompt, to test if Python is correctly working, type in print 1+1 and hit Enter/Return. It should print 2. You have just written your first Python program!
Now that you know Python is working correctly, you need to install PyGame in order to write a game using Python. PyGame is a Python library that makes writing games a lot easier! It provides functionality such as image handling and sound playback that you can easily incorporate into your game. Go and download the PyGame installer appropriate for your system. Make sure you download a Python 2.7 version.
Note: The PyGame installer from the link above will not work with the default Python from Apple that is installed on a Mac. You’ll need to download Python from python.org and install it in order to use PyGame. Or, you can install both Python and PyGame via. To verify that you have PyGame installed properly, open IDLE or run Python via the Terminal and type in import pygame at the Python prompt.
If this doesn’t result in any output, then you’re good. If, on the other hand, it outputs an error like what’s shown below, then PyGame is not installed. Python 2.7.2 (default, Jun 20 2012, 16:23:33) GCC 4.2.1 Compatible Apple Clang 4.0 (tags/Apple/clang-418.0.60) on darwin Type 'help', 'copyright', 'credits' or 'license' for more information.
import pygame Traceback (most recent call last): File ', line 1, in ImportError: No module named pygame If you get an error like this, post on the forums and I will help you get it working. Running Python Code from File While you can run short bits of Python code at the Python prompt, if you want to work on a bigger program (like a game), you probably want to save your code to a file so that you don’t have to type it in over and over again. There are several ways to run a Python program as a file. One way is to use a plain text editor like Notepad (Windows), or TextEdit (Mac).
Open a new text file, type in your Python code (like print 1+1). Then save it as XXX.py (The XXX can be any descriptive file name). Then on Windows, double-click this file to run it. On Mac, open Terminal and type python, then drag the file that you saved onto the Terminal window and press Enter. The other way is to type in your code using the IDLE editor, which is what you’re going to do in this tutorial. To run idle, simply type idle from Terminal. Then choose File New Window from the IDLE menu and you should have a text editor window where you can type in Python code.
You can save your code changes via File Save and even run the code via Run Run Module (F5). Do note that the Run menu is only available if you have a file open in an editor window. Adding the Game Resources You are almost ready to create your game. But what’s a game without some great graphics and sound effects? I’ve put together all the graphics and sound effects you’ll need for your game into a ZIP archive.
You can download it. Once you’ve downloaded the file, create a folder for your game on your hard disk and extract the resources folder into that folder so that your game folder has a subfolder named resources, with the various resources grouped in additional folders inside it, like this: You are now ready to begin creating Bunnies and Badgers.: Step 1: Hello Bunny Run IDLE and open a new text editor window, as mentioned in the previous section.
Note: Where other languages like Objective-C, Java or PHP use curly braces to show a block of code to be executed within a while loop or an if statement, Python uses indenting to identify code blocks. So proper indentation is very important in Python – keep that in mind.:. Fill the screen with black before you draw anything. Add the bunny image that you loaded to the screen at x=100 and y=100. Update the screen.
Check for any new events and if there is one, and it is a quit command, exit the program. Note: According to the, you shouldn’t need to call pygame.quit since the interpreter will automatically call it when the interpreter shuts down.
However, at least on Mac OS, the game would hang on exit unless pygame.quit was called. If you run the code now (via Run Run Module in the Idle menu), you should see a screen similar to the one below: w00t the bunny is in the scene, and ready for action! But the game looks scary and lonely with the bunny just standing there on a black background. Time to prettify things a little bit.: Step 2: Add Scenery Let’s start by adding a background to the game scene. This can be done with a couple more screen.blit calls. At the end of section #3, after loading the player image, add the following code: grass = pygame.image.load('resources/images/grass.png') castle = pygame.image.load('resources/images/castle.png') This loads the images and puts them into specific variables. Now they have to be drawn on screen.
But if you check the grass image, you will notice that it won’t cover the entire screen area, which is 640 x 480. This means you have to tile the grass over the screen area to cover it completely. Add the following code to game.py at the beginning of section #6 (before the player is drawn on screen): for x in range(width/grass.getwidth+1): for y in range(height/grass.getheight+1): screen.blit(grass,(x.100,y.100)) screen.blit(castle,(0,30)) screen.blit(castle,(0,135)) screen.blit(castle,(0,240)) screen.blit(castle,(0,345 )) As you can see, the for statement loops through x first. Then, within that for loop, it loops through y and draws the grass at the x and y values generated by the for loops. The next couple of lines just draw the castles on the screen. If you run the program now, you should get something like this: Much better – this is starting to look good!: Step 3: Make the Bunny Move Next you need to add some actual gameplay elements, like making the bunny respond to key presses. To do that, first you’ll implement a good method of keeping track of which keys are being pressed at a given moment.
You can do this simply by making an array of key states that holds the state of each key you want to use for the game. Add the following code to game.py at the end of section #2 (after you set the screen height and width): keys = False, False, False, False playerpos=100,100 This code is pretty self-explanatory.
The keys array keeps track of the keys being pressed in the following order: WASD. Each item in the array corresponds to one key – the first to W, the second to A and so on. The playerpos variable is where the program draws the player. Since the game will move the player to different positions, it’s easier to have a variable that contains the player position and then simply draw the player at that position. Now you need to modify the existing code for drawing the player to use the new playerpos variable.
Change the following line in section #6: screen.blit(player, (100,100)) To: screen.blit(player, playerpos) Next, update the keys array based on which keys are being pressed. PyGame makes detecting key presses easy by adding event.key functions. At the end of section #8, right after the block checking for event.typepygame.QUIT, put this code (at the same indentation level as the pygame.QUIT if block): if event.type pygame.KEYDOWN: if event.keyKw: keys0=True elif event.keyKa: keys1=True elif event.keyKs: keys2=True elif event.keyKd: keys3=True if event.type pygame.KEYUP: if event.keypygame.Kw: keys0=False elif event.keypygame.Ka: keys1=False elif event.keypygame.Ks: keys2=False elif event.keypygame.Kd: keys3=False Wow! Those are a lot of lines of code.
If you break it down into the if statements though, it’s not that complicated. First you check to see if a key is being pressed down or released. Then you check which key is being pressed or released, and if the key being pressed or released is one of the keys you’re using, you update the keys variable accordingly. Finally, you need to update the playerpos variable in response to the key presses.
This is actually very simple. Add the following code to the end of game.py (with one indentation level, putting it at the same level as the for loop): # 9 - Move player if keys0: playerpos1-=5 elif keys2: playerpos1+=5 if keys1: playerpos0-=5 elif keys3: playerpos0+=5 This code simply checks which of the keys are being pressed and adds or subtracts from the player’s x or y position (depending on the key pressed) to move the player.
Run the game and you should get a player just like before. Try pressing WASD. Step 4: Turning the Bunny Yes, your bunny now moves when you press keys but wouldn’t it be even cooler if you could use your mouse to rotate the bunny to face a direction of your choosing, so he’s not facing the same way all the time? It’s simple enough to implement using trigonometry.
Take a look at the following illustration: In the above image, if (5,3) is the position of the bunny and (2,4) is the current position of the mouse, you can find the rotation angle (z) by applying the atan2 trigonometric function to the difference in distances between the two points. Of course, once you know the rotation angle, you can simply rotate the bunny accordingly.: If you’re a bit confused about this part, don’t worry – you can continue on anyway.
But this is why you should pay attention in Math class!: You’ll use this stuff all the time in game programming. Now you need to apply this concept to your game. To do this, you can use the PyGame Surface.rotate(degrees) function. Incidentally, keep in mind that the Z value is in radians.: The atan2 function comes from the Python math library. So add this to the end of section #1 first: import math Then, replace the last line in section #6 (the player.blit line) with the following code: # 6.1 - Set player position and rotation position = pygame.mouse.getpos angle = math.atan2(position1-(playerpos1+32),position0-(playerpos0+26)) playerrot = pygame.transform.rotate(player, 360-angle.57.29) playerpos1 = (playerpos0-playerrot.getrect.width/2, playerpos1-playerrot.getrect.height/2) screen.blit(playerrot, playerpos1) Let’s go through the basic structure of the above code. First you get the mouse and player positions. Then you feed those into the atan2 function.
After that, you convert the angle received from the atan2 function from radians to degrees (multiply radians by approximately 57.29 or 360/2π). Since the bunny will be rotated, its position will change. So now you calculate the new bunny position and display the bunny on screen.
Run the game again. If you use just the WASD keys, then the game should behave exactly like before. But if you move your mouse, the bunny rotates too. Step 5: Shoot, Bunny, Shoot! Now that your bunny’s moving around, it’s time to add a little more action.: How about letting the bunny shoot enemies using arrows?
This is no mild-mannered rabbit! This step is a bit more complicated because you have to keep track of all the arrows, update them, rotate them, and delete them when they go off-screen. First of all, add the necessary variables to the end of the initialization section, section #2: acc=0,0 arrows= The first variable keeps track of the player’s accuracy and the second array tracks all the arrows. The accuracy variable is essentially a list of the number of shots fired and the number of badgers hit. Later, we will be using this information to calculate an accuracy percentage. Next, load the arrow image at the end of section #3: arrow = pygame.image.load('resources/images/bullet.png') Now when a user clicks the mouse, an arrow needs to fire. Add the following to the end of section #8 as a new event handler: if event.typepygame.MOUSEBUTTONDOWN: position=pygame.mouse.getpos acc1+=1 arrows.append(math.atan2(position1-(playerpos11+32),position0-(playerpos10+26)),playerpos10+32,playerpos11+32) This code checks if the mouse was clicked and if it was, it gets the mouse position and calculates the arrow rotation based on the rotated player position and the cursor position.
This rotation value is stored in the arrows array. Next, you have to actually draw the arrows on screen. Add the following code right after section #6.1: # 6.2 - Draw arrows for bullet in arrows: index=0 velx=math.cos(bullet0).10 vely=math.sin(bullet0).10 bullet1+=velx bullet2+=vely if bullet1640 or bullet2480: arrows.pop(index) index+=1 for projectile in arrows: arrow1 = pygame.transform.rotate(arrow, 360-projectile0.57.29) screen.blit(arrow1, (projectile1, projectile2)) The vely and velx values are calculated using basic trigonometry. 10 is the speed of the arrows. The if statement just checks if the bullet is out of bounds and if it is, it deletes the arrow.
The second for statement loops through the arrows and draws them with the correct rotation. Try and run the program. You should have a bunny that shoots arrows when you click the mouse!:D Step 6: Take Up Arms! OK, you have a castle and you have a hero who can move and shoot.
So what’s missing? Enemies who attack the castle that the hero can shoot!
In this step, you’ll create randomly generated badgers that run at the castle. There will be more and more badgers as the game progresses. So, let’s make a list of what you’ll need it to do.
Add bad guys to a list an array. Update the bad guy array each frame and check if they are off screen. Show the bad guys. Easy, right?: First, add the following code to the end of section #2: badtimer=100 badtimer1=0 badguys=640,100 healthvalue=194 The above sets up a timer (as well as a few other values) so that the game adds a new badger after some time has elapsed. You decrease the badtimer every frame until it is zero and then you spawn a new badger. Now add the following to the end of section #3: badguyimg1 = pygame.image.load('resources/images/badguy.png') badguyimg=badguyimg1 The first line above is similar to all the previous image-loading code.
The second line sets up a copy of the image so that you can animate the bad guy much more easily. Next, you have to update and show the bad guys. Add this code right after section #6.2: # 6.3 - Draw badgers if badtimer0: badguys.append(640, random.randint(50,430)) badtimer=100-(badtimer1.2) if badtimer1=35: badtimer1=35 else: badtimer1+=5 index=0 for badguy in badguys: if badguy0. Note: The acc0.1.0 is just converting acc0 to a float.
If you do not do this, the division operand will return an integer like 1 or 2 instead of a float like 1.5 Add these lines to the end of game.py: #10 - Win/Lose check if pygame.time.getticks=90000: running=0 exitcode=1 if healthvalue.
Code Examples Overview This page contains all Python scripts that we have posted so far on You can find more Python code examples at the bottom of this page. Python code examples Here we link to other sites that provides Python code examples. Recommended Python Training – For, our top recommendation is DataCamp. Provides online interactive courses that combine interactive coding challenges with videos from top instructors in the field.
Datacamp has beginner to advanced Python training that programmers of all levels benefit from.
I have looked at the other posts about this topic but still can not find what I'm doing wrong at the beginning. Instead of rock, paper, and scissors, I am using python, ruby, and java. It is not close to being done yet. I'm not into the if loops yet for, but if the user inputs something different then 'python', 'ruby', or Java', I want it too print 'The game is over'. I get an error saying the string i entered is not defined. Could someone guide me in the direction I need to go?
I think I'm confused when comparing userInput to gameList, since gameList is a list. Import random def pythonRubyJava: gameList = 'python','ruby','java' userInput = input('python, ruby, or java?:') randomInput = random.choice(gameList) if userInput!= gameList: print 'The game is over' I got that part figured out.
Do I need to store 'python', 'ruby', and 'java' as variables to continue now? Or where would you go? Import random def pythonRubyJava: gameList = 'python','ruby','java' userInput = rawinput('python, ruby, or java?:') randomInput = random.choice(gameList) print randomInput if userInput not in gameList: print 'The game is over' if userInput 'python' and randomInput 'python': print 'stalemate' if userInput 'ruby' and randomInput 'ruby': print 'stalemate' if userInput 'java' and randomInput 'java': print 'stalemate' Instead of getting the same answer, I want to be able to run the game again and not have it print the stalemate to end the game, just start over. I know I would have to delete 'print 'stalemate' but I just wanted to show that. Actually, the answer is a combination of both versions of the answers I have seen so far.
First, input does not return a string, it returns the literal characters entered, so when you enter 'python', it is looking for the variable python which does not exist. You would need to surround the input with quotes in order for it to work, but there is a better way. Use rawinput which takes the input as a string value.
Also, once you've fixed that, you will come to an error on line 6. In line six, you are comparing the answer to the entire list, but it needs to be compared to each item in the list. Easily solved with: if userInput not in gameList: #execute.
There are many example programs available for download at: Here is a brief description of what is available:. Program that calculates miles-per-gallon. Calculates the kinetic energy of an object. Simple example if statements. Simple example for loops. Simple example while loops.
(. Simple example for encrypting text. Simple example for decrypting text. Binary and linear searches.
Property check examples. This opens up a blank pygame window.
It is a good template to use when starting a new program. This file demonstrates setting up a window and drawing rectangles, polygons, text, and other basic shapes. See how to rotate text. Demos all the commands in the draw module.
Animate a bouncing rectangle around the screen. Animate a several bouncing balls. This shows how to use an array to animate and track multiple objects. In this case, snow flakes. This file draws a snowman inside of a function. The program can then call the draw snowman function and draw several snowmen easily.
Move an object with the mouse. Move an object with the keyboard. Move an object with the game controller. Show how to read everything off a gamepad/controller/joystick.
Port Scanner In Python
Display bitmapped images (png, jpg) to a screen. Display a board based on a two-dimensional grid.
Useful when creating games like tic-tac-toe, minesweeper, memory-match, connect-four, etc. Display one or more pages of instruction before the game starts. Plays background music. When the music is over, an event is triggered and a different song starts.
The music is included in the downloadable zip file, or you can follow the links in the comments to download the music. Shows how to display a centered 'Game Over' message, and stop game play when a game is over.
Display a line sweeping around in a circle like a radar. Count up and count down timers. Using recursion to make nested rectangles.
Using recursion to make fractals. Put a timer on the screen. Move a sprite with the mouse and collect blocks. Same as collect blocks example, but all the sprites move. Same as collect blocks example, but you can move the sprite by clicking to pick them up. Rather than just move down, these sprites bounce. Prior example too boring?
Get the sprites to move in circles. Expands the prior example to show how to manage a game with levels. Level advances when all the blocks are cleared. Same as spritecollectblocks.py but with a black circle instead of a block. Same as spritecollectblocks.py but with a graphic instead of a block.
Same as spritecollectblocks.py but with a graphic instead of a block. Same idea as spritecollectblocks.py but uses a Game class to organize the code. This is a more advanced way of organizing the code.
It helps if you want to “restart” a game once it is over. Move a sprite around the screen with the mouse. Move a sprite with the keyboard in discrete “jumps.”. Move a sprite with the keyboard smoothly and continuously while a key is pressed. Move a sprite with a game controller or joystick. Basic Pong game using two game controllers. How to manage bullets with sprites.
How to aim bullets. Control a snake as it moves around the screen. Move a sprite around the screen, but not let it move through walls.
More complex version of prior example, with multi-colored walls, and multiple rooms. Get the player to jump off platforms.
Like platform jumper, but scroll side to side. Make those platforms move!. A multi-file example that shows a platformer using sprite sheets.
Popular Snake game with Python-Pygame module. Important: If you try to run this script without special png-wav files it will fail, you have to put following files to a directory with this script. They are basically apple picture, head of snake, intro sound and dead sound.Without them script will not run. Just make inactive the statements intro.wav and dead.wav, and find a little apple picture and snake head:).Or you can play the game just install it. Here is the installer: It will install the game in program files, you can find it in search 'Flafel' and click to Flafel.exe. #!/usr/bin/env python # -.-coding:utf-8-.- import pygame, sys import win32api, win32console, win32gui, codecs import time, random from pygame.sprite import Sprite pygame.
Mar 08, 2010 3D Custom Girl: touhou girls and others. I managed to get my hands on 3D Custom Girl thanks to a friend. I can get the mod for ya if you want. 3d custom girl clothes mod. Alibaba.com offers 279 3d custom girl mods clothing products. About 79% of these are plus size jackets, 6% are girls' clothing sets, and 6% are fitness & yoga wear.
Init win = win32console. GetConsoleWindow win32gui. ShowWindow ( win, 0 ) white = ( 255, 255, 255 ) black = ( 0, 0, 0 ) red = ( 255, 0, 0 ) green = ( 0, 155, 0 ) displaywidth = 800 displayheight = 600 gameDisplay = pygame.
Setmode (( displaywidth, displayheight )) pygame. Setcaption ( 'Flafel' ) icon = pygame. Load ( 'apple.png' ) pygame. Seticon ( icon ) img = pygame. Load ( 'snakehead.png' ) appleimg = pygame. Load ( 'apple.png' ) clock = pygame.
Clock AppleThickness = 30 blocksize = 20 FPS = 15 direction = 'right' smallfont = pygame. SysFont ( 'comicsansms', 25 ) medfont = pygame. SysFont ( 'comicsansms', 50 ) largefont = pygame. SysFont ( 'comicsansms', 80 ) pygame. Init introsound = pygame. Sound ( 'intro.wav' ) deadsound = pygame. Sound ( 'dead.wav' ) def gameintro : intro = True while intro: for event in pygame.
Get : if event. Type pygame. QUIT: pygame. Quit quit if event. Type pygame.
KEYDOWN: if event. Key pygame. Kc: intro = False if event. Key pygame. Quit quit gameDisplay.
Fill ( white ) messagetoscreen ( 'Welcome to Flafel', green, - 100, 'large' ) messagetoscreen ( 'The objective of the game is to eat red apples', black, - 30 ) messagetoscreen ( 'The more apples you eat,the longer you get', black, 10 ) messagetoscreen ( 'If you run into yourself, or the edges, you die!' , black, 50 ) messagetoscreen ( 'Press C to play, P to pause or Q to quit', black, 180 ) pygame. Update clock. Tick ( 15 ) def pause : paused = True messagetoscreen ( 'Paused', black, - 100, size = 'large' ) messagetoscreen ( 'Press C to continue or Q to quit', black, 25 ) pygame.
Update while paused: for event in pygame. Get : if event. Type pygame. QUIT: pygame. Quit quit if event.
Type pygame. KEYDOWN: if event. Key pygame. Kc: paused = False elif event. Key pygame. Quit quit clock.
Tick ( 5 ) def score ( score ): text = smallfont. Render ( 'Score: ' + str ( score ), True, black ) gameDisplay.
Blit ( text, 0, 0 ) def randAppleGen : randApplex = round ( random. Randrange ( 0, displaywidth - AppleThickness )) #/10.0).10.0 randAppley = round ( random. Randrange ( 0, displayheight - AppleThickness )) #/10.0).10.0 return randApplex, randAppley def snake ( blocksize, snakeList ): if direction 'right': head = pygame. Rotate ( img, 270 ) if direction 'left': head = pygame. Rotate ( img, 90 ) if direction 'up': head = img if direction 'down': head = pygame. Rotate ( img, 180 ) gameDisplay. Blit ( head,( snakeList - 1 0 , snakeList - 1 1 )) for XnY in snakeList : - 1 : pygame.
Rect ( gameDisplay, green, ( XnY 0 , XnY 1 , blocksize, blocksize )) def textobjects ( text, color, size ): if size 'small': textSurface = smallfont. Render ( text, True, color ) elif size 'medium': textSurface = medfont. Render ( text, True, color ) elif size 'large': textSurface = largefont.
Render ( text, True, color ) return textSurface, textSurface. Getrect def messagetoscreen ( msg, color, ydisplace = 0, size = 'small' ): textSurf, textRect = textobjects ( msg, color, size ) textRect. Center = ( displaywidth / 2 ),( displayheight / 2 ) + ydisplace gameDisplay. Blit ( textSurf, textRect ) def gameLoop : global direction direction = 'right' running = True gameOver = False leadx = displaywidth / 2 leady = displayheight / 2 leadxchange = 10 leadychange = 0 snakeList = snakeLength = 1 randApplex, randAppley = randAppleGen while running: if gameOver True: messagetoscreen ( 'Game over', red, - 50, size = 'large' ) messagetoscreen ( 'Press C to play again or Q to quit', black, 50, size = 'medium' ) pygame. Update while gameOver True: #gameDisplay.fill(white) for event in pygame. Get : if event. Type pygame.
QUIT: gameOver = False running = False if event. Type pygame. KEYDOWN: if event. Key pygame. Kq: running = False gameOver = False if event. Key pygame.
Kc: gameLoop for event in pygame. Get : if event. Type pygame. Tvgenial 3.4 crack. QUIT: running = False if event. Type pygame. KEYDOWN: if event.
Key pygame. KLEFT: direction = 'left' leadxchange = - blocksize leadychange = 0 elif event. Key pygame. KRIGHT: direction = 'right' leadxchange = blocksize leadychange = 0 elif event. Key pygame. KUP: direction = 'up' leadychange = - blocksize leadxchange = 0 elif event. Key pygame.
KDOWN: direction = 'down' leadychange = blocksize leadxchange = 0 elif event. Key pygame. Kp: pause if leadx = displaywidth or leadx = displayheight: gameOver = True deadsound.
Play leadx += leadxchange leady += leadychange gameDisplay. Fill ( white ) gameDisplay. Blit ( appleimg,( randApplex, randAppley )) snakeHead = snakeHead. Append ( leadx ) snakeHead. Append ( leady ) snakeList. Append ( snakeHead ) if len ( snakeList ) snakeLength: del snakeList 0 for eachSegment in snakeList : - 1 : if eachSegment snakeHead: gameOver = True deadsound. Play snake ( blocksize, snakeList ) score ( snakeLength - 1 ) pygame.
Update if leadx randApplex and leadx randApplex and leadx + blocksize randAppley and leady randAppley and leady + blocksize.
Comments are closed.
|
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |