I am trying to create a game where "player_one.png" is controlled by the arrow keys to move around and dodge a bunch of randomly placed "player_two.png" that can move around on their own in random directions on a football field.
I have created a program that displays the field and the two images. I am having difficulty getting "player_two.png" display multiple copies on the field and cannot get them to move.
I also cannot get the "player_one.png" image to move based on the arrow key. I found a program using Sprites that moves a red block in the same way I want my player to move but cannot switch out the sprite with my image.
Here is my initial set-up which displays the field and the two images facing each other.
import pygame
import random
pygame.init()
#colors
black = (0, 0, 0)
white = (255, 255, 255)
green = (0, 100, 0)
red = (255, 0, 0)
size = [1000, 500]
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Tony's newest game attempt")
#boolean for while loop
done = False
#create clock
clock = pygame.time.Clock()
#declare font
font = pygame.font.Font(None, 25)
player_one = pygame.image.load("player_one.png").convert()
player_one.set_colorkey(white)
player_two = pygame.image.load("player_two.png").convert()
player_two.set_colorkey(white)
while done == False:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
screen.fill(green)
for x in range(60,940,35):
pygame.draw.line(screen, white, [x, 0], [x, 500], 1)
score = 0
text = font.render("Score:" +str(score), True, black)
screen.blit(text, [0, 0])
screen.blit(player_one, [940, 240])
screen.blit(player_two, [60, 240])
pygame.display.flip()
clock.tick(20)
pygame.quit()
The sprite program that uses a class (something I could not get to work with images) moves the Player sprite using this code: (Please note this is not the entire program).
class Player(pygame.sprite.Sprite):
# Constructor function
def __init__(self, color, x, y):
# Call the parent's constructor
pygame.sprite.Sprite.__init__(self)
# Set height, width
self.image = pygame.Surface([35, 35])
self.image.fill(color)
# Make our top-left corner the passed-in location.
self.rect = self.image.get_rect()
self.rect.x = 930
self.rect.y = 250
def reset_player(self):
self.rect.x = 930
self.rect.y = 250
# Find a new position for the player
def update(self):
self.rect.x += self.change_y
self.rect.y += self.change_x
while done == False:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done=True
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
player.rect.x -= player.rect.width
elif event.key == pygame.K_RIGHT:
player.rect.x += player.rect.width
elif event.key == pygame.K_UP:
player.rect.y -= player.rect.height
elif event.key == pygame.K_DOWN:
player.rect.y += player.rect.height
# -- Draw everything
# Clear screen
screen.fill(green)
for x in range(60,940,35):
pygame.draw.line(screen, white, [x, 0], [x, 500], 1)
# Draw sprites
all_sprites_list.draw(screen)
text = font.render("Score: "+str(score), True, black)
screen.blit(text, [10, 10])
# Flip screen
pygame.display.flip()
# Pause
clock.tick(20)
pygame.quit()
Can someone please help me figure out how to get my image to move the way the sprite does. Or help me display "player_two.png" all over the field and move in random directions. It would be best if the "player_two.png" moved every once every 3 times I hit an arrow key. If this is vague please email me and I can send my code. I need to finish this game in 2 weeks!
Multiple comments on the game -
I don't see where self.change_y is defined. Also, shouldn't the update function be like - self.rect.x += self.change_x instead of self.rect.x += self.change_y?
Also, the main loop should be something like this
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done=True
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
if player.rect.x > 0:
player.rect.x -= player.rect.width
elif event.key == pygame.K_RIGHT:
if player.rect.x < screen_width: # the screen/game width
player.rect.x += player.rect.width
# Something similar for the up & down keys
I would recommend you to look at this question.
I think you have the right idea but aren't executing it well.
Try going to your game loop and when displaying an image, display like so:
gameDisplay.blit(player1, (player1X,player1Y))
This way, you can use a if statement to change playerX and player1Y. Insert the following code under the code that quits pygame:
elif e.type == pygame.KEYDOWN:
if e.key == pygame.K_LEFT:
player1X -= 5
pygame.display.update()
elif e.key == pygame.K_RIGHT:
player1X += 5
pygame.display.update()
The reason this works is because the variable that is defining X and Y are not staic. You can also do the same thing for up and down using:
elif e.key == pygame.K_UP:
or
elif e.key == pygame.K_DOWN:
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I'm making Mario with pygame for my class assessment this school term and am sorta new to pygame, i can't find anywhere how to properly implement gravity into my game, so when mario jumps, he comes back down. My second problem is trying to make a running animation, i want Mario to flick through pictures as he moves left and right in the order; 1, 2, 3, 2 (and over and over). If someone could help it would be great!
import pygame
import time
import random
pygame.init()
display_width = 800
display_height = 600
mario_width = 55
blue = (77, 240, 255)
green = (0, 186, 43)
ground_colour = (186, 150, 97)
gameDisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption("Super Italiano Bros")
direction = 'right'
clock = pygame.time.Clock()
cloudImg = pygame.image.load('Cloud.png')
rightMarioImg = pygame.image.load('MarioRight.png')
rightMarioImg2 = pygame.image.load("MarioRight2.png")
rightMarioImg3 = pygame.image.load("MarioRight3.png")
leftMarioImg = pygame.image.load('MarioLeft.png')
leftMarioImg2 = pygame.image.load('MarioLeft2.png')
leftMarioImg3 = pygame.image.load('MarioLeft3.png')
def marioRight(x,y):
gameDisplay.blit(rightMarioImg, (x,y))
def marioLeft(x,y):
gameDisplay.blit(leftMarioImg, (x,y))
def cloud(x_cloud,y_cloud):
gameDisplay.blit(cloudImg, (x_cloud,y_cloud))
def cloud_two(x_cloud_two,y_cloud_two):
gameDisplay.blit(cloudImg, (x_cloud_two,y_cloud_two))
def game_loop():
global direction
x = (320)
y = (360)
x_cloud = (-200)
y_cloud = (-220)
x_cloud_two = (200)
y_cloud_two = (-170)
x_change = (0)
y_change = (0)
gameExit = False
while not gameExit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameExit = True
print(event)
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x_change = -5
direction = 'left'
if event.key == pygame.K_RIGHT:
x_change = 5
direction = 'right'
if event.key == pygame.K_UP:
y_change = -60
if event.key == pygame.K_ESCAPE:
gameExit = True
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT or event.key == pygame.K_UP:
x_change = 0
y_change = 60
x += x_change
y += y_change
if x <= 0:
x = 0
if y <= 300:
y = 300
if y >= 360:
y = 360
gameDisplay.fill(blue)
pygame.draw.rect(gameDisplay, ground_colour, (0,500,800,500))
pygame.draw.rect(gameDisplay, green, (0, 470, 800, 30))
cloud(x_cloud,y_cloud)
cloud_two(x_cloud_two,y_cloud_two)
if direction == 'right':
marioRight(x,y)
else:
marioLeft(x,y)
pygame.display.update()
clock.tick(60)
game_loop()
pygame.quit()
quit()
Fixed some issues and did a lot of code styling. When you press the up key he jumps a fixed amount and when you release it he goes back to the ground level. Now it animates itself. The image is changed every loop, which is probably super fast, so you will probably only want to increase the state every a certain amount of frames.
Summary of what I changed:
Imports are usually grouped in three different blocks (divided by a single blank line) and ordered alphabetically:
The first block contains all standard library imports
The second block contains third party libraries
The third block contains local imports to other files in this project
A file should have 0 not used imports
Function and variable names in python follow snake case notation: my_variable and my_function. "Constants" are written in snake upper case: MY_CONSTANT. Classes use camel case: MyClass.
dicts and lists allow you to store data in a more organized way. For example, we can have a MARIO_IMGS dict of lists that store all the mario images so they can be accessed like MARIO_IMGS['right'][0] (the first image is index 0 as lists start counting by 0).
Try to avoid global variables, I moved the variables that were only needed inside the loop to the game_loop function and the remaining top level statements that were not definitions isnide a if __name__ == '__main__': block that runs whenever this script is launched but not when this scrip is imported.
Functions are meant to be reused, having cloudand cloud_two functions that do exactly the same makes no sense. Call cloud(x_cloud, y_cloud) and then cloud(x_cloud_two, y_cloud_two).
Do not use unneeded brackets if they do not provide clarity, for example: x = (320) should be x = 320
You had a indentation error where you process events outside the event loop, so only the last event would be processed (except for exiting, that part was inside the loop so every event would be checked against pygame.QUIT)
Lines should be 80 chars or lower.
quit() at the end of a python file is not needed. quit() is mostly used to close the python interpreter from a terminal window.
import pygame
# Window width and height in px
DISPLAY_SIZE = (800, 600)
# Window title
TITLE = "Super Italiano Bros"
# Predefined colors
BLUE = (77, 240, 255)
GREEN = (0, 186, 43)
GROUND_COLOR = (186, 150, 97)
# Images
MARIO_IMGS = {
'right': [
pygame.image.load('MarioRight.png'),
pygame.image.load("MarioRight2.png"),
pygame.image.load("MarioRight3.png"),
pygame.image.load("MarioRight2.png"),
],
'left': [
pygame.image.load('MarioLeft.png'),
pygame.image.load('MarioLeft2.png'),
pygame.image.load('MarioLeft3.png'),
pygame.image.load('MarioLeft2.png'),
]
}
CLOUD_IMG = pygame.image.load('Cloud.png')
MAX_STATES = min(map(len, MARIO_IMGS.values())) # 3
def draw_mario(x, y, direction='right', state=0):
screen.blit(MARIO_IMGS[direction][state], (x, y))
def draw_cloud(x_cloud, y_cloud):
screen.blit(CLOUD_IMG, (x_cloud, y_cloud))
def game_loop():
# Mario position
x = 320
y = 360
x_change = 0
state = 0
direction = 'right'
# Cloud positions
x_cloud = -200
y_cloud = -220
x_cloud_two = 200
y_cloud_two = -170
# Clock used to limit the FPS
clock = pygame.time.Clock()
game_exit = False
while not game_exit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_exit = True
print(event)
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x_change = -5
direction = 'left'
if event.key == pygame.K_RIGHT:
x_change = 5
direction = 'right'
if event.key == pygame.K_UP:
y = 300
if event.key == pygame.K_ESCAPE:
game_exit = True
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
x_change = 0
elif event.key == pygame.K_UP:
y = 360
x += x_change
if x < 0:
x = 0
elif x > DISPLAY_SIZE[0]:
x = DISPLAY_SIZE[0]
screen.fill(BLUE)
pygame.draw.rect(screen, GROUND_COLOR, (0, 500, 800, 500))
pygame.draw.rect(screen, GREEN, (0, 470, 800, 30))
draw_cloud(x_cloud, y_cloud)
draw_cloud(x_cloud_two, y_cloud_two)
draw_mario(x, y, direction, state)
# Increase the state to animate Mario
state += 1
state %= MAX_STATES # Start back from 0 if we have reached the end
pygame.display.update()
clock.tick(60)
if __name__ == '__main__':
pygame.init()
screen = pygame.display.set_mode(DISPLAY_SIZE)
pygame.display.set_caption(TITLE)
game_loop()
pygame.quit()
You should probably change your mario and cloud to Sprites. An Sprite is a class that has a rect and an image attributes that define how they are drawn, and then instead of using screen.blit(IMAGE, POSITION) you just tell pygame to draw the sprite and he will use those two attributes to draw the desired image at the position of the rect.
The cube is only moving once.
import time
import pygame
pygame.init()
class Window(object):
def __init__(self, width, height, bg):
self.width = width
self.height = height
self.bg = bg
def create(self):
return pygame.display.set_mode((self.width, self.height))
The problem is somewhere here
class Cube(object):
def __init__(self, surface, x, y, width, height, color):
self.surface = surface
self.x = x
self.y = y
self.width = width
self.height = height
self.color = color
def move(self, lead_x_change=0, lead_y_change=0):
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
lead_x_change = -20
elif event.key == pygame.K_RIGHT:
lead_x_change = 20
elif event.key == pygame.K_UP:
lead_y_change = -20
elif event.key == pygame.K_DOWN:
lead_y_change = 20
self.x += lead_x_change
self.y += lead_y_change
def draw(self):
pygame.draw.rect(self.surface, self.color, (self.x, self.y, self.width, self.height))
window = Window(800, 600, (0, 0, 0))
surface = window.create()
head = Cube(surface, 400, 300, 20, 20, (255, 255, 255))
starting gameloop
gameloop = True
while gameloop:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
head.move()
surface.fill((0, 0, 0))
head.draw()
pygame.display.update()
The Cube moves, but only one time after a keypress. it should continiously move in one direction though, after pressing the direction.
I dont know how to make it move continiously, even watched ton of videos about it and still dont understand.
Based on the comment that OP wants the movement to occur until another key is pressed, as opposed to whether a key is held down, there is an entirely separate solution involved. Instead, the code must be refactored to instead include a variable for the last direction that was pressed, and a timed loop to continuously move in that direction.
In the Cube's __init__ method, add:
self.lastDir = null
Make a new method in the Cube class for handling the key event:
def updateDir(self, event):
if event.type == pygame.KEYDOWN and event.key in [pygame.K_LEFT, pygame.K_RIGHT, pygame.K_UP, pygame.K_DOWN]:
self.lastDir = event.key
Modify the move method to instead be based on self.lastDir instead of event.key:
if self.lastDir != null:
if self.lastDir == pygame.K_LEFT:
lead_x_change = -20
...
And finally, modify the main loop to call the move method on a regular basis, as opposed to waiting for a new move:
gameloop = True
while gameloop:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
head.updateDir(event)
head.move()
surface.fill((0, 0, 0))
head.draw()
pygame.display.update()
# Insert time.sleep(seconds) here if too fast
Maybe because when you are calling the method
head.move()
and have in the method parameters set lead changes to 0.
and when it is called it's always 0.
Try changing
def move(self, lead_x_change=0, lead_y_change=0):
to
def move(self, lead_x_change, lead_y_change):
I'm not 100% sure this will work.
Let me know!
In the main loop, when you call pygame.event.get(), the program is waiting until a new event occurs. In pygame, only a new key press qualifies as an "event"; holding a key down will not continuously fire an "event".
Instead, you will need to call a different function. As per this question, pygame.key.get_pressed() is probably more what you are looking for. You will want to modify your main loop so it runs even when an event is not present, like so:
gameloop = True
while gameloop:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
# Note the next line is un-indented, so it executes anyway
head.move()
surface.fill((0, 0, 0))
head.draw()
pygame.display.update()
And also fix the move() method to be structured like:
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
lead_x_changed = -1 # Will move much faster now
elif keys[pygame.K_RIGHT]:
...
I am trying to move a sprite (called Player) to the left or right by pressing the arrow keys. The movement to the right or left would be made by changing the center of the rectangle of the sprite. As you might be able to see, I am trying to add/subtract 8 from the sprite's x coordinates in order to move it right or left. However, the sprite doesn't move when I hit an arrow key. How can I fix this?
import pygame
import random
import time
import pygame as pg
# set the width and height of the window
width = 800
height = 370
groundThickness = 30
pheight = 50
pwidth = 50
playerx = 0+pwidth
playery = height-groundThickness-pheight/2
fps = 30
# define colors
white = (255, 255, 255)
black = (0, 0, 0)
red = (5, 35, 231)
# initialize pygame
pygame.init()
# initialize pygame sounds
pygame.mixer.init()
# create window
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("my game")
clock = pygame.time.Clock()
class Player(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface((pwidth, pheight))
self.image.fill(red)
self.rect = self.image.get_rect()
self.rect.center = (playerx, playery)
all_sprites = pygame.sprite.Group()
player = Player()
all_sprites.add(player)
# Game loop
running = True
x_change = 0
while running:
# keep loop running at the right speed
clock.tick(fps)
# Process input (events)
for event in pygame.event.get():
# check for closing window
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
print("left")
x_change = -8
elif event.key == pygame.K_RIGHT:
print("right")
x_change = 8
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
x_change = 0
print(x_change)
playerx += x_change
all_sprites.update()
#ground
pygame.draw.rect(screen, (0,255,0), ((0, height-groundThickness), (width, groundThickness)))
# Update
all_sprites.update()
# Draw / render
all_sprites.draw(screen)
pygame.display.update()
# AFTER drawing everything, flip the display
pygame.display.flip()
pygame.quit()
You've never altered the position of the sprite player.
How do you expect it to move?
All you've done is to change the value of your local variable playerx, but you've never pushed that change back into the sprite object.
Start by adding the middle line below:
playerx += x_change
player.rect.center = (playerx, playery)
all_sprites.update()
See how that alters things? Can you take it from there?
Filling the screen with your background color or image will also be needed to keep your screen updated with the current position of the moving sprite. The following command will be added at the top of your draw/render section of the game loop:
screen.fill(black)
I'm working on a racing game. I have been using this code but my player keeps moving once only. How do I solve this problem?
change = 7
dist = 7
change_r = 0
change_l = 0
dist_u = 0
dist_d = 0
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
change_r = True
elif event.key == pygame.K_LEFT:
change_l = True
elif event.key == pygame.K_UP:
dist_u = True
elif event.key == pygame.K_DOWN:
dist_d = True
if event.type == pygame.KEYUP:
if event.key == pygame.K_RIGHT or event.key == pygame.K_LEFT or event.key == pygame.K_UP or event.key == pygame.K_DOWN:
change_r = False
change_l = False
dist_u = False
dist_d = False
clock.tick(60)
if change_r == True:
x += change
if change_l == True:
x -= change
if dist_u == True:
y -= dist
if dist_d == True:
y += dist
There are different ways you could go about making move-able shapes/sprites using Pygame. The code you posted in your question seems overly complex. I'll give you two different ways that are simpler, and easier to use. Using a sprite class, and using a function.
It may not seem like I'm answering your question, but if I just told you what to fix in your code you posted, I'd just be knowingly steering you down a road that will lead to many problems, and much complexity in the future.
Method 1: Using a sprite class
To make a your race car sprite, you could use a sprite class like the one below.
class Player(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface((50, 50))
self.image.fill((255, 0, 0))
self.rect = self.image.get_rect()
self.rect.x = WIDTH / 2
self.rect.y = HEIGHT / 2
self.vx = 0
self.vy = 0
def update(self):
self.vx = 0
self.vy = 0
key = pygame.key.get_pressed()
if key[pygame.K_LEFT]:
self.vx = -5
elif key[pygame.K_RIGHT]:
self.vx = 5
if key[pygame.K_UP]:
self.vy = -5
elif key[pygame.K_DOWN]:
self.vy = 5
self.rect.x += self.vx
self.rect.y += self.vy
Since your class is inheriting from Pygame's sprite class, You must name your image self.image and you must name your rectangle for the image self.rect. As you can also see, the class has two main methods. One for creating the sprite(__init__) and one for updating the sprite(update)
To use your class, make a Pygame sprite group to hold all your sprites, and then add your player object to the group:
sprites = pygame.sprite.Group()
player = Player()
sprtites.add(player)
And to actual render your sprites to the screen call sprites.update() and sprites.draw() in your game loop, where you update the screen:
sprites.update()
window_name.fill((200, 200, 200))
sprites.draw(window_name)
pygame.display.flip()
The reason i highly recommended using sprite classes, is that it will make your code look much cleaner, and be much easier to maintain. You could even move each sprite class to their own separate file.
Before diving fully into the method above however, you should read up on pygame.Rect objects and pygame.sprite objects, as you'll be using them.
Method 2: Using A function
If you prefer not to get into sprite classes, you can create your game entities using a function similar to the one below.
def create_car(surface, x, y, w, h, color):
rect = pygame.Rect(x, y, w, h)
pygame.draw.rect(surface, color, rect)
return rect
If you would still like to use a sprites, but don't want to make a class just modify the function above slightly:
def create_car(surface, x, y, color, path_to_img):
img = pygame.image.load(path_to_img)
rect = img.get_rect()
surface.blit(img, (x, y))
Here is an example of how i would use the functions above to make a movable rectangle/sprite:
import pygame
WIDTH = 640
HEIGHT = 480
display = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Moving Player Test")
clock = pygame.time.Clock()
FPS = 60
def create_car(surface, x, y, w, h, color):
rect = pygame.Rect(x, y, w, h)
pygame.draw.rect(surface, color, rect)
return rect
running = True
vx = 0
vy = 0
player_x = WIDTH / 2 # middle of screen width
player_y = HEIGHT / 2 # middle of screen height
player_speed = 5
while running:
clock.tick(FPS)
for e in pygame.event.get():
if e.type == pygame.QUIT:
running = False
pygame.quit()
quit()
if e.type == pygame.KEYDOWN:
if e.key == pygame.K_LEFT:
vx = -player_speed
elif e.key == pygame.K_RIGHT:
vx = player_speed
if e.key == pygame.K_UP:
vy = -player_speed
elif e.key == pygame.K_DOWN:
vy = player_speed
if e.type == pygame.KEYUP:
if e.key == pygame.K_LEFT or e.key == pygame.K_RIGHT or\
e.key == pygame.K_UP or e.key == pygame.K_DOWN:
vx = 0
vy = 0
player_x += vx
player_y += vy
display.fill((200, 200, 200))
####make the player#####
player = create_car(display, player_x, player_y, 10, 10, (255, 0, 0))
pygame.display.flip()
As you may see above, your code for moving your race car can be simplified.
I should note, I'm assuming a few things with each method outlined above.
That your either using a circle, square, or some type of pygame shape object.
Or that your using a sprite.
If your not currently using any of the methods outlined above, I suggest that you do. Doing so will make your code much eaiser to maintain once you begin to build larger and more complex games.
You should have a global loop irrespective of your event handling. You should place your clock.tick() and your movement there. Namely:
#some constants here
while True:
pygame.display.update()
clock.tick(60)
#update you game state
if change_r == True:
x += change
if change_l == True:
x -= change
if dist_u == True:
y -= dist
if dist_d == True:
y += dist
for event in pygame.event.get():
# react to player input by changing the game state
So I am getting an error saying that the super() takes 1 argument but what argument does it want to take??? I really don't know which it's asking for! Can someone help me fix it or at least tell me what's wrong?
import pygame
# Define some colors
BLACK = ( 0, 0, 0)
WHITE = ( 255, 255, 255)
GREEN = ( 0, 255, 0)
RED = ( 255, 0, 0)
class Me(pygame.sprite.Sprite):
super().__init__()
def __init__(self, color, width, height):
self.image = pygame.Surface([width, height])
self.image.fill(color)
self.rect = self.image.get_rect()
you = pygame.sprite.Group()
all_sprites_list = pygame.sprite.Group()
player = Player(GREEN, 20, 15)
all_sprites_list.add(player)
pygame.init()
# Set the width and height of the screen [width, height]
size = (800, 600)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Karl's Game")
#Loop until the user clicks the close button.
done = False
# Used to manage how fast the screen updates
clock = pygame.time.Clock()
#Loading pictures
background_image = pygame.image.load("back.jpg").convert()
#Variables
# Speed in pixels per frame
x_speed = 0
y_speed = 0
# Current position
x_coord = 10
y_coord = 10
# -------- Main Program Loop -----------
while not done:
# --- Main event loop
for event in pygame.event.get(): # User did something
if event.type == pygame.QUIT: # If user clicked close
done = True # Flag that we are done so we exit this loop
elif event.type == pygame.KEYDOWN:
# Figure out if it was an arrow key. If so
# adjust speed.
if event.key == pygame.K_LEFT:
x_speed = -3
elif event.key == pygame.K_RIGHT:
x_speed = 3
if x_coord > 200:
x_speed = 0
elif event.key == pygame.K_UP:
y_speed = -3
elif event.key == pygame.K_DOWN:
y_speed = 3
elif event.type == pygame.KEYUP:
# If it is an arrow key, reset vector back to zero
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
x_speed = 0
elif event.key == pygame.K_UP or event.key == pygame.K_DOWN:
y_speed = 0
x_coord = x_coord + x_speed
y_coord = y_coord + y_speed
player.rect.x = pos[x_coord]
player.rect.y = pos[y_coord]
# First, clear the screen to white. Don't put other drawing commands
# above this, or they will be erased with this command.
# --- Drawing code should go here
screen.blit(background_image, [0,0])
drawSquare(screen, x_coord, y_coord)
# --- Go ahead and update the screen with what we've drawn.
pygame.display.flip()
# --- Limit to 60 frames per second
clock.tick(45)
# Close the window and quit.
# If you forget this line, the program will 'hang'
# on exit if running from IDLE.
pygame.quit()
You must move you super() call inside you class init(self): function. It should be the first line iside the method.
Also, the super call should read.
super(Me, self).__init__()