Sunday, November 2, 2014

Bouncing

     Looks like I missed an article on Halloween... I've been trying to write an article but other stuff keeps happening... Oh well. I probably wouldn't be able to find a good Halloween theme for this topic, anyway.
     Welp, here's today's! Hopefully you aren't caught up by the time you read this.
     Anyway, I hope you still have the picture of that ball in your Python folder--we're using it some more! As you can see from the title of the article, we are going to "bounce the ball."
     Secretly, objects cannot make contact with the sides of the window, so you just have to determine the edge of the screen. For fun, I am going to make the ball move up and down this time (and don't forget, its picture size is 150 x 150 pixels!). In order to allow the ball to change directions, it's best to use a variable. Another thing you shouldn't forget is that when you increase the Y axis, the image goes downward. But, enough chit-chat, let's finally get down to business!
     We already have a lot of it done already from the previous article. All we have to do is change the x = x + 5 into y + [yvariable]. In order to do this, we will add a new variable at the top of the code (outside of the block). I will be calling mine yspeed, and its value will be 5. This variable will make the speed easily managable if we ever need to change it (and we will).
     Now, take the x = x + 5 line and change it to y = y + yspeed (or whatever your variable is). Now, here's a word of advice: there is a function called screen.get_height() (as well as screen.get_width()). This is an easy way to... well, it's obvious. it finds the screen's height and stores it as a number for the following code it ties into. Inside our True block, we will add this function in an "if" block by typing, "if y > screen.get_height() - 150 or y <= 0:"
     Inside this line, we will say "yspeed = - yspeed," turning the 5 into a negative 5 (because, you know, of the -). The "y <= 0" part will check if the number representing y is above or equal to the number 0 (the top of the screen) and reverses its sign again, turning it back into a positive.
     Keep in mind that the y variable is only a number, not actually the screen's height. That's pretty confusing, but since y always the same number as the ball's position, it works.
     So, long story short, the entire program should look like this:

import pygame, sys
import time
pygame.init()
screen=pygame.display.set_mode([640, 480])
screen.fill([255, 255, 255])
ball = pygame.image.load("Ball.png")
x=50
y=50
yspeed=5
screen.blit(ball, [x, y])
pygame.display.flip()
while True:
    pygame.time.delay(20)
    pygame.draw.rect(screen, [255, 255, 255], [x, y, 150, 150], 0)
    y = y + yspeed
    if y > screen.get_height() - 150 or y < 0:
        yspeed = - yspeed
    screen.blit(ball, [x, y])
    pygame.display.flip()
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()

     When you run the program, the ball should start moving up & down, never leaving the screen. It may not be a huge game produced by a popular corporation, but, hey, it's still pretty cool! We're finally getting somewhere!
     Well, that's all there is about bouncing. See you next time!.. Should I find the time and inspiration to write the next article! Until then, I challenge you to make the ball bounce diagonally! Heres a tip: The screen.get_width() and screen.get_height() functions find the position of the right and bottom sides of the screen.
     Here's something for an extra challenge: Try to get the ball to appear on one side of the screen when it reaches the other! You can just have it move vertically or horizontally if you'd like.

Monday, August 25, 2014

Movement

     A red ball on the screen is mighty exciting, isn't it? Well, it's about to get better. But just a little. We're going to move the ball. We're going to add 3 new lines between the exit block and the line before:

import pygame, sys
pygame.init()
screen=pygame.display.set_mode([640, 480])
screen.fill([255, 255, 255])
ball = pygame.image.load("Ball.png")
screen.blit(ball, [50, 50])
pygame.display.flip()
pygame.time.delay(2000)
screen.blit(ball, [200, 50])
pygame.display.flip()
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT: sys.exit()

     Whoa. 2,000 seconds. But, just run the program. All of a sudden...



     I don't necessarily think that counts as moving. Remember, blitting is copying. So, in video games, nothing actually moves. A new version of an image is created for every movement it makes, pixel by pixel. This means we have to wipe the original image from existence. Actually, truth be told, that can't exactly be done. We have to paint over the original. We have to erase the original image before we flip the screen and show the new one. There's only one line of code that needs to be added, right before the flip() function. And just so you know, the picture is 150 by 150 pixels.

import pygame, sys
pygame.init()
screen=pygame.display.set_mode([640, 480])
screen.fill([255, 255, 255])
ball = pygame.image.load("Ball.png")
screen.blit(ball, [50, 50])
pygame.display.flip()
pygame.time.delay(2000)
screen.blit(ball, [200, 50])
pygame.draw.rect(screen, [255, 255, 255], [50, 50, 150, 150], 0)
pygame.display.flip()
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT: sys.exit()

     Now when you run it, the problem should be solved.


     Much better!
     So, that's our ball that moves simply once. Let's see if we can get the animation smoother! Let's change the program so it makes smaller steps, and make it keep moving.

import pygame, sys
pygame.init()
screen=pygame.display.set_mode([640, 480])
screen.fill([255, 255, 255])
ball = pygame.image.load("Ball.png")
x=50
y=50
screen.blit(ball, [x, y])
pygame.display.flip()
while True:
    pygame.time.delay(20)
    pygame.draw.rect(screen, [255, 255, 255], [x, y, 150, 150], 0)
    x=x+5
    screen.blit(ball, [x, y])
    pygame.display.flip()
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()

     You see, it spawns the ball at the points of x and y, and while the program is True (still running), it will move the ball directly to the right every 20 milliseconds, erasing the original with a block of white. In order to avoid erasing the current one, the previous one has to be painted over first. Remember that for fluid movement!
     When you run the program, the ball will move smoothly, but then it goes off of the screen, since it doesn't have any functions to bounce off of the side of the screen or anything. But the good thing is that it doesn't strobe white as it could have done!
     Wow, this article is getting really long. Think of it as an apology for the rate of my article writing this year. Anyway, see you next time!

Sunday, July 6, 2014

A Quick Review

     So, how was your 4th of July (and if you're Canadian, how was your Canada day)? Sorry I missed writing an article on that day. But, here's a little program gift to you.
Download the file here (.zip). Put it in your Python folder and extract the files.
And if you're Canadian, here's one for CanaDay. Follow the instructions above to use the program.

     Anyway, those images can really tie into what we're currently learning about. Images (evidently).
     Actually, we'll probably never use those programs ever again, so let's just go back to our red dot.
     We should all know what image.load() does. It loads whatever is in the parenthesis, thought it has to be a string. That's how it goes. Let's just move on. The image it loads is its own surface, like screen (do you understand why those shapes we made needed a surface to be put on now?). This surface is only in memory, though. Screen is the one we can see, though. We make that surface in line 3 of all of our Pygame programs. screen.blit(ball, [50, 50]) copies the image's surface and pastes it onto the screen surface. display.flip() takes the display surface and (if you think about it literally) flips what's in the window over so the display surface can be visible.
     Um, wait a minute. I have no idea who would know what blit means without looking up a special programming dictionary or something. You see, when we use screen.blit(ball, [50, 50]) or something like that, we're copying the pixels of a surface and putting them on another. This is known as blitting. It's just the programming term for copying a bunch of pixels. [50, 50] is the location from the top left corner (remember the coordinate chart for programming!) where the pixels will be copied.
     I suppose that will be it for this article. See you next time!

Wednesday, June 25, 2014

The Red Circle

     I know, that last article was REALLY confusing. Personally, I'd never program a drawing from scratch. It's easier to use images! In this article, we'll be working with pictures.
So, how tedious would it be to put down each individual pixel for a game? That's what pictures are for! First up, I'll show you how to insert an image. First you need to save the following image as Ball.png, and put it in...wherever you keep your Python programs. For me, it's Python 32, and if your computer is anything like mine, your programs folder will be in your Computer section, in Local Disk (C:). Now, here's that picture:


     Remember, Ball.png. Once it's all good and saved, type in this as a new program:


import pygame, sys
pygame.init()
screen=pygame.display.set_mode([640, 480])
screen.fill([255, 255, 255])
ball = pygame.image.load("Ball.png")
screen.blit(ball, [50, 50])
pygame.display.flip()
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT: sys.exit()


     When you run the program, it should display a big red dot around the top-left corner.


     Wow. A red dot. That's so amazing. But, hey! We're one step closer to being talented programmers!
     We'll continue all this picture stuff next time. Bye!

Tuesday, June 24, 2014

Sine Waves

     You all should have seen this coming. I don't know about you, but this is my worst enemy.
     Math.
     Actually, my worst enemy is creative writing, but that set aside, we have math calculations coming into Python. This is math that won't be done for us, such as print(55 * 10000000e+7). This math works with pixels, and Python won't just go around telling you all 307,200 points. It's all in the luck of the mind. But, I will be nice and won't let you do the math. Yet.
     I've set up a program that draws something called a sine wave (it's some sort of wavy line that works with sound, such as spiking when the volume gets louder). It sets up pixels in various spots to create the basic shape of a sine wave. Open your version of Python and enter this into a new program:



import pygame, sys
import math
pygame.init()
screen = pygame.display.set_mode([640, 480])
screen.fill([0, 0, 0])
for x in range(0, 640):
    y = int(math.sin(x/64.0 * 4 * math.pi) * 200 + 240)
    pygame.draw.rect(screen, [255, 255, 255], [x, y, 1, 1], 1)
pygame.display.flip()
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()



     Just look at that line of math! Can anyone follow that?!...eh. We'll discuss the math functions later. When you run the program, you should get this:


     I had to do white against black instead of black against white this time because it looks cool.
     ...Well. This is...a really embarrassing sine wave. It was torn to shreds and all that's left to show is a few white dots. But, hey, this might come in handy later on for a physics game or something.
     Round as those dots may seem, they're completely square. Each dot is 1 pixel squared. Also, here's a note: the width of the pixels are 1. If it was 0, then there would be nothing on the screen.
     Alright, I'm getting sick of that pathetic sine wave I drew. It's time to fix it! Pygame has a method to draw a single line, and a method to draw multiple lines between multiple points. It's known as pygame.draw.lines(), and must meet the 5 requirements to work.

Surface
On what "surface" to draw the line (in our case, screen).
Color
What color the line will be.
Close
The program needs to know whether or not it should connect the last dot to the first one. We don't want to stick a line through our sine wave, so we'll label it False.
Points
A list of points to connect to.
Width
How thick the line is. If the thickness is 0, it will be nothing.

     So, what we'd write is this:
pygame.draw.lines(screen, [255, 255, 255], False, plotPoints, 1)
     But that's only the appearance of the line. Python doesn't know where to place the line, so we'll have to do a things a bit differently. Retype the program to be like this:



import pygame, sys
import math
pygame.init()
screen=pygame.display.set_mode([640, 480])
screen.fill([0, 0, 0])
plotPoints = []
for x in range(0, 640):
    y = int(math.sin(x/640.0 * 4 * math.pi) * 200 + 240)
    plotPoints.append([x, y])
pygame.draw.lines(screen, [255, 255, 255], False, plotPoints, 2)
pygame.display.flip()
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()



     Notice that I changed the line's thickness to 2. This is just so it looks better. When you run the program, you should get this:


     I stretched the waves out a little more so they'll look good. Actually, I think there was a typo somewhere. But, there is our complete sine wave! Was that evil or what? This is what happens when you draw with programming.
     I guess that's the end of this article. I challenge you to experiment with the lines and points to see what you can do with them! Good luck, and see you next time!

Monday, April 7, 2014

Rect

     Look, you may know how to draw circles, but that's not all you can draw in Python. You can also draw square shapes, A.K.A. rectangles. Of course, there is a function for this. This function is called rect (short for rectangle, of course). You define the rect by the area, starting from the top-left corner, in this order: left, top, width, height. This list defines the location and and size. Something like this: rect1=Rect(250, 150, 300, 200). 250 pixels to the right (starting from the top-left of the screen), 150 down, and the size is 300x200 pixels. Take the program that draws the circle and replace line 6 (I'm counting the blank line, so you should be on the line that actually draws the circle) with the code that I stated that draws the rectangle. The program should look like this.

