project game
import pygame
import os
import random from pygame.locals import * # Constants
import math
import sys
import random
pygame.init()
screen=pygame.display.set_mode((1280,720)) #(length,height)
screen_rect=screen.get_rect()
background = pygame.Surface(screen.get_size())
background.fill((255,255,255)) # fill the background white
White = (255,255,255)
---------------------------------------------------------------------
background = pygame.image.load('stage.png').convert()
screen.blit(background, (0, 0))
class Player(pygame.sprite.Sprite):
def __init__(self):
self.rect = pygame.draw.rect(screen, (0,0,128), (50,560,50,25)) #(colour)(x-position,y-position,width,height)
self.dist = 100
def draw_rect(self,x,y): # This is my code which should make the player move
screen.blit(background, (0, 0)) #If this isn't included then when the rectangle moves it's old positon will still be on the screen
self.rect = self.rect.move(x*self.dist, y*self.dist); pygame.draw.rect(screen, (0, 0, 128), self.rect)
pygame.display.update()
def handle_keys(self): # code to make the character move when the arrow keys are pressed
for e in pygame.event.get():
if e.type == KEYDOWN:
key = e.key
if key == K_LEFT:
self.draw_rect(-0.5,0)
elif key == K_RIGHT:
self.draw_rect(0.5,0)
elif key == K_UP:
self.draw_rect(0,-0.5)
elif key == K_DOWN:
self.draw_rect(0,0.5)
elif key == K_SPACE:
self.draw_rect(2,-3)
if self.rect.right > 1400:
self.rect.right = 1400
if self.rect.left < 0:
self.rect.left = 0
if self.rect.bottom > 500:
self.rect.bottom = 500
if self.rect.top < 0:
self.rect.top = 0
player = Player()
------------------------------------------------------------------------
class Enemy(pygame.sprite.Sprite): # the enemy class which works fine
def __init__(self):
x = random.randint(50,450)
self.rect = pygame.draw.rect(screen, (128,0,0), (300,x,50,25))
enemy = Enemy()
pygame.display.flip() #updates the whole screen
def main(): #my main loop
while True:
player.handle_keys()
for event in pygame.event.get
if event.type == pygame.QUIT:
running = False
if __name__ == '__main__': main()
The player does move but when the keys are pressed and the player moves the enemy disappears so i need help to fix it
Ext the player doesn't move when the arrow keys are held only when pressed
You were checking for keydown events in your player's handle_keys method. Any keydown events only register once until the next keyup. You want to use pygame.key.get_pressed() which returns a dict of all the pressed keys at any given moment. I've fixed it for you as well as cleaned the code up a little bit. You may want to consider using a delay or pygame's built-in Clock class for controlling framerates. If you notice, I had to change your movements to very tiny numbers (0.05 from 0.5) because of how quickly you update your frames. Adding in time.sleep() or the pygame clock would fix this.
import pygame
import os
import random
from pygame.locals import * # Constants
import math
import sys
import random
pygame.init()
screen=pygame.display.set_mode((1280,720)) #(length,height)
screen_rect=screen.get_rect()
background = pygame.Surface(screen.get_size())
background.fill((255,255,255)) # fill the background white
White = (255,255,255)
class Player(pygame.sprite.Sprite):
def __init__(self):
self.rect = pygame.draw.rect(screen, (0,0,128), (50,560,50,25)) #(colour)(x-position,y-position,width,height)
self.dist = 100
def draw_rect(self,x,y): # This is my code which should make the player move
screen.blit(background, (0, 0)) #If this isn't included then when the rectangle moves it's old positon will still be on the screen
self.rect = self.rect.move(x*self.dist, y*self.dist); pygame.draw.rect(screen, (0, 0, 128), self.rect)
pygame.display.update()
def handle_keys(self): # code to make the character move when the arrow keys are pressed
keys = pygame.key.get_pressed()
if keys[K_LEFT]:
self.draw_rect(-0.05,0)
elif keys[K_RIGHT]:
self.draw_rect(0.05,0)
elif keys[K_UP]:
self.draw_rect(0,-0.05)
elif keys[K_DOWN]:
self.draw_rect(0,0.05)
elif keys[K_SPACE]:
self.draw_rect(2,-3)
if self.rect.right > 1400:
self.rect.right = 1400
if self.rect.left < 0:
self.rect.left = 0
if self.rect.bottom > 500:
self.rect.bottom = 500
if self.rect.top < 0:
self.rect.top = 0
class Enemy(pygame.sprite.Sprite): # the enemy class which works fine
def __init__(self):
x = random.randint(50,450)
self.rect = pygame.draw.rect(screen, (128,0,0), (300,x,50,25))
player = Player()
enemy = Enemy()
def main(): #my main loop
running = True
while running:
player.handle_keys()
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
pygame.display.flip() #updates the whole screen
if __name__ == '__main__': main()
Related
This question already has answers here:
Why is my PyGame application not running at all?
(2 answers)
Closed 1 year ago.
So I'm kinda new at Pygame, and just trying to create easy projects to learn.
I've created a basic rectangle first as player, and I want to implement a system where user clicks to somewhere in screen and game spawns a rectangle at that point. Here's my code:
import pygame
import sys
from pygame import *
from pygame.mouse import get_pos
pygame.init()
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
screen = pygame.display.set_mode((SCREEN_WIDTH,SCREEN_HEIGHT))
pygame.display.set_caption("Touch To Create Blocks!")
class Player(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.surf = pygame.Surface((50,50))
self.surf.fill((220,120,37))
self.rect = self.surf.get_rect()
def update(self,pressed_keys):
if pressed_keys[pygame.K_UP]:
self.rect.move_ip(0,-5)
elif pressed_keys[pygame.K_DOWN]:
self.rect.move_ip(0,5)
elif pressed_keys[pygame.K_LEFT]:
self.rect.move_ip(-5,0)
elif pressed_keys[pygame.K_RIGHT]:
self.rect.move_ip(5,0)
if self.rect.left < 0:
self.rect.left = 0
elif self.rect.right > SCREEN_WIDTH:
self.rect.right = SCREEN_WIDTH
elif self.rect.top <= 0:
self.rect.top = 0
elif self.rect.top >= SCREEN_HEIGHT - 50:
self.rect.bottom = SCREEN_HEIGHT
player = Player()
run = True
while run:
for event in pygame.event.get():
if event.type == QUIT:
run = False
sys.exit()
elif event.type == KEYDOWN:
if event.key == K_ESCAPE:
run = False
sys.exit()
elif event.type == MOUSEBUTTONDOWN:
mouse_x, mouse_y = pygame.mouse.get_pos()
rectangle = pygame.Rect(mouse_x, mouse_y, 40, 40)
pygame.draw.rect(screen, (255,255,255) , rectangle)
pygame.display.update()
screen.fill((0,0,0))
pressed_keys = pygame.key.get_pressed()
player.update(pressed_keys)
screen.blit(player.surf,player.rect)
pygame.display.update()
With that code, when I click, a block spawns and disappears immediately. How do I fix this? Thanks for your help.
(Sorry for my bad English)
The problem is that when the user clicks you draw the rectangle
(pygame.draw.rect), update the display (pygame.display.update) and
then, after the for loop, you empty the display
(screen.fill((0,0,0))). This explains why the rectangle disappears
immediately.
Instead of calling pygame.draw.rect each time the user clicks on the
screen, you can instead memorise the rectangle and save it into a
list. Then you have can draw all rectangles you memorised at each
iteration of your main loop.
Here is an implementation of this solution (I have added comments in
the code):
import pygame
import sys
from pygame import *
from pygame.mouse import get_pos
pygame.init()
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
screen = pygame.display.set_mode((SCREEN_WIDTH,SCREEN_HEIGHT))
pygame.display.set_caption("Touch To Create Blocks!")
class Player(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.surf = pygame.Surface((50,50))
self.surf.fill((220,120,37))
self.rect = self.surf.get_rect()
def update(self,pressed_keys):
if pressed_keys[pygame.K_UP]:
self.rect.move_ip(0,-5)
elif pressed_keys[pygame.K_DOWN]:
self.rect.move_ip(0,5)
elif pressed_keys[pygame.K_LEFT]:
self.rect.move_ip(-5,0)
elif pressed_keys[pygame.K_RIGHT]:
self.rect.move_ip(5,0)
if self.rect.left < 0:
self.rect.left = 0
elif self.rect.right > SCREEN_WIDTH:
self.rect.right = SCREEN_WIDTH
elif self.rect.top <= 0:
self.rect.top = 0
elif self.rect.top >= SCREEN_HEIGHT - 50:
self.rect.bottom = SCREEN_HEIGHT
player = Player()
run = True
rectangles = list() # list of the rectangles we have to draw
while run:
for event in pygame.event.get():
if event.type == QUIT:
run = False
sys.exit()
elif event.type == KEYDOWN:
if event.key == K_ESCAPE:
run = False
sys.exit()
elif event.type == MOUSEBUTTONDOWN:
# add a new rectangle to our list of rectangles
mouse_x, mouse_y = pygame.mouse.get_pos()
rectangles.append(pygame.Rect(mouse_x, mouse_y, 40, 40))
screen.fill((0,0,0))
pressed_keys = pygame.key.get_pressed()
player.update(pressed_keys)
screen.blit(player.surf,player.rect)
# draw all the rectangles we memorised
for rectangle in rectangles:
pygame.draw.rect(screen, (255,255,255) , rectangle)
pygame.display.update()
im trying to get my image (bird) to move up and down on the screen but i cant figure out how to do it here is what i tried im sure its way off but im trying to figure it out if anyone can help that would be great!
import pygame
import os
screen = pygame.display.set_mode((640, 400))
running = 1
while running:
event = pygame.event.poll()
if event.type == pygame.QUIT:
running = 0
screen.fill([255, 255, 255])
clock = pygame.time.Clock()
clock.tick(0.5)
pygame.display.flip()
bird = pygame.image.load(os.path.join('C:\Python27', 'player.png'))
screen.blit( bird, ( 0, 0 ) )
pygame.display.update()
class game(object):
def move(self, x, y):
self.player.center[0] += x
self.player.center[1] += y
if event.key == K_UP:
player.move(0,5)
if event.key == K_DOWN:
player.move(0,-5)
game()
im trying to get it to move down on the down button press and up on the UP key press
As stated by ecline6, bird is the least of your worries at this point.
Consider reading this book..
For now, First let's clean up your code...
import pygame
import os
# let's address the class a little later..
pygame.init()
screen = pygame.display.set_mode((640, 400))
# you only need to call the following once,so pull them out of the while loop.
bird = pygame.image.load(os.path.join('C:\Python27', 'player.png'))
clock = pygame.time.Clock()
running = True
while running:
event = pygame.event.poll()
if event.type == pygame.QUIT:
running = False
screen.fill((255, 255, 255)) # fill the screen
screen.blit(bird, (0, 0)) # then blit the bird
pygame.display.update() # Just do one thing, update/flip.
clock.tick(40) # This call will regulate your FPS (to be 40 or less)
Now the reason that your "bird" is not moving is:
When you blit the image, ie: screen.blit(bird, (0, 0)),
The (0,0) is constant, so it won't move.
Here's the final code, with the output you want (try it) and read the comments:
import pygame
import os
# it is better to have an extra variable, than an extremely long line.
img_path = os.path.join('C:\Python27', 'player.png')
class Bird(object): # represents the bird, not the game
def __init__(self):
""" The constructor of the class """
self.image = pygame.image.load(img_path)
# the bird's position
self.x = 0
self.y = 0
def handle_keys(self):
""" Handles Keys """
key = pygame.key.get_pressed()
dist = 1 # distance moved in 1 frame, try changing it to 5
if key[pygame.K_DOWN]: # down key
self.y += dist # move down
elif key[pygame.K_UP]: # up key
self.y -= dist # move up
if key[pygame.K_RIGHT]: # right key
self.x += dist # move right
elif key[pygame.K_LEFT]: # left key
self.x -= dist # move left
def draw(self, surface):
""" Draw on surface """
# blit yourself at your current position
surface.blit(self.image, (self.x, self.y))
pygame.init()
screen = pygame.display.set_mode((640, 400))
bird = Bird() # create an instance
clock = pygame.time.Clock()
running = True
while running:
# handle every event since the last frame.
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit() # quit the screen
running = False
bird.handle_keys() # handle the keys
screen.fill((255,255,255)) # fill the screen with white
bird.draw(screen) # draw the bird to the screen
pygame.display.update() # update the screen
clock.tick(40)
The keyboard events (see pygame.event module) occur only once when the state of a key changes. The KEYDOWN event occurs once every time a key is pressed. KEYUP occurs once every time a key is released. Use the keyboard events for a single action or a step-by-step movement.
If you want to achieve a continuously movement, you have to use pygame.key.get_pressed(). pygame.key.get_pressed() returns a list with the state of each key. If a key is held down, the state for the key is True, otherwise False. Use pygame.key.get_pressed() to evaluate the current state of a button and get continuous movement.
See also Key and Keyboard event and How can I make a sprite move when key is held down.
Minimal example:
import pygame
import os
class Bird(object):
def __init__(self):
self.image = pygame.image.load(os.path.join('C:\Python27', 'player.png'))
self.center = [100, 200]
def move(self, x, y):
self.center[0] += x
self.center[1] += y
def draw(self, surf):
surf.blit(self.image, self.center)
class game(object):
def __init__(self):
self.screen = pygame.display.set_mode((640, 400))
self.clock = pygame.time.Clock()
self.player = Bird()
def run(self):
running = 1
while running:
self.clock.tick(60)
event = pygame.event.poll()
if event.type == pygame.QUIT:
running = 0
keys = pygame.key.get_pressed()
move_x = keys[pygame.K_RIGHT] - keys[pygame.K_LEFT]
move_y = keys[pygame.K_DOWN] - keys[pygame.K_UP]
self.player.move(move_x * 5, move_y * 5)
self.screen.fill([255, 255, 255])
self.player.draw(self.screen)
pygame.display.update()
g = game()
g.run()
I'm writing this code to build a simple square which moves left and right and can jump on a stage using the colliderect function in pygame but the problem is when the player(square) jumps on the stage its y coordinate changes to the y coordinate of the stage permanently and never falls down. Another big issue is that when the player is below the stage it should not be able to jump over the top but it does. My code contains four pages, first contains the main loop, second contains the player class, third contains stage class and forth part contains the basic game functions
Main--Pg 01
import pygame
from player import Player
import game_functions as gf
import sys
from stage import Stage
from pygame.sprite import Group
def run_game():
# Intialise the game and start the screen
pygame.init()
screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption("AmarCreep")
player = Player(screen)
stage = Stage(screen)
clock = pygame.time.Clock()
# Main loop
while True:
clock.tick(60)
# Navy screen
screen.fill((173,216,249))
for event in pygame.event.get():
# Check if user wants to quit
if event.type == pygame.QUIT:
sys.exit()
gf.responses(screen, player, event)
# Update player's x-y coordinate
player.p_movements(stage)
stage.draw_stage()
# Make the player appear
player.draw_player()
# Make the newly made screen visible
pygame.display.flip()
run_game()
Player--Pg 02
import pygame
from pygame.sprite import Sprite
class Player(Sprite):
# Initialise the main player
def __init__(self, screen):
super(Player, self).__init__()
self.screen = screen
self.screen_rect = screen.get_rect()
# Specifying the position of the player at start
self.rect = pygame.Rect(0, 0, 30, 30)
self.rect.centerx = self.screen_rect.centerx
self.rect.bottom = 590
self.moving_left = False
self.moving_right = False
self.moving_up = False
self.vel_y = 18
def p_movements(self, stage):
dx = 0
dy = 0
# Predict the player movements beforehand
if self.moving_left and self.rect.x > 10:
dx -= 7
if self.moving_right and self.rect.x < 760:
dx += 7
if self.moving_up:
dy -= self.vel_y
self.vel_y -= 2
if self.vel_y < -18:
self.moving_up = False
self.vel_y = 18
# Check collisions in x direction
if stage.s_rect.colliderect(self.rect.x + dx, self.rect.y, 30, 30):
dx = 0
# Check collisions in y direction
if stage.s_rect.colliderect(self.rect.x, self.rect.y + dy, 30, 30):
if self.vel_y < 0:
dy = stage.s_rect.bottom - self.rect.top
self.vel_y = 0
elif self.vel_y > 0:
dy = stage.s_rect.top - self.rect.bottom
# Update the positionse
self.rect.x += dx
self.rect.y += dy
if self.rect.bottom > 590:
self.rect.bottom = 590
dy = 0
pygame.time.Clock().tick(60)
def draw_player(self):
''' Draw the player on the screen'''
pygame.draw.rect(self.screen, (245,245,245), self.rect)
Stage--Pg 03
import pygame
from pygame.sprite import Sprite
from random import randint
class Stage(Sprite):
"""Initialize the platform for player to jump on"""
def __init__(self, screen):
super(Stage, self).__init__()
self.screen = screen
self.screen_rect = screen.get_rect()
self.s_rect = pygame.Rect(0, 540, 80, 10)
self.s_rect.x = randint(10, 590)
def draw_stage(self):
''' Draw the platform for the player'''
pygame.draw.rect(self.screen, (0,0,0), self.s_rect)
Game functions--Pg 04
import pygame
def responses(screen, player, event):
''' Check for responses'''
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
player.moving_up = True
if event.key == pygame.K_LEFT:
player.moving_left = True
if event.key == pygame.K_RIGHT:
player.moving_right = True
elif event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT:
player.moving_left = False
if event.key == pygame.K_RIGHT:
player.moving_right = False
From what I can see about your code, you use colliderect with a collision box of 30x30: colliderect(self.rect.x + dx, self.rect.y, 30, 30)
Your level, or stage is 80x10: pygame.Rect(0, 540, 80, 10)
This means that the collision detection will only happen in a certain part of your stage. Here is a visual to help you better understand:
I believe this may be the source of your problems. After colliding with the red box, you have them teleport to around halfway, a time when they are still colliding with the box. This makes them constantly teleport back to where they were, as they are always getting put back into the red box, as they are colliding with it. This may cause some of your other errors.
import pygame
import os
import random
from pygame.locals import * # Constants
import math
import sys
import random
pygame.init()
screen=pygame.display.set_mode((1280,700)) #(length,height)
screen_rect=screen.get_rect()
background = pygame.Surface(screen.get_size())
background.fill((255,255,255)) # fill the background white
background = pygame.image.load('stage.png').convert()
Black=(0,0,0)
class Player(pygame.sprite.Sprite):
x = 20
y = 615
def __init__(self):
super().__init__() # calls the parent class allowing sprite to initalize
self.image = pygame.Surface((50,25)) # this is used to create a blank image with the size inputted
self.image.fill((0,0,128)) # fills the blank image with colour
self.rect = self.image.get_rect(topleft =(20,615)) # This place the player at the given position
self.dist = 10
def update(self): # code to make the character move when the arrow keys are pressed
if self.rect.right > 100: # These are to make the player so move constantly
self.rect.y += 1
self.rect.x += 2
if self.rect.bottom == 700:
pygame.quit()
keys = pygame.key.get_pressed()
if keys[K_LEFT]:
self.rect.move_ip(-1,0)
elif keys[K_RIGHT]:
self.rect.move_ip(0.5,0)
elif keys[K_UP]:
self.rect.move_ip(0,-0.5)
elif keys[K_DOWN]:
self.rect.move_ip(0,1)
self.rect.clamp_ip(screen_rect)
#while self.rect == (20,615):
if keys [K_SPACE]:
self.rect = self.image.get_rect(topleft =(100,100))
class Enemy(pygame.sprite.Sprite): # the enemy class which works fine
def __init__(self):
super().__init__()
#y = random.randint(300,1200)
x = random.randint(50,450)
self.image = pygame.Surface((50,25))
self.image.fill((128,0,0))
self.rect = self.image.get_rect(topleft=(300, 50))
def update(self):
if self.rect.bottom <= 400:
self.rect.y += 1
if self.rect.bottom >= 400:
self.rect.y -= 300
On this part i got so that the enemy class moves downwards and when it reaches 400 it teleport 300 upwards but i wanted it so that it constantly moves upwards and then downwards again.
I thought that i either cancel the movement downwards when it reaches the position but i don't think you can do that.
clock = pygame.time.Clock() # A clock to limit the frame rate.
player = Player()
enemy = Enemy()
enemy_list = pygame.sprite.Group(enemy)
#enemy_list.add(enemy)
sprites = pygame.sprite.Group(player, enemy)
def main(): #my main loop
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
sprites.update()
screen.blit(background, (0, 0))
sprites.draw(screen)
clock.tick(100) # Limit the frame rate to 60 FPS.
pygame.display.flip() #updates the whole screen
#Collison check
player_hit_list = pygame.sprite.spritecollide(player, enemy_list, True)
for enemy in player_hit_list:
pygame.quit()
if __name__ == '__main__':
main()
The Enemy class needs an additional attribute that keeps track of the direction it's moving: up or down.
So a simple solution could look like this:
class Enemy(pygame.sprite.Sprite): # the enemy class which works fine
def __init__(self):
super().__init__()
x = random.randint(50,450)
self.image = pygame.Surface((50,25))
self.image.fill((128,0,0))
self.rect = self.image.get_rect(topleft=(300, 50))
self.direction = 'DOWN'
def update(self):
self.rect.y += 1 if self.direction == 'DOWN' else -1
if self.rect.bottom >= 400:
self.direction = 'UP'
if self.rect.top <= 50:
self.direction = 'DOWN'
I am just getting started with Pygame and I am currently trying out some basic movement functions.
I ran into a problem when trying to code my movement conditions into my object class rather than in the game loop.
My first attempt which works is as follow:
classes.py:
import pygame, sys
from pygame.locals import *
class GameObject:
def __init__(self, image, height, speed):
self.speed = speed
self.image = image
self.pos = image.get_rect().move(0, height) #initial placement
def move_south(self):
self.pos = self.pos.move(0, self.speed)
if self.pos.right > 600:
self.pos.left = 0
def move_east(self):
self.pos = self.pos.move(self.speed , 0)
if self.pos.right > 600:
self.pos.left = 0
main.py:
import pygame, sys
from pygame.locals import *
from classes import *
screen = pygame.display.set_mode((640, 480))
#Importing Chars
player = pygame.image.load('green_hunter_small.png').convert()
#player.set_alpha(100) #makes whole player transparent
player.set_colorkey((0,0,0)) #sets background colour to transparent
ennemi = pygame.image.load('red_hunter_small.png').convert()
ennemi.set_colorkey((0,0,0))
background = pygame.image.load('grass_map_640x640.png').convert()
screen.blit(background, (0, 0))
objects = []
objects.append(GameObject(player, 80, 0))
for x in range(2): #create 2 objects
o = GameObject(ennemi, x*40, 0)
objects.append(o)
while True:
for event in pygame.event.get(): #setting up quit
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == KEYDOWN:
if event.key == K_DOWN:
for o in objects:
screen.blit(background, o.pos, o.pos) #erases players by bliting bg
for o in objects:
o.speed = 4
o.move_south() #moves player
o.speed = 0
screen.blit(o.image, o.pos) #draws player
if event.key == K_RIGHT:
for o in objects:
screen.blit(background, o.pos, o.pos) #erases players by bliting bg
for o in objects:
o.speed = 4
o.move_east() #moves player
o.speed = 0
screen.blit(o.image, o.pos) #draws player
pygame.display.update()
pygame.time.delay(50)
My second attempt which didn't work was to dp:
classes.py:
import pygame, sys
from pygame.locals import *
class GameObject:
def __init__(self, image, height, speed):
self.speed = speed
self.image = image
self.pos = image.get_rect().move(0, height) #initial placement
def move_south(self):
self.pos = self.pos.move(0, self.speed)
if self.pos.right > 600:
self.pos.left = 0
def move_east(self):
self.pos = self.pos.move(self.speed , 0)
if self.pos.right > 600:
self.pos.left = 0
def move(self):
for event in pygame.event.get():
if event.type == KEYDOWN:
if event.key == K_DOWN:
screen.blit(background, self.pos, self.pos) #erases players by bliting bg
self.speed = 4
self.move_south() #moves player
self.speed = 0
if event.key == K_RIGHT:
screen.blit(background, self.pos, self.pos) #erases players by bliting bg
self.speed = 4
self.move_east() #moves player
self.speed = 0
screen.blit(self.image, self.pos) #draws player
main.py:
import pygame, sys
from pygame.locals import *
from classes import *
screen = pygame.display.set_mode((640, 480))
#Importing Chars
player = pygame.image.load('green_hunter_small.png').convert()
#player.set_alpha(100) #makes whole player transparent
player.set_colorkey((0,0,0)) #sets background colour to transparent
ennemi = pygame.image.load('red_hunter_small.png').convert()
ennemi.set_colorkey((0,0,0))
background = pygame.image.load('grass_map_640x640.png').convert()
screen.blit(background, (0, 0))
objects = []
objects.append(GameObject(player, 80, 0))
for x in range(2): #create 2 objects
o = GameObject(ennemi, x*40, 0)
objects.append(o)
while True:
for event in pygame.event.get(): #setting up quit
if event.type == QUIT:
pygame.quit()
sys.exit()
for o in objects:
o.move()
pygame.display.update()
pygame.time.delay(50)
So it seems that the code struggles to go and check the event loop from the instance. The reason I wanted to code the movement as a method rather than straight in main was to save space and make it easier to add characters later on.
Your code has a race condition (to use the term really loosely).
The reason that your characters are not moving is that the first pygame.event.get call (when you are checking for a QUIT event) consumes all the KEYDOWN events that are on the queue. Then (unless you manage to press a key while the first loop is running), there are no KEYDOWN events in the queue when the first GameObject checks for events. Diddo for all other GameObjects.
You need to handler all pygame events in one loop. Example code:
class GameObject():
#rest of class
def move(self,event):
if event.key == K_DOWN:
screen.blit(background, self.pos, self.pos) #erases players by bliting bg
self.speed = 4
self.move_south() #moves player
self.speed = 0
#repeat for all other directions
screen.blit(self.image, self.pos) #draws player
#initialize objects
while True:
for event in pygame.event.get():
if event.type == QUIT: #handle quit event
elif event.type == KEYDOWN:
for o in objects:
o.move(event)
#do non-eventhandling tasks.