"Hello Tank" is a simple program which shows how Pygames main loop should work, how events can be handled and sprites can be moved. You can download the complete source and images here.
Let us start with some simple stuff: Image loading.
def load_image(imagefile):The function load_image gets the path to an image file and returns the loaded image, or raises SystemExit, if the image could not be loaded. Looks pretty simple, right?
try:
image = pygame.image.load(imagefile)
except pygame.error:
print "Cannot load image:" , imagefile
raise SystemExit
return image
After we are able to load images it is time to get to some more complex stuff to work. What we need is a movable tank!
class Tank(pygame.sprite.Sprite):What should I say, it is a tank. It can be created, rotated and driven. The movement direction is determined by the rotation. As you can see, the image is already rotated by 90 degrees. The tank inherits from pygame.sprite.Sprite. This is the base class for all visible objects in Pygame. Also we assign an image to our tank.
def __init__(self, position=(0,0)):
pygame.sprite.Sprite.__init__(self)
self.originalImage = load_image("tank.png")
self.movement = [0,1]
self.position = list(position)
self.rotation = 0
self.rotate_tank(0)
def update_position(self):
self.rect = self.image.get_rect()
self.rect.center = self.position
def update_movement_direction(self):
self.movement[0] = -math.cos(
math.radians(self.rotation + 90)
)
self.movement[1] = math.sin(
math.radians(self.rotation + 90)
)
def rotate_tank(self, angle):
self.rotation += angle
self.image = pygame.transform.rotate(
self.originalImage, self.rotation
)
self.update_position()
self.update_movement_direction()
def drive(self, speed):
self.position[0] -= speed * self.movement[0]
self.position[1] -= speed * self.movement[1]
self.update_position()
We now have a tank. But where can we test it?
class HelloTank(object):As a last step we only need to create a HelloTank instance and let it run.
def __init__(self):
object.__init__(self)
self.initialize_pygame()
self.bgImage = load_image("background.png")
self.tank = Tank((512, 320))
self.leftArrow = False
self.rightArrow = False
self.upArrow = False
self.downArrow = False
self.drawableObjects = \
pygame.sprite.RenderPlain(self.tank)
def initialize_pygame(self):
pygame.init()
self.window = \
pygame.display.set_mode((1024,768))
pygame.display.set_caption(
"warofthepolygons.com - Hello Tank!"
)
self.screen = pygame.display.get_surface()
self.clock = pygame.time.Clock()
def tick(self, clockrate=50):
self.clock.tick(clockrate)
def handle_events(self):
# get the events from pygames event queue
events = pygame.event.get()
# handle the events
for event in events:
# Return False, if the user closes the window.
if event.type == pygame.QUIT:
return False
elif event.type == pygame.KEYDOWN:
# Return False, if the user pressed Escape.
if event.key == pygame.K_ESCAPE:
return False
elif event.key == pygame.K_UP:
self.upArrow = True
elif event.key == pygame.K_DOWN:
self.downArrow = True
# some more code here ...
return True
def move_tank(self):
"""Here the tank will be rotated and driven."""
def run(self):
# Run until self.handle_events
# tells to close the demo
while self.handle_events():
# Draws the background
self.screen.blit(self.bgImage, (0,0))
# moves the tank into direction defined by
# self.[up|down|left|right]Arrow
self.move_tank()
# updates all Sprites and draws them to the screen
self.drawableObjects.update()
self.drawableObjects.draw(self.screen)
# flips the display buffers
pygame.display.flip()
self.tick()
That's easy, isn't it?
No comments:
Post a Comment