Search Results

Search found 149 results on 6 pages for 'pygame'.

Page 1/6 | 1 2 3 4 5 6  | Next Page >

  • pygame double buffering

    - by BaldDude
    I am trying to use double buffering in pygame. What I'm trying to do is display a red then green screen, and switch from one to the other. Unfortunately, all I have is a black screen. I looked through many sites, but have been unable to find a solution. Any help would be appreciated. import pygame, sys from pygame.locals import * RED = (255, 0, 0) GREEN = ( 0, 255, 0) bob = 1 pygame.init() #DISPLAYSURF = pygame.display.set_mode((500, 400), 0, 32) DISPLAYSURF = pygame.display.set_mode((1920, 1080), pygame.OPENGL | pygame.DOUBLEBUF | pygame.HWSURFACE | pygame.FULLSCREEN) glClear(GL_COLOR_BUFFER_BIT) glMatrixMode(GL_MODELVIEW) glLoadIdentity() running = True while running: if bob==1: #pygame.draw.rect(DISPLAYSURF, RED, (0, 0, 1920, 1080)) #pygame.display.flip() glBegin(GL_QUADS) glColor3f(1.0, 0.0, 0.0) glVertex2f(-1.0, 1.0) glVertex2f(-1.0, -1.0) glVertex2f(1.0, -1.0) glVertex2f(1.0, 1.0) glEnd() pygame.dis bob = 0 else: #pygame.draw.rect(DISPLAYSURF, GREEN, (0, 0, 1920, 1080)) #pygame.display.flip() glBegin(GL_QUADS) glColor3f(0.0, 1.0, 0.0) glVertex2f(-1.0, 1.0) glVertex2f(-1.0, -1.0) glVertex2f(1.0, -1.0) glVertex2f(1.0, 1.0) glEnd() pygame.dis bob = 1 for event in pygame.event.get(): if event.type == pygame.QUIT: running = False elif event.type == KEYDOWN: if event.key == K_ESCAPE: running = False pygame.quit() sys.exit() I'm using Python 2.7 and my code need to be os independent. Thanks for your help.

    Read the article

  • Add collison detection to enemy sprites?

    - by xBroak
    i'd like to add the same collision detection used by the player sprite to the enemy sprites or 'creeps' ive added all the relevant code I can see yet collisons are still not being detected and handled, please find below the class, I have no idea what is wrong currently, the list of walls to collide with is 'wall_list' import pygame import pauseScreen as dm import re from pygame.sprite import Sprite from pygame import Rect, Color from random import randint, choice from vec2d import vec2d from simpleanimation import SimpleAnimation import displattxt black = (0,0,0) white = (255,255,255) blue = (0,0,255) green = (101,194,151) global currentEditTool currentEditTool = "Tree" global editMap editMap = False open('MapMaker.txt', 'w').close() def draw_background(screen, tile_img): screen.fill(black) img_rect = tile_img.get_rect() global rect rect = img_rect nrows = int(screen.get_height() / img_rect.height) + 1 ncols = int(screen.get_width() / img_rect.width) + 1 for y in range(nrows): for x in range(ncols): img_rect.topleft = (x * img_rect.width, y * img_rect.height) screen.blit(tile_img, img_rect) def changeTool(): if currentEditTool == "Tree": None elif currentEditTool == "Rock": None def pauseGame(): red = 255, 0, 0 green = 0,255, 0 blue = 0, 0,255 screen.fill(black) pygame.display.update() if editMap == False: choose = dm.dumbmenu(screen, [ 'Resume', 'Enable Map Editor', 'Quit Game'], 64,64,None,32,1.4,green,red) if choose == 0: print("hi") elif choose ==1: global editMap editMap = True elif choose ==2: print("bob") elif choose ==3: print("bob") elif choose ==4: print("bob") else: None else: choose = dm.dumbmenu(screen, [ 'Resume', 'Disable Map Editor', 'Quit Game'], 64,64,None,32,1.4,green,red) if choose == 0: print("Resume") elif choose ==1: print("Dis ME") global editMap editMap = False elif choose ==2: print("bob") elif choose ==3: print("bob") elif choose ==4: print("bob") else: None class Wall(pygame.sprite.Sprite): # Constructor function def __init__(self,x,y,width,height): pygame.sprite.Sprite.__init__(self) self.image = pygame.Surface([width, height]) self.image.fill(green) self.rect = self.image.get_rect() self.rect.y = y self.rect.x = x class insertTree(pygame.sprite.Sprite): def __init__(self,x,y,width,height, typ): pygame.sprite.Sprite.__init__(self) self.image = pygame.image.load("images/map/tree.png").convert() self.image.set_colorkey(white) self.rect = self.image.get_rect() self.rect.y = y self.rect.x = x class insertRock(pygame.sprite.Sprite): def __init__(self,x,y,width,height, typ): pygame.sprite.Sprite.__init__(self) self.image = pygame.image.load("images/map/rock.png").convert() self.image.set_colorkey(white) self.rect = self.image.get_rect() self.rect.y = y self.rect.x = x class Creep(pygame.sprite.Sprite): """ A creep sprite that bounces off walls and changes its direction from time to time. """ change_x=0 change_y=0 def __init__( self, screen, creep_image, explosion_images, field, init_position, init_direction, speed): """ Create a new Creep. screen: The screen on which the creep lives (must be a pygame Surface object, such as pygame.display) creep_image: Image (surface) object for the creep explosion_images: A list of image objects for the explosion animation. field: A Rect specifying the 'playing field' boundaries. The Creep will bounce off the 'walls' of this field. init_position: A vec2d or a pair specifying the initial position of the creep on the screen. init_direction: A vec2d or a pair specifying the initial direction of the creep. Must have an angle that is a multiple of 45 degres. speed: Creep speed, in pixels/millisecond (px/ms) """ Sprite.__init__(self) self.screen = screen self.speed = speed self.field = field self.rect = creep_image.get_rect() # base_image holds the original image, positioned to # angle 0. # image will be rotated. # self.base_image = creep_image self.image = self.base_image self.explosion_images = explosion_images # A vector specifying the creep's position on the screen # self.pos = vec2d(init_position) # The direction is a normalized vector # self.direction = vec2d(init_direction).normalized() self.state = Creep.ALIVE self.health = 15 def is_alive(self): return self.state in (Creep.ALIVE, Creep.EXPLODING) def changespeed(self,x,y): self.change_x+=x self.change_y+=y def update(self, time_passed, walls): """ Update the creep. time_passed: The time passed (in ms) since the previous update. """ if self.state == Creep.ALIVE: # Maybe it's time to change the direction ? # self._change_direction(time_passed) # Make the creep point in the correct direction. # Since our direction vector is in screen coordinates # (i.e. right bottom is 1, 1), and rotate() rotates # counter-clockwise, the angle must be inverted to # work correctly. # self.image = pygame.transform.rotate( self.base_image, -self.direction.angle) # Compute and apply the displacement to the position # vector. The displacement is a vector, having the angle # of self.direction (which is normalized to not affect # the magnitude of the displacement) # displacement = vec2d( self.direction.x * self.speed * time_passed, self.direction.y * self.speed * time_passed) self.pos += displacement # When the image is rotated, its size is changed. # We must take the size into account for detecting # collisions with the walls. # self.image_w, self.image_h = self.image.get_size() bounds_rect = self.field.inflate( -self.image_w, -self.image_h) if self.pos.x < bounds_rect.left: self.pos.x = bounds_rect.left self.direction.x *= -1 elif self.pos.x > bounds_rect.right: self.pos.x = bounds_rect.right self.direction.x *= -1 elif self.pos.y < bounds_rect.top: self.pos.y = bounds_rect.top self.direction.y *= -1 elif self.pos.y > bounds_rect.bottom: self.pos.y = bounds_rect.bottom self.direction.y *= -1 # collision detection old_x=bounds_rect.left new_x=old_x+self.direction.x bounds_rect.left = new_x # hit a wall? collide = pygame.sprite.spritecollide(self, walls, False) if collide: # yes bounds_rect.left=old_x old_y=self.pos.y new_y=old_y+self.direction.y self.pos.y = new_y collide = pygame.sprite.spritecollide(self, walls, False) if collide: # yes self.pos.y=old_y elif self.state == Creep.EXPLODING: if self.explode_animation.active: self.explode_animation.update(time_passed) else: self.state = Creep.DEAD self.kill() elif self.state == Creep.DEAD: pass #------------------ PRIVATE PARTS ------------------# # States the creep can be in. # # ALIVE: The creep is roaming around the screen # EXPLODING: # The creep is now exploding, just a moment before dying. # DEAD: The creep is dead and inactive # (ALIVE, EXPLODING, DEAD) = range(3) _counter = 0 def _change_direction(self, time_passed): """ Turn by 45 degrees in a random direction once per 0.4 to 0.5 seconds. """ self._counter += time_passed if self._counter > randint(400, 500): self.direction.rotate(45 * randint(-1, 1)) self._counter = 0 def _point_is_inside(self, point): """ Is the point (given as a vec2d) inside our creep's body? """ img_point = point - vec2d( int(self.pos.x - self.image_w / 2), int(self.pos.y - self.image_h / 2)) try: pix = self.image.get_at(img_point) return pix[3] > 0 except IndexError: return False def _decrease_health(self, n): """ Decrease my health by n (or to 0, if it's currently less than n) """ self.health = max(0, self.health - n) if self.health == 0: self._explode() def _explode(self): """ Starts the explosion animation that ends the Creep's life. """ self.state = Creep.EXPLODING pos = ( self.pos.x - self.explosion_images[0].get_width() / 2, self.pos.y - self.explosion_images[0].get_height() / 2) self.explode_animation = SimpleAnimation( self.screen, pos, self.explosion_images, 100, 300) global remainingCreeps remainingCreeps-=1 if remainingCreeps == 0: print("all dead") def draw(self): """ Blit the creep onto the screen that was provided in the constructor. """ if self.state == Creep.ALIVE: # The creep image is placed at self.pos. To allow for # smooth movement even when the creep rotates and the # image size changes, its placement is always # centered. # self.draw_rect = self.image.get_rect().move( self.pos.x - self.image_w / 2, self.pos.y - self.image_h / 2) self.screen.blit(self.image, self.draw_rect) # The health bar is 15x4 px. # health_bar_x = self.pos.x - 7 health_bar_y = self.pos.y - self.image_h / 2 - 6 self.screen.fill( Color('red'), (health_bar_x, health_bar_y, 15, 4)) self.screen.fill( Color('green'), ( health_bar_x, health_bar_y, self.health, 4)) elif self.state == Creep.EXPLODING: self.explode_animation.draw() elif self.state == Creep.DEAD: pass def mouse_click_event(self, pos): """ The mouse was clicked in pos. """ if self._point_is_inside(vec2d(pos)): self._decrease_health(3) #begin new player class Player(pygame.sprite.Sprite): change_x=0 change_y=0 frame = 0 def __init__(self,x,y): pygame.sprite.Sprite.__init__(self) # LOAD PLATER IMAGES # Set height, width self.images = [] for i in range(1,17): img = pygame.image.load("images/player/" + str(i)+".png").convert() #player images img.set_colorkey(white) self.images.append(img) self.image = self.images[0] self.rect = self.image.get_rect() self.rect.y = y self.rect.x = x self.health = 15 self.image_w, self.image_h = self.image.get_size() health_bar_x = self.rect.x - 7 health_bar_y = self.rect.y - self.image_h / 2 - 6 screen.fill( Color('red'), (health_bar_x, health_bar_y, 15, 4)) screen.fill( Color('green'), ( health_bar_x, health_bar_y, self.health, 4)) def changespeed(self,x,y): self.change_x+=x self.change_y+=y def _decrease_health(self, n): """ Decrease my health by n (or to 0, if it's currently less than n) """ self.health = max(0, self.health - n) if self.health == 0: self._explode() def update(self,walls): # collision detection old_x=self.rect.x new_x=old_x+self.change_x self.rect.x = new_x # hit a wall? collide = pygame.sprite.spritecollide(self, walls, False) if collide: # yes self.rect.x=old_x old_y=self.rect.y new_y=old_y+self.change_y self.rect.y = new_y collide = pygame.sprite.spritecollide(self, walls, False) if collide: # yes self.rect.y=old_y # right to left if self.change_x < 0: self.frame += 1 if self.frame > 3*4: self.frame = 0 # Grab the image, divide by 4 # every 4 frames. self.image = self.images[self.frame//4] # Move left to right. # images 4...7 instead of 0...3. if self.change_x > 0: self.frame += 1 if self.frame > 3*4: self.frame = 0 self.image = self.images[self.frame//4+4] if self.change_y > 0: self.frame += 1 if self.frame > 3*4: self.frame = 0 self.image = self.images[self.frame//4+4+4] if self.change_y < 0: self.frame += 1 if self.frame > 3*4: self.frame = 0 self.image = self.images[self.frame//4+4+4+4] score = 0 # initialize pyGame pygame.init() # 800x600 sized screen global screen screen = pygame.display.set_mode([800, 600]) screen.fill(black) #bg_tile_img = pygame.image.load('images/map/grass.png').convert_alpha() #draw_background(screen, bg_tile_img) #pygame.display.flip() # Set title pygame.display.set_caption('Test') #background = pygame.Surface(screen.get_size()) #background = background.convert() #background.fill(black) # Create the player player = Player( 50,50 ) player.rect.x=50 player.rect.y=50 movingsprites = pygame.sprite.RenderPlain() movingsprites.add(player) # Make the walls. (x_pos, y_pos, width, height) global wall_list wall_list=pygame.sprite.RenderPlain() wall=Wall(0,0,10,600) # left wall wall_list.add(wall) wall=Wall(10,0,790,10) # top wall wall_list.add(wall) #wall=Wall(10,200,100,10) # poke wall wall_list.add(wall) wall=Wall(790,0,10,600) #(x,y,thickness, height) wall_list.add(wall) wall=Wall(10,590,790,10) #(x,y,thickness, height) wall_list.add(wall) f = open('MapMaker.txt') num_lines = sum(1 for line in f) print(num_lines) lineCount = 0 with open("MapMaker.txt") as infile: for line in infile: f = open('MapMaker.txt') print(line) coords = line.split(',') #print(coords[0]) #print(coords[1]) #print(coords[2]) #print(coords[3]) #print(coords[4]) if "tree" in line: print("tree in") wall=insertTree(int(coords[0]),int(coords[1]), int(coords[2]),int(coords[3]),coords[4]) wall_list.add(wall) elif "rock" in line: print("rock in") wall=insertRock(int(coords[0]),int(coords[1]), int(coords[2]),int(coords[3]),coords[4] ) wall_list.add(wall) width = 20 height = 540 height = height - 48 for i in range(0,23): width = width + 32 name = insertTree(width,540,790,10,"tree") #wall_list.add(name) name = insertTree(width,height,690,10,"tree") #wall_list.add(name) CREEP_SPAWN_TIME = 200 # frames creep_spawn = CREEP_SPAWN_TIME clock = pygame.time.Clock() bg_tile_img = pygame.image.load('images/map/grass.png').convert() img_rect = bg_tile_img FIELD_RECT = Rect(50, 50, 700, 500) CREEP_FILENAMES = [ 'images/player/1.png', 'images/player/1.png', 'images/player/1.png'] N_CREEPS = 3 creep_images = [ pygame.image.load(filename).convert_alpha() for filename in CREEP_FILENAMES] explosion_img = pygame.image.load('images/map/tree.png').convert_alpha() explosion_images = [ explosion_img, pygame.transform.rotate(explosion_img, 90)] creeps = pygame.sprite.RenderPlain() done = False #bg_tile_img = pygame.image.load('images/map/grass.png').convert() #draw_background(screen, bg_tile_img) totalCreeps = 0 remainingCreeps = 3 while done == False: creep_images = pygame.image.load("images/player/1.png").convert() creep_images.set_colorkey(white) draw_background(screen, bg_tile_img) if len(creeps) != N_CREEPS: if totalCreeps < N_CREEPS: totalCreeps = totalCreeps + 1 print(totalCreeps) creeps.add( Creep( screen=screen, creep_image=creep_images, explosion_images=explosion_images, field=FIELD_RECT, init_position=( randint(FIELD_RECT.left, FIELD_RECT.right), randint(FIELD_RECT.top, FIELD_RECT.bottom)), init_direction=(choice([-1, 1]), choice([-1, 1])), speed=0.01)) for creep in creeps: creep.update(60,wall_list) creep.draw() for event in pygame.event.get(): if event.type == pygame.QUIT: done=True if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: player.changespeed(-2,0) creep.changespeed(-2,0) if event.key == pygame.K_RIGHT: player.changespeed(2,0) creep.changespeed(2,0) if event.key == pygame.K_UP: player.changespeed(0,-2) creep.changespeed(0,-2) if event.key == pygame.K_DOWN: player.changespeed(0,2) creep.changespeed(0,2) if event.key == pygame.K_ESCAPE: pauseGame() if event.key == pygame.K_1: global currentEditTool currentEditTool = "Tree" changeTool() if event.key == pygame.K_2: global currentEditTool currentEditTool = "Rock" changeTool() if event.type == pygame.KEYUP: if event.key == pygame.K_LEFT: player.changespeed(2,0) creep.changespeed(2,0) if event.key == pygame.K_RIGHT: player.changespeed(-2,0) creep.changespeed(-2,0) if event.key == pygame.K_UP: player.changespeed(0,2) creep.changespeed(0,2) if event.key == pygame.K_DOWN: player.changespeed(0,-2) creep.changespeed(0,-2) if event.type == pygame.MOUSEBUTTONDOWN and pygame.mouse.get_pressed()[0]: for creep in creeps: creep.mouse_click_event(pygame.mouse.get_pos()) if editMap == True: x,y = pygame.mouse.get_pos() if currentEditTool == "Tree": name = insertTree(x-10,y-25, 10 , 10, "tree") wall_list.add(name) wall_list.draw(screen) f = open('MapMaker.txt', "a+") image = pygame.image.load("images/map/tree.png").convert() screen.blit(image, (30,10)) pygame.display.flip() f.write(str(x) + "," + str(y) + ",790,10, tree\n") #f.write("wall=insertTree(" + str(x) + "," + str(y) + ",790,10)\nwall_list.add(wall)\n") elif currentEditTool == "Rock": name = insertRock(x-10,y-25, 10 , 10,"rock") wall_list.add(name) wall_list.draw(screen) f = open('MapMaker.txt', "a+") f.write(str(x) + "," + str(y) + ",790,10,rock\n") #f.write("wall=insertRock(" + str(x) + "," + str(y) + ",790,10)\nwall_list.add(wall)\n") else: None #pygame.display.flip() player.update(wall_list) movingsprites.draw(screen) wall_list.draw(screen) pygame.display.flip() clock.tick(60) pygame.quit()

    Read the article

  • Pygame surfaces and their Rects

    - by Jaka Novak
    I am trying to understand how pygame surfaces work. I am confused about Rect position of Surface object. If I try blit surface on screen at some position then Surface is drawn at right position, but Rect of the surface is still at position (0, 0)... I tried write my own surface class with new rect, but i am not sure if is that right solution. My goal is that i could move surface like image with rect.move() or something like that. If there is any solution to do that i would be happy to read it. Thanks for answer and time for reading this awful English If helps i write some code for better understanding my problem. (run it first, and then uncomment two lines of code and run again to see the diference): import pygame from pygame.locals import * class SurfaceR(pygame.Surface): def __init__(self, size, position): pygame.Surface.__init__(self, size) self.rect = pygame.Rect(position, size) self.position = position self.size = size def get_rect(self): return self.rect def main(): pygame.init() screen = pygame.display.set_mode((640, 480)) pygame.display.set_caption("Screen!?") clock = pygame.time.Clock() fps = 30 white = (255, 255, 255) red = (255, 0, 0) green = (0, 255, 0) blue = (0, 0, 255) surface = pygame.Surface((70,200)) surface.fill(red) surface_re = SurfaceR((300, 50), (100, 300)) surface_re.fill(blue) while True: for event in pygame.event.get(): if event.type == QUIT: return 0 screen.blit(surface, (100,50)) screen.blit(surface_re, surface_re.position) #pygame.draw.rect(screen, white, surface.get_rect()) #pygame.draw.rect(screen, white, surface_re.get_rect()) pygame.display.update() clock.tick(fps) if __name__ == "__main__": main()

    Read the article

  • Pygame: Save a list of objects/classes/surfaces

    - by Sam Tubb
    I am working on a game, in which you can create mazes. You place blocks on a 16x16 grid, while choosing from a variety of block to make the level with. Whenever you create a block, it adds this class: class Block(object): def __init__(self,x,y,spr): self.x=x self.y=y self.sprite=spr self.rect=self.sprite.get_rect(x=self.x,y=self.y) to a list called instances. I tried shelving it to a .bin file, but it returns some error dealing with surfaces. How can I go about saving and loading levels? Any help is appreciated! :) Here is the whole code for reference: import pygame from pygame.locals import * #initstuff pygame.init() screen=pygame.display.set_mode((640,480)) pygame.display.set_caption('PiMaze') instances=[] #loadsprites menuspr=pygame.image.load('images/menu.png').convert() b1spr=pygame.image.load('images/b1.png').convert() b2spr=pygame.image.load('images/b2.png').convert() currentbspr=b1spr curspr=pygame.image.load('images/curs.png').convert() curspr.set_colorkey((0,255,0)) #menu menuspr.set_alpha(185) menurect=menuspr.get_rect(x=-260,y=4) class MenuItem(object): def __init__(self,pos,spr): self.x=pos[0] self.y=pos[1] self.sprite=spr self.pos=(self.x,self.y) self.rect=self.sprite.get_rect(x=self.x,y=self.y) class Block(object): def __init__(self,x,y,spr): self.x=x self.y=y self.sprite=spr self.rect=self.sprite.get_rect(x=self.x,y=self.y) while True: #menu items b1menu=b1spr.get_rect(x=menurect.left+32,y=48) b2menu=b2spr.get_rect(x=menurect.left+64,y=48) menuitems=[MenuItem(b1menu,b1spr),MenuItem(b2menu,b2spr)] screen.fill((20,30,85)) mse=pygame.mouse.get_pos() key=pygame.key.get_pressed() placepos=((mse[0]/16)*16,(mse[1]/16)*16) if key[K_q]: if mse[0]<260: if menurect.right<255: menurect.right+=1 else: if menurect.left>-260: menurect.left-=1 else: if menurect.left>-260: menurect.left-=1 for e in pygame.event.get(): if e.type==QUIT: exit() if menurect.right<100: if e.type==MOUSEBUTTONUP: if e.button==1: to_remove = [i for i in instances if i.rect.collidepoint(placepos)] for i in to_remove: instances.remove(i) if not to_remove: instances.append(Block(placepos[0],placepos[1],currentbspr)) for i in instances: screen.blit(i.sprite,i.rect) if not key[K_q]: screen.blit(curspr,placepos) screen.blit(menuspr,menurect) for item in menuitems: screen.blit(item.sprite,item.pos) if item.rect.collidepoint(mse): if pygame.mouse.get_pressed()==(1,0,0): currentbspr=item.sprite pygame.draw.rect(screen, ((255,0,0)), item, 1) pygame.display.flip()

    Read the article

  • Splitting Pygame functionality between classes or modules?

    - by sec_goat
    I am attempting to make my pygame application more modular so that different functionalities are split up into different classes and modules. I am having some trouble getting pygame to allow me to draw or load images in secondary classes when the display has been set and pygame.init() has been done in my main class. I have typically used C# and XNA to accomplish this sort of behavior, but this time I need to use python. How do I init pygame in class1, then create an instance of class2 which loads and converts() images. I have tried pygame.init() in class 2 but then it tells me no display mode has been set, when it has been set in class1. I am under the impression i do not wnat to create multiple pygame.displays as that gets problematic I am probably missing something pythonic and simple but I am not sure what. How do I create a Display class, init python and then have other modules do my work like loading images, fonts etc.? here is the simplest version of what I am doing: class1: def __init__(self): self.screen = pygame.display.set_mode((600,400)) self.imageLoader = class2() class2: def __init__(self): self.images = ['list of images'] def load_images(): self.images = os.listdir('./images/') #get all images in the images directory for img in self.images: #read all images in the directory and load them into pygame new_img = pygame.image.load(os.path.join('images', img)).convert() scale_img = pygame.transform.scale(new_img, (pygame.display.Info().current_w, pygame.display.Info().current_h)) self.images.append(scale_img) if __name__ == "__main__": c1 = class1() c1.imageLoader.load_images() Of course when it tries to load an convert the images it tells me pygame has not been initialized, so i throw in a pygame.init() in class2 ( i have heard it is safe to init multiple times) and then the error goes to pygame.error: No video mode has been set

    Read the article

  • Pygame Import Error, Python 3.2

    - by Treb Nicholas
    I'm having an issue with the Pygame module. I run Python 3.2 and installed the respective Pygame file, but now when I try to import it in the IDLE, it gives me this error: import pygame Traceback (most recent call last): File "", line 1, in import pygame File "C:\Python32\lib\site-packages\pygame__init__.py", line 95, in from pygame.base import * ImportError: DLL load failed: %1 is not a valid Win32 application. Any help will be appreciated.

    Read the article

  • pygame.Rect around circle

    - by geekkid
    I'm trying to make a pong game in pygame , but i can't figure out how to but a ball circle , which i can create with pygame.draw.circle into a pygame.Rect object so i can use the colliderect function and manipulate the ball's position. For example, with rectangles, i can do something like this : rect = pygame.Rect(255, 255, 100, 100) pygame.draw.rect(screen, yellow, rect) and then when i change the pygame.Rect object position , the drawing primitives position also changes. How can the same effect be achieved when i want to draw a circle, instead of a rectangle? Thank you.

    Read the article

  • Pygame camera follow in a 2d tile game

    - by Pipyaddict
    import pygame, sys from pygame.locals import * pygame.init() size = width, height = 480,320 screen = pygame.display.set_mode(size) r = 0 bif = pygame.image.load("map5.png") pygame.display.set_caption("Pygame 2D RPG !") x,y=0,0 movex, movey=0,0 character="boy.png" player=pygame.image.load(character).convert_alpha() while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type==KEYDOWN: if event.key==K_a: movex=-1 elif event.key==K_d: movex=+1 elif event.key==K_w: movey=-1 elif event.key==K_s: movey=+1 if event.type==KEYUP: if event.key==K_a: movex=0 elif event.key==K_d: movex=0 elif event.key==K_w: movey=0 elif event.key==K_s: movey=0 x+=movex y+=movey screen.fill((r,0,0)) screen.blit(bif,(0,0)) screen.blit(player,(x,y)) pygame.display.flip() Everything works fine except I was wondering how on earth I was going to be able to move the camera where the player goes sorry that I can't show you the map file as you can't add images to it. But Thanks for your time The map is here: https://dl.dropboxusercontent.com/u/110087275/2d%20pygame/map5.png And finally the code is here: https://dl.dropboxusercontent.com/u/110087275/2d%20pygame/2d_pygame.py Thanks again for your time and effort!!!!!

    Read the article

  • Help getting frame rate (fps) up in Python + Pygame

    - by Jordan Magnuson
    I am working on a little card-swapping world-travel game that I sort of envision as a cross between Bejeweled and the 10 Days geography board games. So far the coding has been going okay, but the frame rate is pretty bad... currently I'm getting low 20's on my Core 2 Duo. This is a problem since I'm creating the game for Intel's March developer competition, which is squarely aimed at netbooks packing underpowered Atom processors. Here's a screen from the game: ![www.necessarygames.com/my_games/betraveled/betraveled-fps.png][1] I am very new to Python and Pygame (this is the first thing I've used them for), and am sadly lacking in formal CS training... which is to say that I think there are probably A LOT of bad practices going on in my code, and A LOT that could be optimized. If some of you older Python hands wouldn't mind taking a look at my code and seeing if you can't find any obvious areas for optimization, I would be extremely grateful. You can download the full source code here: http://www.necessarygames.com/my_games/betraveled/betraveled_src0328.zip Compiled exe here: www.necessarygames.com/my_games/betraveled/betraveled_src0328.zip One thing I am concerned about is my event manager, which I feel may have some performance wholes in it, and another thing is my rendering... I'm pretty much just blitting everything to the screen all the time (see the render routines in my game_components.py below); I recently found out that you should only update the areas of the screen that have changed, but I'm still foggy on how that accomplished exactly... could this be a huge performance issue? Any thoughts are much appreciated! As usual, I'm happy to "tip" you for your time and energy via PayPal. Jordan Here are some bits of the source: Main.py #Remote imports import pygame from pygame.locals import * #Local imports import config import rooms from event_manager import * from events import * class RoomController(object): """Controls which room is currently active (eg Title Screen)""" def __init__(self, screen, ev_manager): self.room = None self.screen = screen self.ev_manager = ev_manager self.ev_manager.register_listener(self) self.room = self.set_room(config.room) def set_room(self, room_const): #Unregister old room from ev_manager if self.room: self.room.ev_manager.unregister_listener(self.room) self.room = None #Set new room based on const if room_const == config.TITLE_SCREEN: return rooms.TitleScreen(self.screen, self.ev_manager) elif room_const == config.GAME_MODE_ROOM: return rooms.GameModeRoom(self.screen, self.ev_manager) elif room_const == config.GAME_ROOM: return rooms.GameRoom(self.screen, self.ev_manager) elif room_const == config.HIGH_SCORES_ROOM: return rooms.HighScoresRoom(self.screen, self.ev_manager) def notify(self, event): if isinstance(event, ChangeRoomRequest): if event.game_mode: config.game_mode = event.game_mode self.room = self.set_room(event.new_room) def render(self, surface): self.room.render(surface) #Run game def main(): pygame.init() screen = pygame.display.set_mode(config.screen_size) ev_manager = EventManager() spinner = CPUSpinnerController(ev_manager) room_controller = RoomController(screen, ev_manager) pygame_event_controller = PyGameEventController(ev_manager) spinner.run() # this runs the main function if this script is called to run. # If it is imported as a module, we don't run the main function. if __name__ == "__main__": main() event_manager.py #Remote imports import pygame from pygame.locals import * #Local imports import config from events import * def debug( msg ): print "Debug Message: " + str(msg) class EventManager: #This object is responsible for coordinating most communication #between the Model, View, and Controller. def __init__(self): from weakref import WeakKeyDictionary self.listeners = WeakKeyDictionary() self.eventQueue= [] self.gui_app = None #---------------------------------------------------------------------- def register_listener(self, listener): self.listeners[listener] = 1 #---------------------------------------------------------------------- def unregister_listener(self, listener): if listener in self.listeners: del self.listeners[listener] #---------------------------------------------------------------------- def post(self, event): if isinstance(event, MouseButtonLeftEvent): debug(event.name) #NOTE: copying the list like this before iterating over it, EVERY tick, is highly inefficient, #but currently has to be done because of how new listeners are added to the queue while it is running #(eg when popping cards from a deck). Should be changed. See: http://dr0id.homepage.bluewin.ch/pygame_tutorial08.html #and search for "Watch the iteration" for listener in list(self.listeners): #NOTE: If the weakref has died, it will be #automatically removed, so we don't have #to worry about it. listener.notify(event) #------------------------------------------------------------------------------ class PyGameEventController: """...""" def __init__(self, ev_manager): self.ev_manager = ev_manager self.ev_manager.register_listener(self) self.input_freeze = False #---------------------------------------------------------------------- def notify(self, incoming_event): if isinstance(incoming_event, UserInputFreeze): self.input_freeze = True elif isinstance(incoming_event, UserInputUnFreeze): self.input_freeze = False elif isinstance(incoming_event, TickEvent): #Share some time with other processes, so we don't hog the cpu pygame.time.wait(5) #Handle Pygame Events for event in pygame.event.get(): #If this event manager has an associated PGU GUI app, notify it of the event if self.ev_manager.gui_app: self.ev_manager.gui_app.event(event) #Standard event handling for everything else ev = None if event.type == QUIT: ev = QuitEvent() elif event.type == pygame.MOUSEBUTTONDOWN and not self.input_freeze: if event.button == 1: #Button 1 pos = pygame.mouse.get_pos() ev = MouseButtonLeftEvent(pos) elif event.type == pygame.MOUSEMOTION: pos = pygame.mouse.get_pos() ev = MouseMoveEvent(pos) #Post event to event manager if ev: self.ev_manager.post(ev) #------------------------------------------------------------------------------ class CPUSpinnerController: def __init__(self, ev_manager): self.ev_manager = ev_manager self.ev_manager.register_listener(self) self.clock = pygame.time.Clock() self.cumu_time = 0 self.keep_going = True #---------------------------------------------------------------------- def run(self): if not self.keep_going: raise Exception('dead spinner') while self.keep_going: time_passed = self.clock.tick() fps = self.clock.get_fps() self.cumu_time += time_passed self.ev_manager.post(TickEvent(time_passed, fps)) if self.cumu_time >= 1000: self.cumu_time = 0 self.ev_manager.post(SecondEvent()) pygame.quit() #---------------------------------------------------------------------- def notify(self, event): if isinstance(event, QuitEvent): #this will stop the while loop from running self.keep_going = False rooms.py #Remote imports import pygame #Local imports import config import continents from game_components import * from my_gui import * from pgu import high class Room(object): def __init__(self, screen, ev_manager): self.screen = screen self.ev_manager = ev_manager self.ev_manager.register_listener(self) def notify(self, event): if isinstance(event, TickEvent): pygame.display.set_caption('FPS: ' + str(int(event.fps))) self.render(self.screen) pygame.display.update() def get_highs_table(self): fname = 'high_scores.txt' highs_table = None config.all_highs = high.Highs(fname) if config.game_mode == config.TIME_CHALLENGE: if config.difficulty == config.EASY: highs_table = config.all_highs['time_challenge_easy'] if config.difficulty == config.MED_DIF: highs_table = config.all_highs['time_challenge_med'] if config.difficulty == config.HARD: highs_table = config.all_highs['time_challenge_hard'] if config.difficulty == config.SUPER: highs_table = config.all_highs['time_challenge_super'] elif config.game_mode == config.PLAN_AHEAD: pass return highs_table class TitleScreen(Room): def __init__(self, screen, ev_manager): Room.__init__(self, screen, ev_manager) self.background = pygame.image.load('assets/images/interface/background.jpg').convert() #Initialize #--------------------------------------- self.gui_form = gui.Form() self.gui_app = gui.App(config.gui_theme) self.ev_manager.gui_app = self.gui_app c = gui.Container(align=0,valign=0) #Quit Button #--------------------------------------- b = StartGameButton(ev_manager=self.ev_manager) c.add(b, 0, 0) self.gui_app.init(c) def render(self, surface): surface.blit(self.background, (0, 0)) #GUI self.gui_app.paint(surface) class GameModeRoom(Room): def __init__(self, screen, ev_manager): Room.__init__(self, screen, ev_manager) self.background = pygame.image.load('assets/images/interface/background.jpg').convert() self.create_gui() #Create pgu gui elements def create_gui(self): #Setup #--------------------------------------- self.gui_form = gui.Form() self.gui_app = gui.App(config.gui_theme) self.ev_manager.gui_app = self.gui_app c = gui.Container(align=0,valign=-1) #Mode Relaxed Button #--------------------------------------- b = GameModeRelaxedButton(ev_manager=self.ev_manager) self.b = b print b.rect c.add(b, 0, 200) #Mode Time Challenge Button #--------------------------------------- b = TimeChallengeButton(ev_manager=self.ev_manager) self.b = b print b.rect c.add(b, 0, 250) #Mode Think Ahead Button #--------------------------------------- # b = PlanAheadButton(ev_manager=self.ev_manager) # self.b = b # print b.rect # c.add(b, 0, 300) #Initialize #--------------------------------------- self.gui_app.init(c) def render(self, surface): surface.blit(self.background, (0, 0)) #GUI self.gui_app.paint(surface) class GameRoom(Room): def __init__(self, screen, ev_manager): Room.__init__(self, screen, ev_manager) #Game mode #--------------------------------------- self.new_board_timer = None self.game_mode = config.game_mode config.current_highs = self.get_highs_table() self.highs_dialog = None self.game_over = False #Images #--------------------------------------- self.background = pygame.image.load('assets/images/interface/game screen2-1.jpg').convert() self.logo = pygame.image.load('assets/images/interface/logo_small.png').convert_alpha() self.game_over_text = pygame.image.load('assets/images/interface/text_game_over.png').convert_alpha() self.trip_complete_text = pygame.image.load('assets/images/interface/text_trip_complete.png').convert_alpha() self.zoom_game_over = None self.zoom_trip_complete = None self.fade_out = None #Text #--------------------------------------- self.font = pygame.font.Font(config.font_sans, config.interface_font_size) #Create game components #--------------------------------------- self.continent = self.set_continent(config.continent) self.board = Board(config.board_size, self.ev_manager) self.deck = Deck(self.ev_manager, self.continent) self.map = Map(self.continent) self.longest_trip = 0 #Set pos of game components #--------------------------------------- board_pos = (SCREEN_MARGIN[0], 109) self.board.set_pos(board_pos) map_pos = (config.screen_size[0] - self.map.size[0] - SCREEN_MARGIN[0], 57); self.map.set_pos(map_pos) #Trackers #--------------------------------------- self.game_clock = Chrono(self.ev_manager) self.swap_counter = 0 self.level = 0 #Create gui #--------------------------------------- self.create_gui() #Create initial board #--------------------------------------- self.new_board = self.deck.deal_new_board(self.board) self.ev_manager.post(NewBoardComplete(self.new_board)) def set_continent(self, continent_const): #Set continent based on const if continent_const == config.EUROPE: return continents.Europe() if continent_const == config.AFRICA: return continents.Africa() else: raise Exception('Continent constant not recognized') #Create pgu gui elements def create_gui(self): #Setup #--------------------------------------- self.gui_form = gui.Form() self.gui_app = gui.App(config.gui_theme) self.ev_manager.gui_app = self.gui_app c = gui.Container(align=-1,valign=-1) #Timer Progress bar #--------------------------------------- self.timer_bar = None self.time_increase = None self.minutes_left = None self.seconds_left = None self.timer_text = None if self.game_mode == config.TIME_CHALLENGE: self.time_increase = config.time_challenge_start_time self.timer_bar = gui.ProgressBar(config.time_challenge_start_time,0,config.max_time_bank,width=306) c.add(self.timer_bar, 172, 57) #Connections Progress bar #--------------------------------------- self.connections_bar = None self.connections_bar = gui.ProgressBar(0,0,config.longest_trip_needed,width=306) c.add(self.connections_bar, 172, 83) #Quit Button #--------------------------------------- b = QuitButton(ev_manager=self.ev_manager) c.add(b, 950, 20) #Generate Board Button #--------------------------------------- b = GenerateBoardButton(ev_manager=self.ev_manager, room=self) c.add(b, 500, 20) #Board Size? #--------------------------------------- bs = SetBoardSizeContainer(config.BOARD_LARGE, ev_manager=self.ev_manager, board=self.board) c.add(bs, 640, 20) #Fill Board? #--------------------------------------- t = FillBoardCheckbox(config.fill_board, ev_manager=self.ev_manager) c.add(t, 740, 20) #Darkness? #--------------------------------------- t = UseDarknessCheckbox(config.use_darkness, ev_manager=self.ev_manager) c.add(t, 840, 20) #Initialize #--------------------------------------- self.gui_app.init(c) def advance_level(self): self.level += 1 print 'Advancing to next level' print 'New level: ' + str(self.level) if self.timer_bar: print 'Time increase: ' + str(self.time_increase) self.timer_bar.value += self.time_increase self.time_increase = max(config.min_advance_time, int(self.time_increase * 0.9)) self.board = self.new_board self.new_board = None self.zoom_trip_complete = None self.game_clock.unpause() def notify(self, event): #Tick event if isinstance(event, TickEvent): pygame.display.set_caption('FPS: ' + str(int(event.fps))) self.render(self.screen) pygame.display.update() #Wait to deal new board when advancing levels if self.zoom_trip_complete and self.zoom_trip_complete.finished: self.zoom_trip_complete = None self.ev_manager.post(UnfreezeCards()) self.new_board = self.deck.deal_new_board(self.board) self.ev_manager.post(NewBoardComplete(self.new_board)) #New high score? if self.zoom_game_over and self.zoom_game_over.finished and not self.highs_dialog: if config.current_highs.check(self.level) != None: self.zoom_game_over.visible = False data = 'time:' + str(self.game_clock.time) + ',swaps:' + str(self.swap_counter) self.highs_dialog = HighScoreDialog(score=self.level, data=data, ev_manager=self.ev_manager) self.highs_dialog.open() elif not self.fade_out: self.fade_out = FadeOut(self.ev_manager, config.TITLE_SCREEN) #Second event elif isinstance(event, SecondEvent): if self.timer_bar: if not self.game_clock.paused: self.timer_bar.value -= 1 if self.timer_bar.value <= 0 and not self.game_over: self.ev_manager.post(GameOver()) self.minutes_left = self.timer_bar.value / 60 self.seconds_left = self.timer_bar.value % 60 if self.seconds_left < 10: leading_zero = '0' else: leading_zero = '' self.timer_text = ''.join(['Time Left: ', str(self.minutes_left), ':', leading_zero, str(self.seconds_left)]) #Game over elif isinstance(event, GameOver): self.game_over = True self.zoom_game_over = ZoomImage(self.ev_manager, self.game_over_text) #Trip complete event elif isinstance(event, TripComplete): print 'You did it!' self.game_clock.pause() self.zoom_trip_complete = ZoomImage(self.ev_manager, self.trip_complete_text) self.new_board_timer = Timer(self.ev_manager, 2) self.ev_manager.post(FreezeCards()) print 'Room posted newboardcomplete' #Board Refresh Complete elif isinstance(event, BoardRefreshComplete): if event.board == self.board: print 'Longest trip needed: ' + str(config.longest_trip_needed) print 'Your longest trip: ' + str(self.board.longest_trip) if self.board.longest_trip >= config.longest_trip_needed: self.ev_manager.post(TripComplete()) elif event.board == self.new_board: self.advance_level() self.connections_bar.value = self.board.longest_trip self.connection_text = ' '.join(['Connections:', str(self.board.longest_trip), '/', str(config.longest_trip_needed)]) #CardSwapComplete elif isinstance(event, CardSwapComplete): self.swap_counter += 1 elif isinstance(event, ConfigChangeBoardSize): config.board_size = event.new_size elif isinstance(event, ConfigChangeCardSize): config.card_size = event.new_size elif isinstance(event, ConfigChangeFillBoard): config.fill_board = event.new_value elif isinstance(event, ConfigChangeDarkness): config.use_darkness = event.new_value def render(self, surface): #Background surface.blit(self.background, (0, 0)) #Map self.map.render(surface) #Board self.board.render(surface) #Logo surface.blit(self.logo, (10,10)) #Text connection_text = self.font.render(self.connection_text, True, BLACK) surface.blit(connection_text, (25, 84)) if self.timer_text: timer_text = self.font.render(self.timer_text, True, BLACK) surface.blit(timer_text, (25, 64)) #GUI self.gui_app.paint(surface) if self.zoom_trip_complete: self.zoom_trip_complete.render(surface) if self.zoom_game_over: self.zoom_game_over.render(surface) if self.fade_out: self.fade_out.render(surface) class HighScoresRoom(Room): def __init__(self, screen, ev_manager): Room.__init__(self, screen, ev_manager) self.background = pygame.image.load('assets/images/interface/background.jpg').convert() #Initialize #--------------------------------------- self.gui_app = gui.App(config.gui_theme) self.ev_manager.gui_app = self.gui_app c = gui.Container(align=0,valign=0) #High Scores Table #--------------------------------------- hst = HighScoresTable() c.add(hst, 0, 0) self.gui_app.init(c) def render(self, surface): surface.blit(self.background, (0, 0)) #GUI self.gui_app.paint(surface) game_components.py #Remote imports import pygame from pygame.locals import * import random import operator from copy import copy from math import sqrt, floor #Local imports import config from events import * from matrix import Matrix from textrect import render_textrect, TextRectException from hyphen import hyphenator from textwrap2 import TextWrapper ############################## #CONSTANTS ############################## SCREEN_MARGIN = (10, 10) #Colors BLACK = (0, 0, 0) WHITE = (255, 255, 255) RED = (255, 0, 0) YELLOW = (255, 200, 0) #Directions LEFT = -1 RIGHT = 1 UP = 2 DOWN = -2 #Cards CARD_MARGIN = (10, 10) CARD_PADDING = (2, 2) #Card types BLANK = 0 COUNTRY = 1 TRANSPORT = 2 #Transport types PLANE = 0 TRAIN = 1 CAR = 2 SHIP = 3 class Timer(object): def __init__(self, ev_manager, time_left): self.ev_manager = ev_manager self.ev_manager.register_listener(self) self.time_left = time_left self.paused = False def __repr__(self): return str(self.time_left) def pause(self): self.paused = True def unpause(self): self.paused = False def notify(self, event): #Pause Event if isinstance(event, Pause): self.pause() #Unpause Event elif isinstance(event, Unpause): self.unpause() #Second Event elif isinstance(event, SecondEvent): if not self.paused: self.time_left -= 1 class Chrono(object): def __init__(self, ev_manager, start_time=0): self.ev_manager = ev_manager self.ev_manager.register_listener(self) self.time = start_time self.paused = False def __repr__(self): return str(self.time_left) def pause(self): self.paused = True def unpause(self): self.paused = False def notify(self, event): #Pause Event if isinstance(event, Pause): self.pause() #Unpause Event elif isinstance(event, Unpause): self.unpause() #Second Event elif isinstance(event, SecondEvent): if not self.paused: self.time += 1 class Map(object): def __init__(self, continent): self.map_image = pygame.image.load(continent.map).convert_alpha() self.map_text = pygame.image.load(continent.map_text).convert_alpha() self.pos = (0, 0) self.set_color() self.map_image = pygame.transform.smoothscale(self.map_image, config.map_size) self.size = self.map_image.get_size() def set_pos(self, pos): self.pos = pos def set_color(self): image_pixel_array = pygame.PixelArray(self.map_image) image_pixel_array.replace(config.GRAY1, config.COLOR1) image_pixel_array.replace(config.GRAY2, config.COLOR2) image_pixel_array.replace(config.GRAY3, config.COLOR3) image_pixel_array.replace(config.GRAY4, config.COLOR4) image_pixel_array.replace(config.GRAY5, config.COLOR5)

    Read the article

  • Alternative to pyGame ?

    - by stighy
    Hi, i'm learning something about game programming from a book about "pyGame". pyGame is simple, but... python is a little complex and different from my previous knoweledge about programming. I know "classical" language: C# (also C/C++), Java ... I know a lot of people love Python but for me is a little harder to learn! So i'm looking something like "pyGame" but for java or for c# ... A library with which i can do almost the same thing i can do with pygame (so .. do more with less code ... and headhace). Thank you Ps: excuse my "poor" english!

    Read the article

  • Pygame set_colorkey transparency issues

    - by Nathan Chowning
    I'm having a strange issue that I cannot seem to remedy. I am doing some prototyping with Pygame on a desktop running windows and a laptop running OS X. Both are running python v2.7.3 (installed via homebrew for the Macbook) and pygame v1.9.1. For transparency, I have been using set_colorkey with a transparency color of (255, 0, 255). Here is the applicable code: transColor = pygame.Color(255, 0, 255) image = pygame.image.load(playerPath + "idle.png").convert() image.set_colorkey(transColor) This works flawlessly on my windows machine. On my laptop, it does not work. It just shows the hideous magenta color. Here's the strange part. If I change the transColor to (0, 0, 0), all black pixels in my images are transparent. Has anyone run into this issue before?

    Read the article

  • Make pygame's frame rate faster

    - by Smashery
    By profiling my game, I see that the vast majority of the execution time of my hobby game is between the blit and the flip calls. Currently, it's only running at around 13fps. My video card is fairly decent, so my guess is that pygame is not using it. Does anyone know of any graphics/display options I need to set in pygame to make this faster? Or is this just something that I have to live with since I've chosen pygame?

    Read the article

  • How can a pygame image be colored?

    - by Juicy
    I'm writing a 2d particle system for a game in Pygame[1]. For the particles, I have an image surface loaded from a file -- basically a white primitive drawn over a transparent background. I'd like the particle engine to emit variously colored particles, but I'm not sure how to tell Pygame to color the surface. I've looked through what passes for documentation, but I'm having trouble finding anything. [1] Yeah, I don't really like Pygame, but my course insists I write this project in Python.

    Read the article

  • Collision in PyGame for spinning rectangular object.touching circles

    - by OverAchiever
    I'm creating a variation of Pong. One of the differences is that I use a rectangular structure as the object which is being bounced around, and I use circles as paddles. So far, all the collision handling I've worked with was using simple math (I wasn't using the collision "feature" in PyGame). The game is contained within a 2-dimensional continuous space. The idea is that the rectangular structure will spin at different speed depending on how far from the center you touch it with the circle. Also, any extremity of the rectangular structure should be able to touch any extremity of the circle. So I need to keep track of where it has been touched on both the circle and the rectangle to figure out the direction it will be bounced to. I intend to have basically 8 possible directions (Up, down, left, right and the half points between each one of those). I can work out the calculation of how the objected will be dislocated once I get the direction it will be dislocated to based on where it has been touch. I also need to keep track of where it has been touched to decide if the rectangular structure will spin clockwise or counter-clockwise after it collided. Before I started coding, I read the resources available at the PyGame website on the collision class they have (And its respective functions). I tried to work out the logic of what I was trying to achieve based on those resources and how the game will function. The only thing I could figure out that I could do was to make each one of these objects as a group of rectangular objects, and depending on which rectangle was touched the other would behave accordingly and give the illusion it is a single object. However, not only I don't know if this will work, but I also don't know if it is gonna look convincing based on how PyGame redraws the objects. Is there a way I can use PyGame to handle these collision detections by still having a single object? Can I figure out the point of collision on both objects using functions within PyGame precisely enough to achieve what I'm looking for? P.s: I hope the question was specific and clear enough. I apologize if there were any grammar mistakes, English is not my native language.

    Read the article

  • Doing an SNES Mode 7 (affine transform) effect in pygame

    - by 2D_Guy
    Is there such a thing as a short answer on how to do a Mode 7 / mario kart type effect in pygame? I have googled extensively, all the docs I can come up with are dozens of pages in other languages (asm, c) with lots of strange-looking equations and such. Ideally, I would like to find something explained more in English than in mathematical terms. I can use PIL or pygame to manipulate the image/texture, or whatever else is necessary. I would really like to achieve a mode 7 effect in pygame, but I seem close to my wit's end. Help would be greatly appreciated. Any and all resources or explanations you can provide would be fantastic, even if they're not as simple as I'd like them to be. If I can figure it out, I'll write a definitive how to do mode 7 for newbies page. edit: mode 7 doc: http://www.coranac.com/tonc/text/mode7.htm

    Read the article

  • Embedding Pygame to C++ [closed]

    - by Pendertuga
    If embedding Pygame to C++ to have a game be an executable, is there any extra process I would have to use in order to use Pygame functions when embedding into C++? As opposed to just writing embedding code in C++ for normal Python code? To clear cut the question I want to know if it's the same process without having to call different functions. EDIT: My question is if I have to call different functions in C++ when embedding Python code that uses Pygame modules. I am NOT using pygame2exe nor py2exe. I never even mentioned those. My question is solely about code embedding.

    Read the article

  • I am trying to move a rectangle in Pygame using coordinates but won't work

    - by user1821449
    this is my code import pygame from pygame.locals import * import sys pygame.init() pygame.display.set_caption("*no current mission*") size = (1280, 750) screen = pygame.display.set_mode(size) clock = pygame.time.Clock() bg = pygame.image.load("bg1.png") guy = pygame.image.load("hero_stand.png") rect = guy.get_rect() x = 10 y = 10 while True: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() if event.type == KEYDOWN: _if event.key == K_RIGHT: x += 5 rect.move(x,y)_ rect.move(x,y) screen.blit(bg,(0,0)) screen.blit(guy, rect) pygame.display.flip() it is just a simple test to see if i can get a rectangle to move. Everything seems to work except the code I put in italic.

    Read the article

  • Bullet physics in python and pygame

    - by Pomg
    I am programming a 2D sidescroller in python and pygame and am having trouble making a bullet go farther than just farther than the player. The bullet travels straight to the ground after i fire it. How, in python code using pygame do I make the bullet go farther. If you need code, here is the method that handles the bullet firing: self.xv += math.sin(math.radians(self.angle)) * self.attrs['speed'] self.yv += math.cos(math.radians(self.angle)) * self.attrs['speed'] self.rect.left += self.xv self.rect.top += self.yv

    Read the article

  • Problem with a* implementation in pygame

    - by piyush3dxyz
    Yesterday i decide to make RTS game in pygame(pygame is best).I figured out many components of RTS game like unit selecting,health,resources but only 1 thing i still not understand.. which is a* pathfinding in pygame... I also done little bit of research on wiki,articles and papers...but still cant figure out problem.... function A*(start,goal) closedset := the empty set // The set of nodes already evaluated. openset := {start} // The set of tentative nodes to be evaluated, initially containing the start node came_from := the empty map // The map of navigated nodes. g_score[start] := 0 // Cost from start along best known path. // Estimated total cost from start to goal through y. f_score[start] := g_score[start] + heuristic_cost_estimate(start, goal) while openset is not empty current := the node in openset having the lowest f_score[] value if current = goal return reconstruct_path(came_from, goal) remove current from openset add current to closedset for each neighbor in neighbor_nodes(current) if neighbor in closedset continue tentative_g_score := g_score[current] + dist_between(current,neighbor) if neighbor not in openset or tentative_g_score <= g_score[neighbor] came_from[neighbor] := current g_score[neighbor] := tentative_g_score f_score[neighbor] := g_score[neighbor] + heuristic_cost_estimate(neighbor, goal) if neighbor not in openset add neighbor to openset return failure here is the pseudocode for wiki a* implementation......

    Read the article

  • How can I make smoother upwards/downwards controls in pygame?

    - by Zolani13
    This is a loop I use to interpret key events in a python game. # Event Loop for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_a: my_speed = -10; if event.key == pygame.K_d: my_speed = 10; if event.type == pygame.KEYUP: if event.key == pygame.K_a: my_speed = 0; if event.key == pygame.K_d: my_speed = 0; The 'A' key represents up, while the 'D' key represents down. I use this loop within a larger drawing loop, that moves the sprite using this: Paddle1.rect.y += my_speed; I'm just making a simple pong game (as my first real code/non-gamemaker game) but there's a problem between moving upwards <= downwards. Essentially, if I hold a button upwards (or downwards), and then press downwards (or upwards), now holding both buttons, the direction will change, which is a good thing. But if I then release the upward button, then the sprite will stop. It won't continue in the direction of my second input. This kind of key pressing is actually common with WASD users, when changing directions quickly. Few people remember to let go of the first button before pressing the second. But my program doesn't accommodate the habit. I think I understand the reason, which is that when I let go of my first key, the KEYUP event still triggers, setting the speed to 0. I need to make sure that if a key is released, it only sets the speed to 0 if another key isn't being pressed. But the interpreter will only go through one event at a time, I think, so I can't check if a key has been pressed if it's only interpreting the commands for a released key. This is my dilemma. I want set the key controls so that a player doesn't have to press one button at a time to move upwards <= downwards, making it smoother. How can I do that?

    Read the article

  • Pygame surface rotation, rect rotation or sprite rotation?

    - by Alan
    i seem to have a conceptual misunderstanding of the surface and rect object in pygame. I currently observe these objects this way: Surface Just the loaded image rect the 'hard' representation of the ingame object (sprite). Used for simplifying object moment and collision detection sprite rect and surface grouped together What i want to do is rotate my sprite. The only available method i found for rotation is pygame.transform.rotate. How do i rotate the rectangle, or even better, the whole sprite? Below is the image of how i visualize this problem.

    Read the article

  • Mac OS X pygame input goes to Terminal instead of Python

    - by Parappa
    I'm having trouble running a pygame based app on Mac OS X via Terminal. Input events such as keystrokes go to the Terminal instead of my Python app, and are detected by pygame. For example, I have the following test script: import pygame pygame.init() screen = pygame.display.set_mode((640, 480)) done = False while not done: pygame.event.pump() keys = pygame.key.get_pressed() if keys[pygame.K_ESCAPE]: done = True if keys[pygame.K_SPACE]: print "got here" Neither K_ESCAPE nor K_SPACE will be handled by this script when I run it from a Mac OS X Terminal, but Terminal will echo back the spaces. I'm running the MacPorts port of pygame (py-game), which depends on Python 2.4, and I've also used python_select to make python24 the active version.

    Read the article

  • how to do event checks for loops?

    - by yao jiang
    I am having some trouble getting the logic down for this. Currently, I have an app that animates the astar pathfinding algorithm. On start of the app, the ui will show the following: User can press "space" to randomly choose start/end coords, then the app will animate it. Or, user can choose the start/end by left-click/right-click. During the animation, the user can also left-click to generate blocks, or right-click to choose a new destiantion. Where I am stuck at is how to handle the events while the app is animating. Right now, I am checking events in the main loop, then when the app is animating, I do event checks again. While it works fine, I feel that I am probably doing it wrong. What is the proper way of setting up the main loop that will handle the events while the app is animating? In main loop, the app start animating once user choose start/end. In my draw function, I am putting another event checker in there. def clear(rows): for r in range(rows): for c in range(rows): if r%3 == 1 and c%3 == 1: color = brown; grid[r][c] = 1; buildCoor.append(r); buildCoor.append(c); else: color = white; grid[r][c] = 0; pick_image(screen, color, width*c, height*r); pygame.display.flip(); os.system('cls'); # draw out the grid def draw(start, end, grid, route_coord): # draw the end coords color = red; pick_image(screen, color, width*end[1],height*end[0]); pygame.display.flip(); # then draw the rest of the route for i in range(len(route_coord)): # pausing because we want animation time.sleep(speed); # get the x/y coords x,y = route_coord[i]; event_on = False; if grid[x][y] == 2: color = green; elif grid[x][y] == 3: color = blue; for event in pygame.event.get(): if event.type == pygame.MOUSEBUTTONDOWN: if event.button == 3: print "destination change detected, rerouting"; # get mouse position, px coords pos = pygame.mouse.get_pos(); # get grid coord c = pos[0] // width; r = pos[1] // height; grid[r][c] = 4; end = [r, c]; elif event.button == 1: print "user generated event"; pos = pygame.mouse.get_pos(); # get grid coord c = pos[0] // width; r = pos[1] // height; # mark it as a block for now grid[r][c] = 1; event_on = True; if check_events([x,y]) or event_on: # there is an event # mark it as a block for now grid[y][x] = 1; pick_image(screen, event_x, width*y, height*x); pygame.display.flip(); # then find a new route new_start = route_coord[i-1]; marked_grid, route_coord = find_route(new_start, end, grid); draw(new_start, end, grid, route_coord); return; # just end draw here so it wont throw the "index out of range" error elif grid[x][y] == 4: color = red; pick_image(screen, color, width*y, height*x); pygame.display.flip(); # clear route coord list, otherwise itll just add more unwanted coords route_coord_list[:] = []; clear(rows); # main loop while not done: # check the events for event in pygame.event.get(): # mouse events if event.type == pygame.MOUSEBUTTONDOWN: # get mouse position, px coords pos = pygame.mouse.get_pos(); # get grid coord c = pos[0] // width; r = pos[1] // height; # find which button pressed, highlight grid accordingly if event.button == 1: # left click, start coords if grid[r][c] == 2: grid[r][c] = 0; color = white; elif grid[r][c] == 0 or grid[r][c] == 4: grid[r][c] = 2; start = [r,c]; color = green; else: grid[r][c] = 1; color = brown; elif event.button == 3: # right click, end coords if grid[r][c] == 4: grid[r][c] = 0; color = white; elif grid[r][c] == 0 or grid[r][c] == 2: grid[r][c] = 4; end = [r,c]; color = red; else: grid[r][c] = 1; color = brown; pick_image(screen, color, width*c, height*r); # keyboard events elif event.type == pygame.KEYDOWN: clear(rows); # one way to quit program if event.key == pygame.K_ESCAPE: print "program will now exit."; done = True; # space key for random start/end elif event.key == pygame.K_SPACE: # first clear the ui clear(rows); # now choose random start/end coords buildLoc = zip(buildCoor,buildCoor[1:])[::2]; #print buildLoc; (start_x, start_y, end_x, end_y) = pick_point(); while (start_x, start_y) in buildLoc or (end_x, end_y) in buildLoc: (start_x, start_y, end_x, end_y) = pick_point(); clear(rows); print "chosen random start/end coords: ", (start_x, start_y, end_x, end_y); if (start_x, start_y) in buildLoc or (end_x, end_y) in buildLoc: print "error"; # draw the route marked_grid, route_coord = find_route([start_x,start_y],[end_x,end_y], grid); draw([start_x, start_y], [end_x, end_y], marked_grid, route_coord); # return key for user defined start/end elif event.key == pygame.K_RETURN: # first clear the ui clear(rows); # get the user defined start/end print "user defined start/end are: ", (start[0], start[1], end[0], end[1]); grid[start[0]][start[1]] = 1; grid[end[0]][end[1]] = 2; # draw the route marked_grid, route_coord = find_route(start, end, grid); draw(start, end, marked_grid, route_coord); # c to clear the screen elif event.key == pygame.K_c: print "clearing screen."; clear(rows); # go fullscreen elif event.key == pygame.K_f: if not full_sc: pygame.display.set_mode([1366, 768], pygame.FULLSCREEN); full_sc = True; rows = 15; clear(rows); else: pygame.display.set_mode(size); full_sc = False; # +/- key to change speed of animation elif event.key == pygame.K_LEFTBRACKET: if speed >= 0.1: print SPEED_UP; speed = speed_up(speed); print speed; else: print FASTEST; print speed; elif event.key == pygame.K_RIGHTBRACKET: if speed < 1.0: print SPEED_DOWN; speed = slow_down(speed); print speed; else: print SLOWEST print speed; # second method to quit program elif event.type == pygame.QUIT: print "program will now exit."; done = True; # limit to 20 fps clock.tick(20); # update the screen pygame.display.flip();

    Read the article

  • Pygame Tile Based Character movement speed

    - by Ryan
    Thanks for taking the time to read this. Right now I'm making a really basic tile based game. The map is a large amount of 16x16 tiles, and the character image is 16x16 as well. My character has its own class that is an extension of the sprite class, and the x and y position is saved in terms of the tile position. To note I am fairly new to pygame. My question is, I am planning to have character movement restricted to one tile at a time, and I'm not sure how to make it so that, even if the player hits the directional key dozens of time quickly, (WASD or arrow keys) it will only move from tile to tile at a certain speed. How could I implement this generally with pygame? (Similar to game movement of like Pokemon or NexusTk). Edit: I should probably note that I want it so that the player can only end a movement in a tile. He couldn't stop moving halfway inbetween a tile for example. Thanks for your time! Ryan

    Read the article

  • PyGame QIX clone, filling areas

    - by astropanic
    I'm playing around with PyGame. Now I'm trying to implement a QIX clone. I have my game loop, and I can move the player (cursor) on the screen. In QIX, the movment of the player leaves a trace (tail) on the screen, creating a polyline. If the polyline with the screen boundaries creates a polygon, the area is filled. How I can accomplish this behaviour ? How store the tail in memory ? How to detect when it build a closed shape that should be filled ? I don't need an exact working solution, some pointers, algo names would be cool.

    Read the article

1 2 3 4 5 6  | Next Page >