EzDevInfo.com

pygame interview questions

Top pygame frequently asked interview questions

Add scrolling to a platformer in pygame

Ok so I included the code for my project below, I'm just doing some experimenting with pygame on making a platformer. I'm trying to figure out how to do some very simple scrolling that follows the player, so the player is the center of the camera and it bounces/follows him. Can anyone help me?

import pygame
from pygame import *

WIN_WIDTH = 800
WIN_HEIGHT = 640
HALF_WIDTH = int(WIN_WIDTH / 2)
HALF_HEIGHT = int(WIN_HEIGHT / 2)

DISPLAY = (WIN_WIDTH, WIN_HEIGHT)
DEPTH = 32
FLAGS = 0
CAMERA_SLACK = 30

def main():
    global cameraX, cameraY
    pygame.init()
    screen = pygame.display.set_mode(DISPLAY, FLAGS, DEPTH)
    pygame.display.set_caption("Use arrows to move!")
    timer = pygame.time.Clock()

    up = down = left = right = running = False
    bg = Surface((32,32))
    bg.convert()
    bg.fill(Color("#000000"))
    entities = pygame.sprite.Group()
    player = Player(32, 32)
    platforms = []

    x = y = 0
    level = [
        "PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP",
        "P                                P",
        "P                                P",
        "P                                P",
        "P                                P",
        "P                                P",
        "P                                P",
        "P                                P",
        "P       PPPPPPPPPPP              P",
        "P                                P",
        "P                                P",
        "P                                P",
        "P                                P",
        "PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP",]
    # build the level
    for row in level:
        for col in row:
            if col == "P":
                p = Platform(x, y)
                platforms.append(p)
                entities.add(p)
            if col == "E":
                e = ExitBlock(x, y)
                platforms.append(e)
                entities.add(e)
            x += 32
        y += 32
        x = 0

    entities.add(player)

    while 1:
        timer.tick(60)

        for e in pygame.event.get():
            if e.type == QUIT: raise SystemExit, "QUIT"
            if e.type == KEYDOWN and e.key == K_ESCAPE:
                raise SystemExit, "ESCAPE"
            if e.type == KEYDOWN and e.key == K_UP:
                up = True
            if e.type == KEYDOWN and e.key == K_DOWN:
                down = True
            if e.type == KEYDOWN and e.key == K_LEFT:
                left = True
            if e.type == KEYDOWN and e.key == K_RIGHT:
                right = True
            if e.type == KEYDOWN and e.key == K_SPACE:
                running = True

            if e.type == KEYUP and e.key == K_UP:
                up = False
            if e.type == KEYUP and e.key == K_DOWN:
                down = False
            if e.type == KEYUP and e.key == K_RIGHT:
                right = False
            if e.type == KEYUP and e.key == K_LEFT:
                left = False
            if e.type == KEYUP and e.key == K_RIGHT:
                right = False

        # draw background
        for y in range(32):
            for x in range(32):
                screen.blit(bg, (x * 32, y * 32))

        # update player, draw everything else
        player.update(up, down, left, right, running, platforms)
        entities.draw(screen)

        pygame.display.update()

class Entity(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)

class Player(Entity):
    def __init__(self, x, y):
        Entity.__init__(self)
        self.xvel = 0
        self.yvel = 0
        self.onGround = False
        self.image = Surface((32,32))
        self.image.fill(Color("#0000FF"))
        self.image.convert()
        self.rect = Rect(x, y, 32, 32)

    def update(self, up, down, left, right, running, platforms):
        if up:
            # only jump if on the ground
            if self.onGround: self.yvel -= 10
        if down:
            pass
        if running:
            self.xvel = 12
        if left:
            self.xvel = -8
        if right:
            self.xvel = 8
        if not self.onGround:
            # only accelerate with gravity if in the air
            self.yvel += 0.3
            # max falling speed
            if self.yvel > 100: self.yvel = 100
        if not(left or right):
            self.xvel = 0
        # increment in x direction
        self.rect.left += self.xvel
        # do x-axis collisions
        self.collide(self.xvel, 0, platforms)
        # increment in y direction
        self.rect.top += self.yvel
        # assuming we're in the air
        self.onGround = False;
        # do y-axis collisions
        self.collide(0, self.yvel, platforms)

    def collide(self, xvel, yvel, platforms):
        for p in platforms:
            if pygame.sprite.collide_rect(self, p):
                if isinstance(p, ExitBlock):
                    pygame.event.post(pygame.event.Event(QUIT))
                if xvel > 0:
                    self.rect.right = p.rect.left
                    print "collide right"
                if xvel < 0:
                    self.rect.left = p.rect.right
                    print "collide left"
                if yvel > 0:
                    self.rect.bottom = p.rect.top
                    self.onGround = True
                    self.yvel = 0
                if yvel < 0:
                    self.rect.top = p.rect.bottom


