Getting my character to move fluidly in Pygame - python

I am trying to create a pygame for my com sci final, but my teacher has not done an excellent job at explaining how pygame works. My trouble here is I need make my character, a custom sprite I created, move fluidly when any of the 4 arrow keys are held. So far, all I've been able to do is make it move with every individual key press, and I have no idea how to fix this.
I'm not sure if my code is the most efficient, but essentially depending on what key you press, not only do the X and Y coordinates change, but the png image changes to face the appropriate direction. This is all draw using blits.
import pygame
pygame.init()
def redraw_game_window(texture):
screen = pygame.display.set_mode(size)
background_image = pygame.image.load("lava.jpg").convert()
background_image = pygame.transform.scale(background_image, (size))
screen.blit(background_image, [0, 0])
texture= pygame.transform.scale(texture, (65,64))
texture=texture.convert_alpha()
screen.blit(texture,(EarlX,EarlY))
size=1200,600
EarlWidth=65
EarlLength=64
texture = pygame.image.load("UpFacingEarl.png")
EarlX=500
EarlY=150
speed=50
inPlay= True
while inPlay:
redraw_game_window(texture)
pygame.time.delay(20)
keys = pygame.key.get_pressed()
if keys[pygame.K_ESCAPE]:
inPlay = False
if keys[pygame.K_LEFT]:
texture = pygame.image.load("LeftFacingEarl.png")
EarlX-=speed
if keys[pygame.K_RIGHT]:
texture = pygame.image.load("RightFacingEarl.png")
EarlX+=speed
if keys[pygame.K_UP]:
texture = pygame.image.load("UpFacingEarl.png")
EarlY-=speed
if keys[pygame.K_DOWN]:
texture = pygame.image.load("DownFacingEarl.png")
EarlY+=speed
pygame.display.flip()
Any help on how to improve my code would be greatly appreciated, I know im not including the png's but theres not much I can do there.

First, you don't need to double space your code. Now that we've gotten that out of the way:
screen = pygame.display.set_mode(size)
should only called at the beginning of the program. Not every time! This is the reason your program isn't working.
Here are other less important things to fix:
this should also only be called at the beginning:
background_image = pygame.image.load("lava.jpg").convert()
background_image = pygame.transform.scale(background_image, (size))
all in all, you redraw_game_window function should look like:
def redraw_game_window(texture, EarlX, EarlY, screen): #you should pass all the variables you are using to the function. Python doesn't work well with global variables. if you really want to use global variables like you did here, use the global keyword
screen.fill((0,0,0)) #clear the screen
screen.blit(background_image, [0, 0]) #draw new background
texture = pygame.transform.scale(texture, (65,64))
texture = texture.convert_alpha()
screen.blit(texture,(EarlX,EarlY)) #draw earl
This event loop is fine:
for event in pygame.event.get():
if event.type == pygame.QUIT: #you need this or else pressing the red "x" on the window won't close it
quit()
keys = pygame.key.get_pressed()
if keys[pygame.K_ESCAPE]: #press esc to exit program
quit()
if keys[pygame.K_UP]:
EarlY -= 1
if keys[pygame.K_DOWN]:
EarlY -= -1
if keys[pygame.K_LEFT]:
EarlX += -1
if keys[pygame.K_RIGHT]:
EarlX += 1

Related

Pygame displays black window