import pygame, sys
pygame.init()
screen=pygame.display.set_mode([640, 480])
screen.fill([255, 255, 255])
pygame.draw.rect(screen, [255, 0, 0], [250, 150, 300, 200] 0)
pygame.display.flip()
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()

     And when you run it, you get a blank screen with a big, red block slapped on.

     Ta-da! That's how you make a rectangle. Hey, I might as well give you the steps to making a rectangle like what I did for doing a shape in general, in case you forget something or the order. Here is the list:

Location - Left-Right
This is the distance the rectangle will be from the left side of the screen.
Location - Top-Bottom
This is the distance the rectangle will be from the top of the screen.
Size - Width
How wide the rectangle will be.
Size - Height
How tall the rectangle will be.

     That's the end of this little bit on rectangles. Until next time!

Monday, March 17, 2014

Review

     So, remember, when we did the color of the circle, we typed "255, 0, 0"? Well, this is a color system used in most computer languages: R.G.B. It stands for Red, Green, & Blue. Simple. The max number you can have of one of those colors is 255, and the least is evidently 0. The higher the number of one color is, it will look more like that one. There are over 600 colors! Some are 255, 255, 255 (white), 255, 0, 0 (red), 0, 0, 255 (dark blue), 0, 255, 255 (light blue), 255, 0, 255 (pink), 0, 0, 0 (black), 0, 255, 0 (light green), and 255, 255, 0 (yellow). That's only some of the main ones. And that was quite a lot. You can try experimenting around with the colors and see what you find. If you know your color mixtures, then you should already have an idea of what colors you can figure out.
     Okay, off of the topic of color, let's go to coordinates. You might have learned about coordinates in math class, with the X axis (the horizontal line) and the Y axis (the vertical line going through the X axis). You use these same coordinates when placing something on the screen (remember, the X axis goes first, down the hall, and then the Y axis, up the stairs). Remember that (0, 0) starts at the top left corner of the screen. Well, if you have learned about coordinates in math, you would know that (0, 0) should be in the middle, but, apparently, this is one of the many programming mysteries of the world. So, remember, this: The X axis goes along the top of the window, and the Y axis will go down. Kick that knowledge of normal coordinates out and memorize those computer coordinates. With the size of the screen we always use, (320, 240) should be the middle.

