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)
Related
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
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
I have created some sort of menu navigation system in my game. All the screens are blitted in. The "Play" and "Quit" and "Controls" button works just fine but when I try to press menu from the controls screen, nothing happens. On the controls screen, you can faintly see the first menu screen from before. That might be the problem. I think that as the return to menu button is over the previous controls page button, it somehow is pressing the controls button from before. The button and menu segment of my code will be pasted here and the full thing will be pasted in a pastebin.
def text_to_button(msg,color,buttonx,buttony,buttonwidth,buttonheight,size = "small"):
textSurf, textRect = text_objects(msg,color,size)
textRect.center = ((buttonx + buttonwidth/2)), buttony+(buttonheight/2)
gameDisplay.blit(textSurf, textRect)
def button(text,x,y,width,height,inactive_color,active_color,size = "small",action = None):
cur = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
#print(click)
if x + width > cur[0] > x and y + height > cur[1] > y:
pygame.draw.rect(gameDisplay, active_color,(x,y,width,height))
if click[0] == 1 and action != None:
if action == "quit":
pygame.quit()
quit()
if action == "controls":
game_controls()
if action == "play":
gameLoop()
if action == "main":
game_intro()
else:
pygame.draw.rect(gameDisplay, inactive_color,(x,y,width,height))
text_to_button(text,black,x,y,width,height,size)
def game_controls():
gcont = True
while gcont:
gameDisplay.blit(cont,(0,0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
button("Play",150,500,100,50,white,gray,"small",action = "play")
button("Main Menu",320,500,150,50,white,gray,"tiny", action = "main")
button("Quit",550,500,100,50,white,gray,"small", action = "quit")
pygame.display.update()
clock.tick(15)
def game_intro():
intro = True
while intro:
gameDisplay.blit(imggg,(0,0))
button("Play",150,500,100,50,white,gray,"small",action = "play")
button("ControLs",320,500,150,50,white,gray,"tiny", action = "controls")
button("Quit",550,500,100,50,white,gray,"small", action = "quit")
pygame.display.update()
clock.tick(15)
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_p:
intro = False
Full Code: https://pastebin.com/jrd82gkJ
You will have very hard time to debug your code in order to achieve the behavior you want for one simple reason:
The logic you use to switch between different screens providing different functionality is causing much trouble you can't directly see if you only run the game.
So you think: "oh ... how come the button doesn't work, there must be an issue with the button".
You are probably not aware of the fact that using functions having own while loops you go deeper and deeper into recursive calls with increasing recursion depth with each switch from one view to another - it is not how pygame is thought to be programmed.
I suggest you add some print() commands into your code to see in the console output that the code doesn't really do what you expect even if it appears to be OK at the first glance because it works.
Then I suggest you REWRITE your entire code so that you have one main while notGameExit: loop, and don't use any other looping in the helper functions. If you want use looping in your helper functions at least don't call from the helper functions another functions with own loops (and so on), but RETURN from them with an explicit return to avoid recursion.
If you leave the in the main loop called function with return your main loop will continue running and depending on some switches you can display in it different things on the screen and react differently to user actions.
Maybe looking at a minimal working pygame script showing "action" without usage of a loop you will gain better understanding and some deep "enlightenment" about how pygame works and then start a total rewrite of your game using another approach as this one you have used in the current code? Then come back with what you have achieved if you have further questions, but you won't probably have any, because it would be much easier to debug it yourself if the code will become more straightforward.
import pygame
pygame.init() # start PyGame (necessary because 'import pygame' doesn't start PyGame)
winDisplay = pygame.display.set_mode((1024, 768)) # set PyGame window size to 1024x768 pixel
pygame.display.set_caption("Minimal PyGame Test Script")
# Time in pygame is measured in milliseconds (1/1000 seconds) (defined by TIMER_RESOLUTION constant):
pygame.TIMER_RESOLUTION = 1000 # assure 1000 explicit, don't relay on default value
colorWhite = (255, 255, 255) # RGB color in Pygame format (valueRed=255, valueGreen=255, valueBlue=255)
colorRed = (255, 0, 0)
colorGreen = ( 0, 255, 0)
colorBlue = ( 0, 0, 255)
winDisplay.fill(colorWhite)
pygame.display.update()
pygame.time.wait(3000) # show the Pygame window for 3 seconds
winDisplay.fill(colorRed)
pygame.display.update()
pygame.time.wait(3000) # show the Pygame window for 3 seconds
winDisplay.fill(colorGreen)
pygame.display.update()
pygame.time.wait(3000) # show the Pygame window for 3 seconds
winDisplay.fill(colorBlue)
pygame.display.update()
pygame.time.wait(3000) # show the Pygame window for 3 seconds
winDisplay.fill(colorWhite)
pygame.display.update()
pygame.time.wait(3000) # show the Pygame window for 3 seconds
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?
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.