class Platform(Entity):
    def __init__(self, x, y):
        Entity.__init__(self)
        self.image = Surface((32, 32))
        self.image.convert()
        self.image.fill(Color("#DDDDDD"))
        self.rect = Rect(x, y, 32, 32)

    def update(self):
        pass

class ExitBlock(Platform):
    def __init__(self, x, y):
        Platform.__init__(self, x, y)
        self.image.fill(Color("#0033FF"))

if __name__ == "__main__":
    main()

Source: (StackOverflow)

How to make a surface with a transparent background in pygame

Can someone give me some example code that creates a surface with a transparent background in pygame?


Source: (StackOverflow)

Advertisements

Does pyGame do 3d?

I can't seem to find the answer to this question anywhere. I realise that you have to use pyOpenGL or something similar to do openGL stuff, but I was wondering if its possible to do very basic 3d graphics without any other dependencies.


Source: (StackOverflow)

Best way to install pygame on OS X Lion?

I tried to install pygame via pip but this fails. Based on my google searches, it sounds like easy_install also fails.

I also checked out: http://www.pygame.org/wiki/MacLionCompile but the solution is incomplete.

I'm running python 2.7.1 bundled with Lion.

Suggestions? Appreciate the help.


Source: (StackOverflow)

Which Python user interface library can I use for 2D games?

I want to create a 2D game on Python with heavy user interface: windows, buttons, text input, etc. So far I've been using PyGame for a few simple games.

The game is a 2D MUD, with the standard rendering loop to draw stuff on the screen. I need the user interface to interact with the game entities like sales, blacksmith, etc.

I am looking for something like a mix of Pygame and wxPython/pyQT/pyGTK.

Which libraries can I use?


Source: (StackOverflow)

Is Python and pygame a good way to learn SDL? [closed]

If I want to move to C++ and SDL in the future, is Python and pygame a good way to learn SDL?


Source: (StackOverflow)

What can Pygame do in terms of graphics that wxPython can't?

I want to develop a very simple 2D game in Python. Pygame is the most popular library for game development in Python, but I'm already quite familiar with wxPython and feel comfortable using it. I've even written a Tetris clone in it, and it was pretty smooth.

I wonder, what does Pygame offer in terms of graphics (leaving sound aside, for a moment) that wxPython can't do ? Is it somehow simpler/faster to do graphics in Pygame than in wxPython ? Is it even more cross-platform ?

It looks like I'm missing something here, but I don't know what.


Source: (StackOverflow)

Solving "DLL load failed: %1 is not a valid Win32 application." for Pygame

I recently installed Python 3.1 and the Pygame module for Python 3.1 When I type import python in the console I get the following error:

Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    import pygame
  File "C:\Python31\lib\site-packages\pygame\__init__.py", line 95, in <module>
    from pygame.base import *
ImportError: DLL load failed: %1 is not a valid Win32 application.

Please help!


Source: (StackOverflow)

Differences between Python game libraries Pygame and Pyglet?

I've had some experience with Pygame, but there seems to be a lot of buzz around Pyglet these days.

How do these two libraries compare? What would be the advantage of using one over the other, both in features and ease of use?

Finally, would you say that one is more Pythonic than the other?


Source: (StackOverflow)