import pygame, sys

pygame.init()
screen = pygame.display.set_mode([640, 480])
screen.fill([0, 255, 0])
pygame.draw.circle(screen, [255, 100, 0], [320, 240], 30, 0)
pygame.display.flip()
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()


     Well, there's a code to verify. Let's see what happens when we run it.


     Ha! I bet you thought I forgot it was St. Patrick's Day! Nah, those colors are a sure sign I didn't. I wouldn't want you to track me down just so you could pinch me!
     We'll continue the review next time. I have to go slay an evil death dragon in a Pygame now. Bye!

Friday, February 14, 2014

Graphics: The Hollow Circle

     You guessed it--that's graphics. When you zoom in very, very far, you'll see a ton of tiny blocks. Well, of course, these are pixels, picture elements. Everything virtual has these, from the computer to the Wii.
     Let's make our own graphics!
     Well, we all know the black screen of black screens. Open that up and edit the program to this.


import pygame, sys
pygame.init()
screen=pygame.display.set_mode([640, 480])
screen.fill([255, 255, 255])
pygame.draw.circle(screen, [255, 0, 0], [100, 400], 30, 10)
pygame.display.flip()
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()


     Colors. They're hard to explain. ([255, 255, 255]) and [255, 0, 0] is computer for white and red. Here's the 5 steps to creating a shape:
