So last week I was telling you all about Pygame. Well, it was more about a certain book which covers python game development using pygame. Anyway, I thought I might share a bit of code that I've used in designing my latest python game.
The idea for my game was just a simple hack-n-slash zombie killer. Nothing flashy, just a project to help me keep my python skills from going to utter crap. The game isn't quite finished, but I've learned a few things along the way. And if there's any interest, I can post the source for what I have so far. Just let me know.
Anywho, so where do you start with a python game? Well, if you're using pygame libraries, you'll want to import the libraries, initialize pygame and create a surface to begin drawing.
import pygame
pygame.init()
#create the display object named screen
screen = pygame.display.set_mode((800, 600))
Use whatever size screen you want. And if you feel fancy, you could use the os or pygame libraries to pull the display resolution and use that. To do that with python, just use something like:
screen_x = pygame.display.Info().current_w
screen_y = pygame.display.Info().current_h
screen = pygame.display.set_mode((screen_x,screen_y))
Of course, that's a bit wonky since it's still windowed, and the explorer bar one windows, (or the menu bar on linux distros) will be in the way. To get around this you have to set the display to fullscreen. Here's an example:
#give me the biggest 16bit display available
>>> modes = pygame.display.list_modes(16)
>>> if not modes:
... print '16bit not supported'
... else:
... print 'Found Resolution:', modes[0]
... pygame.display.set_mode(modes[0], FULLSCREEN, 16)
I pulled this example from one of the pygame tutorials located here: http://www.pygame.org/docs/tut/DisplayModes.html
Anyway, once you have this much, you can start drawing to the screen. You can draw images (loaded from a file) or just draw some basic shapes using pygame. Let's start by drawing a background. I'm just going to fill it black.
background = pygame.Surface(screen.get_size())
background.fill((0,0,0))
By the way, if you're going to be using certain colors throughout your code, it makes sense to create some variables to store the rgb tuples. Here's a few to get you started:
black = (0,0,0)
white = (255,255,255)
blue = (0,0,255)
red = (255,0,0)
green = (0,255,0)
#then if you were to use them to fill the background it would look like this
background.fill(black)
So now we've got a black background, so what? Most boring game ever. Let's add a rectangle or something.
pygame.draw.rect(background, green, (100, 100, 100, 100))
You can probably figure that out, but I'm using the pygame draw class to draw a rectangle. This function takes several arguments. First it needs a surface to draw the rectangle to, I used background. Then it takes a tuple for the color. And lastly it needs to know where the rectangle is to be drawn, and the dimensions. These are passed as a tuple of four elements, where the first element is the x coordinate and the second element is the y coordinate. The other two are for width and height.
This is drawing the rectangle (square actually) object to the background surface. Remember though, that the background was drawn to the screen surface object. So how do we display the changes we just made to the background surface? With the blit function. Each surface object has a number of useful functions that come along with it. Blit basically, redraws one surface to another, updating any changed pixels. Here's a quick example:
screen.blit(background, (0,0))
I'm updating the screen surface with the new background image at the coordinates 0, 0. Since the background is the same size, this will place it directly on top of the screen.
If you run this, it will open your game, draw the rectangle and immediately close it. In order to keep the window open, you have to have the drawing done in some sort of loop, or tell python to wait for input or something to that effect. I may go over the different ways to do that later on, but for now let's just create a little game loop to watch for "events" and quit when it sees a specific event.
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
You can probably guess as to what this does for the most part. It's looking through pygame events, which are all sorts of keyboard, and mouse input events. pygame.QUIT is basically when the user clicks the window's X to close the window. Without this you'll have to manually kill the process.
So here's what we have so far:
import pygame
#set up color variables
black = (0,0,0)
white = (255,255,255)
blue = (0,0,255)
red = (255,0,0)
green = (0,255,0)
#start pygame
pygame.init()
#set up a basic surface
screen = pygame.display.set_mode((800, 600))
#create a background using the screen surface size
background = pygame.Surface(screen.get_size())
background.fill(black)
#draw a rectangle to the background surface
pygame.draw.rect(background,green,(100,100,100,100))
#draw the whole thing to the screen
screen.blit(background, (0,0))
#update your display
pygame.display.update()
#loop through events till we get the signal to close the window
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
And there we go. We have a basic window, with a couple surfaces, and a rectangle object that we have drawn onto them. Now you could do this with a single surface object. I just got into the habit of having two recently. The reason for this is kind of convoluted, and it involves a solution for resizing the window to fit multiple android devices. I'll have to do a post on that down the road, but this post is getting pretty lengthy, so I'll just leave off here for now.
Next time, I'll go into a bit about moving your rectangles and animating using images rather than just using a single static green rectangle.
-Newt
Wednesday, March 27, 2013
Wednesday, March 20, 2013
Games with Python
Over the last year and some change, I've been trying to teach myself to code. I started with Python for no real reason other than there were a number of tutorial sites out there that seemed to be pretty complete.
After going through the tutorials and Python documentation (several times in some cases) I found myself wondering how to get in some badly needed practice. After all, in order to code something you need to have some sort of use case in mind. I had found a number of forums offering up ideas for projects, but most were either way above my head or so simple I completed them in minutes.
Longer projects seemed to only hold my interest if there were some actual need for the functionality. Like parsing proxy logs or cmdb data at work. For everything else, I had trouble keeping focused till the completion of the code.
One day, by chance, I found this: http://inventwithpython.com/
At the time Albert Sweigart had only written the first book, but it was enough to renew my interest in learning the language. It's written so that even those with no working knowledge of programming can start creating games and learning python. It goes through a few command-line based games, into graphics based games teaching skills that can easily be translated into scripting and app development.
If you are interested in simple game development, or Python, I would definitely recommend reading his book either by download (for free) or purchasing a hardcopy . The second book is also now available and goes into even more detail with several new game types and development concepts.
I know this sounds like some sort of plug, but I am in no way being compensated for this endorsement. I am merely a grateful reader of his work.
-newt
After going through the tutorials and Python documentation (several times in some cases) I found myself wondering how to get in some badly needed practice. After all, in order to code something you need to have some sort of use case in mind. I had found a number of forums offering up ideas for projects, but most were either way above my head or so simple I completed them in minutes.
Longer projects seemed to only hold my interest if there were some actual need for the functionality. Like parsing proxy logs or cmdb data at work. For everything else, I had trouble keeping focused till the completion of the code.
One day, by chance, I found this: http://inventwithpython.com/
At the time Albert Sweigart had only written the first book, but it was enough to renew my interest in learning the language. It's written so that even those with no working knowledge of programming can start creating games and learning python. It goes through a few command-line based games, into graphics based games teaching skills that can easily be translated into scripting and app development.
If you are interested in simple game development, or Python, I would definitely recommend reading his book either by download (for free) or purchasing a hardcopy . The second book is also now available and goes into even more detail with several new game types and development concepts.
I know this sounds like some sort of plug, but I am in no way being compensated for this endorsement. I am merely a grateful reader of his work.
-newt
Wednesday, March 13, 2013
Coding Challenge - Python
So I've been a fan of hackthissite.org for a while now. IT Security has been an interest of mine since I was introduced to computers. They've got tons of hacking challenges to test your skills and teach you new ones.
Just recently though, I noticed that they have coding/scripting challenges now as well. They range from beginner to really difficult, but they've got some really neat ones up there. If you're interested, go register (for free, of course) and try them out for yourself.
The first challenge asks you to code something that can take a number of scrambled words, that were chosen from a file that they provide you with, run the input through a script and produce the unscrambled words in a specific format. i.e. (word1, word2, word3,.....)
Sure you could do it manually, but the page expires a few seconds after the scrambled words are given. So you have to get the scrambled words, run them through your script and submit the output in a few seconds.
There are a ton of ways you could handle this, like sending the output to a file, or console, or even have it go straight to the clipboard so you can paste it into the web form quickly. Even write something to parse the page, pull down the words, and post the output automatically...
Below the break, you can see how I did it using python. Kind of a spoiler if you're planning to try this stuff out yourself, just fyi.
Just recently though, I noticed that they have coding/scripting challenges now as well. They range from beginner to really difficult, but they've got some really neat ones up there. If you're interested, go register (for free, of course) and try them out for yourself.
The first challenge asks you to code something that can take a number of scrambled words, that were chosen from a file that they provide you with, run the input through a script and produce the unscrambled words in a specific format. i.e. (word1, word2, word3,.....)
Sure you could do it manually, but the page expires a few seconds after the scrambled words are given. So you have to get the scrambled words, run them through your script and submit the output in a few seconds.
There are a ton of ways you could handle this, like sending the output to a file, or console, or even have it go straight to the clipboard so you can paste it into the web form quickly. Even write something to parse the page, pull down the words, and post the output automatically...
Below the break, you can see how I did it using python. Kind of a spoiler if you're planning to try this stuff out yourself, just fyi.
Labels:
Challenge,
Code,
hackthissite,
output to file,
Python,
Script
Wednesday, March 6, 2013
Assignment - Python
So, one of my java classes had this assignment a while back to write a command-line application to store user input to a text file. Easy, right? Just loop over the 3 questions and save the user responses on a line in a text file.
Having never worked with Java before, I was surprised at the amount of code necessary to do this. Even without validating user input, the code ended up being around 40 lines.
It got me thinking about how I would do the same thing in python. And I was curious to see how few lines it would take to get the exact same functionality. Here's what I came up with:
file = open("output.txt", 'w')
listOfStuff = []
while True:
productID = raw_input("enter productID: ")
product = raw_input("enter product: ")
price = raw_input("enter price: ")
listOfStuff.append(productID+" "+product+" "+price+ "\n")
blah = raw_input("Coninue? yes or no: ")
if blah in ("no", "nope", "negative"):
break
for i in listOfStuff:
file.write(i)
file.close()
13 lines does it. Sure I should do some input validation and all that best-practice jazz, but I didn't have to implement any of that for the java project either, and I was just trying to get the same output and functionality.
If anyone wants to see the crappy java version of this that I did, I guess I could post that too, just leave a comment, or shoot me a message. I only leave it out because 1) I'm lazy, and 2) I have my doubts about anyone actually reading this blog.
-newt
Having never worked with Java before, I was surprised at the amount of code necessary to do this. Even without validating user input, the code ended up being around 40 lines.
It got me thinking about how I would do the same thing in python. And I was curious to see how few lines it would take to get the exact same functionality. Here's what I came up with:
file = open("output.txt", 'w')
listOfStuff = []
while True:
productID = raw_input("enter productID: ")
product = raw_input("enter product: ")
price = raw_input("enter price: ")
listOfStuff.append(productID+" "+product+" "+price+ "\n")
blah = raw_input("Coninue? yes or no: ")
if blah in ("no", "nope", "negative"):
break
for i in listOfStuff:
file.write(i)
file.close()
13 lines does it. Sure I should do some input validation and all that best-practice jazz, but I didn't have to implement any of that for the java project either, and I was just trying to get the same output and functionality.
If anyone wants to see the crappy java version of this that I did, I guess I could post that too, just leave a comment, or shoot me a message. I only leave it out because 1) I'm lazy, and 2) I have my doubts about anyone actually reading this blog.
-newt
Subscribe to:
Posts (Atom)