Subscribe to MentalFloss - PyBlog        RSS Feed
-----

Pygame - Quick Tips

Icon Leave Comment
Placement

Greetings. If you're starting up a new game and you want to get some assets quickly placed to see what it looks like, you can block out parts of a mock screen and then add code to listen for the arrow keys and move that asset by incrementing correctly. Finally, add a key (I used return) to report its x,y position. From there, you'll know your boundaries.

import pygame
from pygame.locals import *


def game_on():
    pygame.init()
    screen = pygame.display.set_mode((296, 289))
    background = pygame.image.load('background_296x289.png')
    playground = pygame.image.load('dummy_blocks.png')
    
    in_game = True
    
    x = 20
    y = 15
    
    while in_game:
    
        for event in pygame.event.get():
            if event.type == QUIT:
                return
            if event.type == KEYDOWN:
                if event.key == K_DOWN:
                    y += 1
                if event.key == K_UP:
                    y -= 1
                if event.key == K_RETURN:
                    print 'x=%d,y=%d' % (x,y)
        
                
        screen.blit(background, (0,0))
        screen.blit(playground, (x,y))
        pygame.display.flip()

if __name__ == '__main__':
    game_on()



Posted Image

One thing you want to be careful about is your blit order. Remember -- the further away something is, the earlier it's blitted to screen.



Mousing

If you have a play area in your game that you would prefer not showing the mouse in, you can use pygame.mouse.set_visible() to toggle its visibility. A good game that this would be used for would be a breakout clone for instance.

To do it, just have a rect assigned to your play area and in your update loop, check if the mouse passes a collidepoint check.

    # game loop
    while True:
        if playground.rect.collidepoint(pyg.mouse.get_pos()):
            pyg.mouse.set_visible(False)
        else:
            pyg.mouse.set_visible(True)



Now the mouse will show except when you're in the play area.

0 Comments On This Entry

 

Trackbacks for this entry [ Trackback URL ]

There are no Trackbacks for this entry

December 2014

S M T W T F S
 123456
78910111213
14151617181920
2122232425 26 27
28293031   

Tags

    Recent Entries

    Recent Comments

    Search My Blog

    1 user(s) viewing

    1 Guests
    0 member(s)
    0 anonymous member(s)