Surface
On what "surface" to draw the circle (in our case, screen).
Color
What color the circle will be.
Location
Where on the surface the circle will appear.
Size
Self-explanatory. The size (the radius measured by pixels).
Width
How thick the line is. If the thickness is 0, it will be a solid circle.
     Yeah, it's Valentines Day. What's the theme? Red and White are Valentine colors. That's all I got. It's not easy for something like this.
Remember, EVERYTHING is measured by pixels.
     I challenge you to experiment with the colors. Here's a tip: There are always 3 sets of numbers.

Tuesday, January 21, 2014

X

     So, last time, we created a Pygame program. Uh, but it's just a black screen. And it stays open for a mere second. Not even the X button works. So, today we're trying to get X to work. How does that work? Let's just find out.
     A standard module of Python known as sys is our key. A function from sys is sys.exit(). "No questions asked. Just close the window." So, this is how we're going to use it.

import pygame, sys
pygame.init()
screen=pygame.display.set_mode([640, 480])
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()

     Wow, just getting a black screen to be able to close takes a lot of code. So, not only did we do that, but now we can drag the screen around without having it crash! But, well, it will crash if you hit the X button. Man, that icon is hard to work with!
     Oh well... Next time, we're getting into the gooder--I mean better--stuff. We're going to do graphics.

Wednesday, January 1, 2014

Print("Hello") to Pygame!

     Have you had fun reading these articles and creating basic games over the course of 2013? I hope so, because my New Years resolution is to make things a lot more entertaining! Print("Hello") to graphics!
     Not only graphics, but getting sound as well is difficult. It has to do with operating systems, graphics cards, and a lot of other random things you most likely don't know about. Don't worry, though. Remember last article, when I talked about downloading standard modules? I have (a safe) one here, at pygame.org!
     Just so you know, Pygame doesn't run on Python 3.3.0. You'll have to find a version of Python that supports it. And me? I'm using Python 2.5. Also, Pygame needs to be supported by Numeric, which can also be found on the site.
     Alright, I hope everything's cleared up. Type this in the new window of your new Python IDLE window.

import pygame
pygame.init()
screen=pygame.display.set_mode([640, 480])

     If you run this program, you should get a window that's just a black screen for a second.


     Either that, or it crashes instantly.
     Games aren't independent. They interact with the user. Pygame is meant for creating games. But, it has something called event loops. They constantly check for things the user does, such as jamming on the keyboard or flinging the mouse. The "game" we just made had no event loop started in the first place. The Pygame window stays open while the program is running. Let's keep it running. Add this to the bottom of the program.

while True:
    pass

     You see, True means... True, and pass means... Do nothing. This may seem confusing at first. Seeing the entire program might help.

import pygame
pygame.init()
screen=pygame.display.set_mode([640, 480])
while True:
    pass

     So, you might have found out by now. This basically means, "while the window is open, do NOTHING." So, it does nothing. That means it doesn't even close or crash. So, let's run it. Remember, you can use CTRL+C to close it (as long as IDLE is the active window).


     It didn't crash that time! Alright! We're getting somewhere! But, try running the program again. What happens when you press that X button in the corner, you know, the one that closes every window?


     Not again! We've got to make that thing work.
     I suppose we'll discuss X next article. See ya!