I'm doing tutorial for platform game but my Pygame window displays a black screen.
I don't know how to solve this.
I tried closing and opening Visual Studio Code again but nothing happens.
import pygame
SCREEN_SIZE = (700,500)
DARK_GREY = (50,50,50)
OGURKOWY = (21,179, 58)
pygame.init()
screen = pygame.display.set_mode(SCREEN_SIZE)
pygame.display.set_caption("Platformówka")
player_image = pygame.image.load("ogurek\doggo.png")
player_x = 300
platforms = [
pygame.Rect(100,300,400,50),
pygame.Rect(100,250 ,50,50),
pygame.Rect(450,250,50,50),
pygame.Rect(450,250,100,50)
]
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
keys = pygame.key.get_pressed()
if keys[pygame.K_a]:
player_x -= 2
if keys[pygame.K_a]:
player_x += 2
#tło
screen.fill(DARK_GREY)
#platformy
for p in platforms:
pygame.draw.rect(screen, (OGURKOWY), p)
#gracz
screen.blit(player_image, (player_x,100))
#
pygame.display.flip()
pygame.quit()
It is a matter of Indentation. The for-loop that draws the platforms (for p in platforms:) must be *in the application loop instead of after the application loop:
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
keys = pygame.key.get_pressed()
if keys[pygame.K_a]:
player_x -= 2
if keys[pygame.K_a]:
player_x += 2
#tło
screen.fill(DARK_GREY)
#platformy
# INDENTATION
#-->|
for p in platforms:
pygame.draw.rect(screen, (OGURKOWY), p)
#gracz
screen.blit(player_image, (player_x,100))
#
pygame.display.flip()
How to fix this apparent indentation issue was commented by Ari Cooper-Davis and answered by Rabbid76.
My answer aims to avoid such issues by design (keeping loops short and segregating nested constructs into methods).
Advice to avoid such indentation typos and improve readability of your code:
keep the game-loop (your while running:) short
extract code-blocks into functions/methods
put empty-lines (vertical spacing) between major code-blocks like for/if/functions, etc.
Extract methods
This recipe follows Single Responsibility Principle (SRP) and structures your code like your comments did. Moreover it makes the code more expressive, because method-calls will document same as comments to the reader.
def handle_exit_events():
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
def handle_key_events():
keys = pygame.key.get_pressed()
if keys[pygame.K_a]:
player_x -= 2
if keys[pygame.K_a]:
player_x += 2
def draw_background():
# tło
screen.fill(DARK_GREY)
def draw_platforms():
# platformy
for p in platforms:
pygame.draw.rect(screen, (OGURKOWY), p)
def draw_player():
# gracz
screen.blit(player_image, (player_x,100))
def update_display():
pygame.display.flip()
Note the 2 blank lines between each method definition.
Keep loops short
Now that we declared the methods (before), we can use them to shorten the loop:
# methods declared (from above)
# inits (screen/game-objects/color definitions) omitted to focus on game-loop
running = True
while running:
handle_exit_events()
handle_key_events()
draw_background() # currently static, could move above loop
draw_platforms() # currently static, could move above loop
draw_player() # player move triggered by key-press only
update_display()
pygame.quit()
See how your original comments inside the game-loop (# platformy, # tło and # gracz) were transformed to method-calls. Thus your code documents itself (making these comments obsolete).
What depends on change inside game-loop ?
Now we can think and recognize dependencies inside the loop.
The game-loop is for interactive parts like reacting to events or updating the screen.
Draw static objects once ahead
So the handle_x_events methods fit well inside the loop. But some static scenery like background and platforms are fixed objects in your game. They can be drawn once before entering the game-loop. Because they don't change with any of the events (like quit or key-pressed).
# methods declared (from above)
# inits (screen/game-objects/color definitions) omitted to focus on game-loop
draw_background()
draw_platforms()
running = True
while running:
Next is more questionable and depends on your design-approach.
Draw player when event triggers change (position or appearence)
draw_player() is needed once before the loop because when the game starts, the player is placed into the world. Then the player uses key-presses to change its position (see handle_key_events()) which will trigger the player-image to be re-positioned (horizontally only, player_x) and drawn on the screen.
You could express that dependency in code:
player_y = 100 # initial vertical position (fixed at the moment)
player_x = 300
player_x_speed = 2 # pixels delta per horizontal movement
def move_player_forward():
player_x += player_x_speed
screen.blit(player_image, (player_x, player_y))
def move_player_backward():
player_x -= player_x_speed
screen.blit(player_image, (player_x, player_y))
def handle_key_events():
keys = pygame.key.get_pressed()
if keys[pygame.K_a]:
move_player_backward()
if keys[pygame.K_a]:
move_player_forward()
# remaining code
while running:
handle_exit_events()
handle_key_events()
update_display()
pygame.quit()
See how the horizontal movement is expressed in code. The player_x modification was internalized into the movement methods.
Usually you would work with Player class and objects or at least player-coordinates, for example defined as tuple, which has some benefits:
player_position = (300, 100) # pixel coordinates of players initial position`
player_x_speed = 2 # pixels delta per horizontal movement
player_jump_height = 10 # pixels to jump vertically, e.g. on a platform
# walk forward
player_position[0] += player_x_speed
# jump forward
player_position = (player_position[0] + player_x_speed, player_position[1] + player_jump_height)
# directly drawn
screen.blit(player_image, player_position)

How to make a rectangular object to move slowly across the screen? [duplicate]

This question already has an answer here:
Pygame clock and event loops
(1 answer)
Closed 2 years ago.
i am new to python programming and now starting to write simple "Snake" game.
i am trying to make the head of the snake move around the screen in a way that
when an arrow key is pressed, the head should move in that direction non-stop, until a perpendicular
arrow is pressed.
i cant make the head of the snake ( a rectangle) to move non stop in single direction slowly.
i tried to use time.sleep() --> it made the whole code stuck.
i tried to use for loop --> it just made the rectangle to transport to the other direction fast.
this is my main function:
while not GameOver:
#create time delay of 10 milliseconds
pygame.time.delay(10)
# Get all of the events on the game's screen [all of the user's input]
# Loop on the user's activity and look for exit button pressing.
for event in pygame.event.get():
# If the user presses the X button:
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# Define a shortcut name to "get_pressed" method in pygame:
keys = pygame.key.get_pressed()
# defining x location
x = head_position[0]
y = head_position[1]
# if he pressed left key
if keys[pygame.K_LEFT]:
# reducing location by constant
head_position[0] -= head_speed
elif keys[pygame.K_RIGHT]:
# increacing location by constant
head_position[0] += head_speed
elif keys[pygame.K_UP]:
# increacing location by constant
head_position[1] -= head_speed
elif keys[pygame.K_DOWN]:
# increacing location by constant
head_position[1] += head_speed
#If the head passes the screen Boundaries, it would pop in the other side.
if head_position[0] >= WIDTH:
head_position[0] = 0
elif head_position[0] < 0:
head_position[0] = WIDTH-head_size
elif head_position[1] >= HEIGHT:
head_position[1] = 0
elif head_position[1] < 0:
head_position[1] = HEIGHT-head_size
Use the pygame.time module to control the frames per second. Generate a pygame.time.Clock object. If you pass the optional framerate argument to pygame.time.Clock.tick, the function will delay to keep the game running slower than the given ticks per second:
clock = pygame.time.Clock()
while not GameOver:
clock.tick(10) # 10: the game runs with 10 frames per second
# [...]
if you want to make it move at a constant speed in one direction after one key press then make a
right = False varible
then make a
key[pygame.K_YOURCHOICE]:
right = True
if right:
head_pos[1 or 0] -= head_speed

Different colors for shapes through iterations in Python / Pygame?

I'm new to stackoverflow, but was hoping for a little insight from more advanced programmers. I am switching majors to Computer Science next semester and am taking an intro class learning some beginner's Python programming. I have already finished the program below (the assignment was to make a program that draws ovals on the window surface by filling in some of the professor's code, not too bad at all) but I wanted to add a little something extra: As you can see, I have the color of the ovals set to be random, but it stays the same until the program is restarted entirely i.e. all of the ovals are that particular color for the length of the program. With the code written the way it is, I can't figure out a way to get the color to change for each oval. Keep in mind, this is all for kicks, but if anyone's feeling especially helpful or creative, I'm curious to see what you have to say. Let me know if I can expound on anything. Thanks!
import pygame, random, sys
WINDOWWIDTH = 700
WINDOWHEIGHT = 700
BACKGROUNDCOLOR = (150,160,100)
#A different color every run
OVAL_COLOR = (random.randint (0,255),random.randint (0,255),
random.randint (0,255))
pygame.init()
windowSurface = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
pygame.display.set_caption("Mobile Ovals")
#The draw variable is used later to indicate the mouse is still pressed
ovals = []
completedOvals = []
finished = False
draw = False
startXY = (-1, -1)
while not finished:
for event in pygame.event.get():
if event.type == pygame.QUIT or (event.type == pygame.KEYUP and
event.key == pygame.K_ESCAPE):
finished = True
elif event.type == pygame.KEYDOWN:
pressed = pygame.key.get_pressed()
if pressed[pygame.K_F4] and (pressed[pygame.K_LALT] or
pressed[pygame.K_RALT]):
finished = True
elif event.type == pygame.MOUSEBUTTONDOWN:
startXY = event.pos
draw = True
elif event.type == pygame.MOUSEBUTTONUP:
draw = False
for oval in ovals:
completedOvals.append (oval)
if draw == True:
del ovals [:]
#The above function ensures only one oval is onscreen at any given time
endXY = event.pos
width = (abs(endXY[0]-startXY[0]))
height = (abs(endXY[1]-startXY[1]))
#The code below allows the user to drag any direction
if endXY[0] < startXY[0]:
left = endXY[0]
else:
left = startXY[0]
if endXY[1] < startXY[1]:
top = endXY[1]
else:
top = startXY[1]
ovals.append (pygame.Rect (left, top, width, height))
windowSurface.fill(BACKGROUNDCOLOR)
for oval in ovals:
pygame.draw.ellipse(windowSurface, OVAL_COLOR, oval)
for completedOval in completedOvals:
pygame.draw.ellipse(windowSurface, OVAL_COLOR, completedOval)
pygame.display.update()
pygame.quit()
Your problem is quite simple. You set OVAL_COLOR once. But every time you make reference to the variable OVAL_COLOR, you're not creating a new random color, you're re-using the RGB color that was randomly generated when you created the variable.
Now, the way your program is structured, you maintain a list of all complete ovals that you're re-drawing every time the draw variable is set to true. If you place the OVAL_COLOR variable inside the for loop, you will update the color with every mouse movement, changing the color of the oval being drawn, as well as the color of all the old ovals being re-drawn.
The solution to have a new random oval color is to set the variable OVAL_COLOR when the mouse button goes down. That way, the oval color won't change as you drag the mouse to adjust the oval. But, given the current structure of the program, you'll need to save the oval colors assigned to completed ovals, or you'll still have the oval color change each time.
When the mouse button is pressed down, we want a new random color for our circle. Generate a random value, which will be used every time the circle is re-drawn.
elif event.type == pygame.MOUSEBUTTONDOWN:
startXY = event.pos
OVAL_COLOR = (random.randint (0,255),random.randint (0,255),
random.randint (0,255))
draw = True
When the mouse button is released, save the coordinates for the oval, along with the color that it was drawn with.
elif event.type == pygame.MOUSEBUTTONUP:
draw = False
# print len(ovals) # (always ==1)
completedOvals.append ((ovals[-1], OVAL_COLOR))
When we iterate through these completed ovals, draw them with the same color each time.
for (completedOval, color) in completedOvals:
pygame.draw.ellipse(windowSurface, color, completedOval)
Create a simple Oval() class, that contains it's color, and size.
import pygame
from pygame.locals import *
class Oval(object):
"""handle, and draw basic ovals. stores Rect() and Color()"""
def __init__(self, startXY, endXY):
self.color = Color(random.randint(0,255), random.randint(0,255), random.randint(0,255))
self.rect = Rect(0,0,1,1)
self.coord_to_oval(startXY, endXY)
def draw(self):
pygame.draw.ellipse(windowSurface, self.color, self.rect)
def coord_to_oval(self, startXY, endXY):
width = (abs(endXY[0]-startXY[0]))
height = (abs(endXY[1]-startXY[1]))
#The code below allows the user to drag any direction
if endXY[0] < startXY[0]:
left = endXY[0]
else:
left = startXY[0]
if endXY[1] < startXY[1]:
top = endXY[1]
else:
top = startXY[1]
self.rect = Rect(left, top, width, height)
# main loop
while not finished:
for event in pygame.event.get():
# events, and creation:
# ... your other events here ...
elif event.type == MOUSEBUTTONDOWN:
startXY = event.pos
draw = True
elif event.type ==MOUSEBUTTONUP:
# on mouseup, create instance.
endXY = event.pos
oval_new = Oval(startXY, endXY)
completedOvals.append(oval_new)
# draw them:
for oval in ovals:
oval.draw()
for oval in completedOvals:
oval.draw()
I mostly left out your non-completed ovals. Was that to show the size before clicking?

Pygame Inquiry- Generating Multiple Sprites in Same Class

Unimportant Preamble:
Hello, I'm using Python and Pygame to create a game. This is for the purpose of improving my programming skills rather than a serious attempt at game creation. I've taken a break from Python lately for Objective C, but I'm now returning to it. This is a problem that I was having before I took a brief break, and I've returned to a question that was originally puzzling me. I've spent quite a while researching it, and I have a suspicion I've come across the solution and merely failed to understand it. I apologize for some of the bad naming conventions/lack of comments. I'm working on improving that.
Substance of Question:
Anyway, I've attached the four images I'm using. The program uses a simple function to position various Tiles on the screen. The mouse cursor is a sword. It is the entire image, but I'll be changing that later. I've made the program type "blue" in the shell whenever the cursor collides with a Tile. My goal is to have this happen when it collides with "ANY" tile of that color.
Long-term, I want to be able to modify the properties of these tile sprites. Various game-pieces would interact, and I would need to save the state of each sprite. I'd also be setting interactions for the other sprites.
Right now the sprites are all generating images, but my collision rectangle for the Tile is simply moving after each image is generated. I suppose that makes sense given the code, but I need a way to multiple sprites, each with a rectangle for collision.
Thanks
EDIT: I was unable to add images due to a new-user restriction. They are available enter link description here I think I read somewhere that people can (and do) edit posts here. So if anyone who the ability to move the images into this thread is welcome to do so.
import random,math,sys,os
import pygame
from pygame.locals import *
pygame.init() #Initializing Pygame
#Colors
black=(0,0,0)
#Screen
screen=pygame.display.set_mode((1200,800),0,0)
pygame.display.set_caption("Nero's Sandbox")
pygame.mouse.set_visible(False)
clock=pygame.time.Clock()
fps=40
#Game Functions:
def terminate():
pygame.quit()
sys.exit()
def numgen(x,y):
return random.randint(x,y)
#Loop Variables
tri=2
#Groups:
allsprites = pygame.sprite.Group()
alltiles = pygame.sprite.Group()
allmice = pygame.sprite.Group()
#Mouse Classes
class Pointy(pygame.sprite.DirtySprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load('redsword.png').convert() #31x32 image
self.image.set_colorkey(black)
self.rect=self.image.get_rect()
self.set=pygame.sprite.Group()
self.add(allmice, allsprites, self.set)
pygame.sprite.RenderPlain((self.set,allmice,allsprites))
def update(self):
screen.fill(black)
alltiles.draw(screen)
if event.type == pygame.MOUSEMOTION:
pos = pygame.mouse.get_pos()
self.rect.topright = pos
self.set.draw(screen)
#Tile Sprites - only one rect is being recognized.
class Tile(pygame.sprite.Sprite):
def __init__(self, graphic):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load(graphic).convert()
self.image = pygame.transform.scale((self.image),(50,50))
self.rect=self.image.get_rect()
self.add(alltiles, allsprites)
self.set=pygame.sprite.RenderPlain((self))
def update(self, x, y):
pos = (x,y)
self.rect.topleft = pos
#Micers
pointy1=Pointy()
#Game Loops
while True: #Ensures all loops within program are constantly called when conditions are met.
screen.fill(black)
while tri==2:
for event in pygame.event.get():
if event.type == QUIT:
terminate()
pygame.display.flip()
x = 0
y = 50
w = 0
while x!=600:
x=x+50
w = w+1
if w%2==0:
purpletile1=Tile('purplesquare.png')
purpletile1.set.update(x,y)
purpletile1.set.draw(screen)
else:
c=numgen(1,2)
if c==1:
bluetile1=Tile('lightbluesquare.png')
bluetile1.set.update(x,y)
bluetile1.set.draw(screen)
if c==2:
redtile1=Tile('redsquare.png')
redtile1.set.update(x,y)
redtile1.set.draw(screen)
if x>=600 and y!=450:
if y<450:
x = 0
y = y+50
w=w-1
if y>=450:
tri=3
while tri==3:
for event in pygame.event.get():
if event.type == QUIT:
terminate()
alltiles.draw(screen)
pointy1.set.update()
pointy1.set.draw(screen)
pygame.display.flip()
clock.tick(fps)
if pygame.sprite.collide_rect(pointy1,bluetile1):
print('blue')
I had this same problem myself! I did some debugging, and it appeared that all instances of my class shared the same instance of pygame.Rect()
You may want to change the line:
pygame.sprite.Sprite.__init__(self)
to
super.__init__(self)
This way, pygame.sprite.Sprite's init will set attributes to your tile. I could be wrong, I'm not entirely familiar with python's inheritance syntax, but that is the way I do it.
I could also be the get_rect that is causing the same rectangle to be used for all classes, but that doesn't seem to be likely.
I hope that I was some help, and just remember that pygame.Rect is an object, so somehow you are instantiating only once.

Using classes in Pygame

Okay, so I am starting to have fun with pygame. But I've got a problem. I tried to somehow enchance my code, make it organised, so I've decided to use classes here. It looks like this:
import pygame
from pygame.locals import *
import sys
pygame.init()
class MainWindow:
def __init__(self, width, height):
self.width=width
self.height=height
self.display=pygame.display.set_mode((self.width,self.height))
pygame.display.set_caption("Caption")
def background(self)
img = pygame.image.load("image.png")
self.display.blit(img, (0,0))
mainWindow = MainWindow(800,600)
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.exit()
sys.exit()
mainWindow.background()
pygame.display.update()
Okay, works. But what if I want to, for example fill the windows with white color? Then I have to define a method fill(), which will just self.display.fill(), right? Is there a way, to handle it normally, without defining hundreds of pygame-already-existing methods in my class?
And one another thing. If I do something by using my class, and I screw up, I always get this msg:
File "C:/Python35/game.py", line 23, in <module>
pygame.display.update()
pygame.error
And I actually don't know what the heck is wrong. If I do this normally, without classes, then I get erros such as, pygame object blabla has no method blablabla or something like that, I just know what's happening. Is there a way to get through this, and find what's going on?
Thanks in advance for your help!
What you are doing here is on the right track, but it is done the wrong way. Your main "game loop" should be inside the class itself as a method, rather than calling stuff from outside the class in an actual loop. Here is a basic example of what you should be doing.
# Load and initialize Modules here
import pygame
pygame.init()
# Window Information
displayw = 800
displayh = 600
window = pygame.display.set_mode((displayw,displayh))
# Clock
windowclock = pygame.time.Clock()
# Load other things such as images and sound files here
image = pygame.image.load("foo.png").convert # Use convert_alpha() for images with transparency
# Main Class
class MainRun(object):
def __init__(self,displayw,displayh):
self.dw = displayw
self.dh = displayh
self.Main()
def Main(self):
#Put all variables up here
stopped = False
while stopped == False:
window.fill((255,255,255)) #Tuple for filling display... Current is white
#Event Tasking
#Add all your event tasking things here
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
elif event.type == pygame.KEYDOWN:
stopped = True
#Add things like player updates here
#Also things like score updates or drawing additional items
# Remember things on top get done first so they will update in the order yours is set at
# Remember to update your clock and display at the end
pygame.display.update()
windowclock.tick(60)
# If you need to reset variables here
# This includes things like score resets
# After your main loop throw in extra things such as a main menu or a pause menu
# Make sure you throw them in your main loop somewhere where they can be activated by the user
# All player classes and object classes should be made outside of the main class and called inside the class
#The end of your code should look something like this
if __name__ == __main__:
MainRun()
The main loop will call itself when the object MainRun() is created.
If you need more examples on specific things such as object handling let me know and I will see if I can throw some more information up for you.
I hope this helps you with your programming and the best of luck to you.
========================= EDIT ================================
In this case for these special operations make them object specific. Instead of using one generic method to blit your objects, make each object have its own function. This is done this way to allow for more options with each object you make. The general idea for the code is below... I have created a simple player object here.
#Simple player object
class Player(object):
def __init__(self,x,y,image):
self.x = x
self.y = y
self.image = image
#Method to draw object
def draw(self):
window.blit(self.image,(self.x,self.y))
#Method to move object (special input of speedx and speedy)
def move(self,speedx,speedy):
self.x += speedx
self.y += speedy
Now here is how you use the object's methods... I have included an event loop to help show how to use the move function. Just add this code to your main loop wherever it is needed and you will be all set.
#Creating a player object
player = Player(0,0,playerimage)
#When you want to draw the player object use its draw() method
player.draw()
#Same for moving the player object
#I have included an event loop to show an example
#I used the arrow keys in this case
speedx = 0
speedy = 0
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
speedy = -5
speedx = 0
elif event.key == pygame.K_DOWN:
speedy = 5
speedx = 0
elif event.key == pygame.K_RIGHT:
speedy = 0
speedx = 5
elif event.key == pygame.K_LEFT:
speedy = 0
speedx = -5
elif event.type == pygame.KEYUP:
speedx = 0
speedy = 0
#Now after you event loop in your object updates section do...
player.move(speedx,speedy)
#And be sure to redraw your player
player.draw()
#The same idea goes for other objects such as obstacles or even scrolling backgrounds
Be sure to use the same display name of the display inside your draw function.

Categories

Resources