Unable to install Pygame using pip

I'm trying to install Pygame. I am running Windows 7 with Enthought Python Distribution. I successfully installed pip, but when I try to install Pygame using pip, I get the following error:

"Could not install requirement Pygame because of HTTP error HTTP error 400: Bad request for URL ..."

I can't find anything about this issue with a Google search, but I did find another Stack Overflow question that prompted the asker to use the following command:

pip install hg+http://bitbucket.org/pygame/pygame

This gave me the following error:

Cannot find command hg

I'm not sure what else to do, as everything I find with a Google search is for Mac, so I don't know how well I can follow those instructions on Windows.


Source: (StackOverflow)

Convert tuple to list and back

I'm currently working on a map editor for a game in pygame, using tile maps. The level is built up out of blocks in the following structure(though much larger):

level1 = (
         (1,1,1,1,1,1)
         (1,0,0,0,0,1)
         (1,0,0,0,0,1)
         (1,0,0,0,0,1)
         (1,0,0,0,0,1)
         (1,1,1,1,1,1))

where "1" is a block that's a wall and "0" is a block that's empty air.

The following code is basically the one handling the change of block type:

clicked = pygame.mouse.get_pressed()
if clicked[0] == 1:
    currLevel[((mousey+cameraY)/60)][((mousex+cameraX)/60)] = 1

But since the level is stored in a tuple, I'm unable to change the values of the different blocks. How do I go about changing the different values in the level in an easy manner?

Edit: Solved! Thank you guys


Source: (StackOverflow)

Pygame installation for Python 3.3

I am trying to import Pygame to use for my version of Python, 3.3. The downloads on the Pygame website only have Python 3.1 and 3.2. I cannot seem to be able to import Pygame though I thought I had it installed in the correct path. I have tried both the 3.1 and 3.2 Pygame downloads.

Is Pygame just not installed in the correct file path or is Pygame not compatible with my version of Python (3.3)?

I am running Windows 7 and here is the error:

Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
import pygame
File ".\pygame\__init__.py", line 95, in <module>
from pygame.base import *
ImportError: DLL load failed: The specified module could not be found.

Source: (StackOverflow)

Pygame water ripple effect

I have Googled for it but there are no ready scripts - as opposed to the same effect on Flash. I have checked the algorithm on The Water Effect Explained and also tested an implementation of the Perlin Noise, which provides a good simulation of the end of waves on a flat surface. I am looking for the same implementation found on several Flash Effects, based on mouseover/hover actions. This is targetting an interactive floor library, and I would enjoy moving away from Flash for this matter, particularly to avoid such easy reverse-engineering of the code - and yes, I know it could just use some ready-made flash code, but I would only use that as a last resort.

Has anyone seen a suitable implementation of this effect for Pygame (using OpenGL or not)?

EDIT: Can anyone provide a suitable implementation of this effect using OpenCV/OpenGL and Pygame?

The culprit here is the (code) interface to pass a list of values that will be sent from an external interpreter (tracker - not TUIO though) via Python. I have tried for some straight days but Pygame is not able to generate anything as fast as sheer C/C++ code (as used for the shaders in OpenGL), and my knowledge of C/C++ is null. So the target is to at least have that coming from Python code.

A good example, different from the Flash effect but that is still good is Water Simulation using Java applet.

(bounty is showing answers do not have enough detail since this was the closest to 'the OP is incapable of creating the code he wants to as he lacks fundamental skills and this answer will probably be of use to several people').


Source: (StackOverflow)

Start with pyglet or pygame? [closed]

I would like to know what is the best to start with, pyglet or pygame? Which one is faster and which one is more active?

I would also like to know if pyglet will get python 3 support, because I have read here that it might not be possible or it would take a long time.

Would it be better to choose pygame, because of the python 3 support, or should I go with pyglet?

Thanks.


Source: (StackOverflow)

Python display text w/ font & color?

Is there a way I can display text on a pygame window using python?

I need to display a bunch of live information that updates and would rather not make an image for each character I need.

Can I blit text to the screen?


Source: (StackOverflow)