I am working on a little project to get to know Pygame and I was working with the following tutorial to introduce myself:
https://www.101computing.net/pong-tutorial-using-pygame-getting-started/
After following that tutorial and making tweaks of my own (mainly stylistic, nothing functional), every time I run the program the ball just goes back and forth on the same y coordinate and won't go up and down. It seems like everything else works but the variation in the vertical movement of the ball.
I can provide my code if needed as well, but it looks similar to the tutorial above.
edit: here's the code
import pygame
#need random integers for velocity changes
import random
Black = (0,0,0)
#create ball object for the game, wil be a sprite object
class Ball(pygame.sprite.Sprite):
#define the package function and also call the pygame sprite constructor using super()
def __init__(self, color, width, height):
super().__init__()
self.image = pygame.Surface([width, height])
self.image.fill(Black)
self.image.set_colorkey(Black)
#draw the ball
pygame.draw.rect(self.image, color, [0, 0, width, height])
#set velocity
self.velocity = [random.randint(4,8), random.randint(-8,8)]
#get rectangle object from image package
self.rect = self.image.get_rect()
def update(self):
self.rect.x += self.velocity[0]
self.rect.y += self.velocity[1]
#reverse velocity path of ball hits paddle
def bounce(self):
self.velocity[0] = -self.velocity[0]
self.velocity[1] = random.randint(-8,8)
-----Main File-----
import pygame
#import paddle sprites
from paddle import Paddle
#import ball
from ball import Ball
import time
pygame.init()
#set local colors: Black for background, white for text, blue and red for teams
Black = (0,0,0)
White = (255,255,255)
Red = (255,0,0)
Blue = (0,0,255)
#create paddles using paddle class and add them to a list of sprites
paddleLeft = Paddle(Red, 10, 100)
paddleLeft.rect.x = 20
paddleLeft.rect.y = 200
paddleRight = Paddle(Blue, 10, 100)
paddleRight.rect.x = 870
paddleRight.rect.y = 200
ball = Ball(White, 10, 10)
ball.rect.x = 445
ball.rect.y = 195
allSprites = pygame.sprite.Group()
allSprites.add(paddleLeft)
allSprites.add(paddleRight)
allSprites.add(ball)
#set game window
size = (900,500)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Multiplayer Pong")
#to the functionality, we will have a while loop that will listen to user inputs, adding logic to the game (score, boundaries, etc.), and refreshing the program
#global "running" funtion that will control the while loop, simple bool
running = True
#need a clock for refreshing the screen (included in pygame package)
clock = pygame.time.Clock()
#scores for each side
scoreLeft = 0
scoreRight = 0
#start loop
while running:
#--listen for inputs
for event in pygame.event.get():
if event.type == pygame.QUIT: #if quit button is pressed, leave
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_x:
running = False
#keyboard inputs
key = pygame.key.get_pressed()
if key[pygame.K_w]:
paddleLeft.mUp(5)
if key[pygame.K_s]:
paddleLeft.mDown(5)
if key[pygame.K_UP]:
paddleRight.mUp(5)
if key[pygame.K_DOWN]:
paddleRight.mDown(5)
#--logic
allSprites.update()
#--drawing here (paddles, screen, scores, boundaries, etc
screen.fill(Black)
pygame.draw.line(screen, White, [448, 0], [448, 500], 4)
allSprites.draw(screen)
#check for wall bounce
#algorithms for bounce look like
#Hits right or left wall? reverse X-bound velocity
#Hits top or bottom wall? reverse Y-bound velocity
if ball.rect.x >= 890:
scoreLeft += 1
ball.rect.x = 445
ball.rect.y = 195
time.sleep(2)
ball.velocity[0] = -ball.velocity[0]
if ball.rect.x <= 0:
scoreRight += 1
ball.rect.x = 445
ball.rect.y = 195
time.sleep(2)
ball.velocity[0] = -ball.velocity[0]
#reverse ball angle
if ball.rect.y >= 490:
ball.velocity[1] = -ball.velocity[1]
if ball.rect.y >= 0:
ball.velocity[1] = -ball.velocity[1]
#check for paddle hit
if pygame.sprite.collide_mask(ball, paddleLeft) or pygame.sprite.collide_mask(ball, paddleRight):
ball.bounce()
#display scores
font = pygame.font.SysFont("impact.ttf", 50)
text = font.render(str(scoreLeft), 1, Red)
screen.blit(text, (420,10))
text = font.render(str(scoreRight), 1, Blue)
screen.blit(text, (460,10))
#--update screen with drawings
pygame.display.flip()
#--60 fps limit
clock.tick(60)
#stop program once main loop is exited
pygame.quit()
After some debugging I realized that the y values was constantly hopping from some value up then down, the velocity seemed to work but it was constantly changing signs
The problem is on line 103 the:
if ball.rect.y >= 0:
you must of missed typed it as the y value will always be greater then 0, I fixed it by switching it to
if ball.rect.y <= 0:
and it worked.
Related
I am making a space invaders game where the enemy hits the left or right side of the screen it will go down. However, I am struggling to figure out how to do the same thing but in reverse. So when it hits the end of the screen it will move left/right. Here is the code for the enemy.
import pygame
import random
# Initialize Pygame
pygame.init()
# Creates the screen for pygame
screen = pygame.display.set_mode((1000, 800))
#Enemy1
enemy1image = pygame.image.load('Enemy1.png')
enemy1image = pygame.transform.scale(enemy1image, (80, 80))
#Make it appear in a random cordinate
enemy1X = random.randint (0,1000)
enemy1y = random.randint(40,300)
enemy1X_change = 3
enemy1Y_change = 30
enemy1y_change_reverse = -30
def enemy1(x,y):
#Draws Enemy1 on screen
screen.blit(enemy1image,(x,y))
#Enemy1 Movement/boundaries
enemy1X += enemy1X_change
enemy1(enemy1X, enemy1y)
#Every time the enemy hits the boundary, it moves down
if enemy1X <= 0:
enemy1X_change = 4
enemy1y += enemy1Y_change
elif enemy1X >= 917:
enemy1X_change = -4
enemy1y += enemy1Y_change
It is difficult to answer what is specifically wrong with your code without a Minimal, Reproducible Example. Your concept appears valid, when you hit the boundary, change direction, move down and increase speed.
Here is an example that creates sprites that exhibit space-invader style movement. It it a little more effort to create sprites, but they make handling multiple game entities much easier.
import pygame
import random
screen = pygame.display.set_mode((800, 800))
pygame.init()
sprite_list = pygame.sprite.Group()
class Block(pygame.sprite.Sprite):
"""A block that moves like a space invader"""
def __init__(self, size, pos):
pygame.sprite.Sprite.__init__(self)
self.size = size
self.image = pygame.Surface([size[0], size[1]])
self.image.fill(pygame.color.Color("blueviolet"))
self.rect = self.image.get_rect()
self.rect.x = pos[0]
self.rect.y = pos[1]
self.speedx = random.randint(-5, 5) # note: includes zero
self.speedy = size[1] # this only changes on edge collission
def update(self):
"""move across the screen, skip down a row when at the edge"""
width, height = screen.get_size()
if not 0 < self.rect.x < (width - self.size[0]):
self.speedx *= -1 # reverse direction
self.rect.y += self.speedy
self.rect.x += self.speedx
if self.rect.y > (height - self.size[1]):
self.kill()
# Create some random blocks in random positions
for _ in range(5):
invader = Block(
(random.randint(80, 100), random.randint(80, 100)), # size
(random.randint(0, 800), random.randint(0, 800)), # position
)
sprite_list.add(invader)
run = True
clock = pygame.time.Clock()
while run:
## Handle Events
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
elif event.type == pygame.MOUSEBUTTONUP:
# create block on mouse click
invader = Block((random.randint(80, 100), random.randint(80, 100)), event.pos)
sprite_list.add(invader)
## Clear background
screen.fill("white")
## Update Sprites
sprite_list.update()
## Draw Sprites
sprite_list.draw(screen)
## Update Screen
pygame.display.update()
clock.tick(60) # limit to 60 FPS
pygame.quit()
I'm struggling to work out how collisions work in pygame. I understand it's something to do with pygame.rect.colliderect, and I'm probably pretty close, but I'd appreciate someone who knows a bit more than me having a look! :-)
Here's a simple program I've written to steer a tiny green square onto a larger red square, and I'm trying to implement collision detection when the two meet, but at this stage everything works except collisions.
Thanks in advance!!
pygame.init()
import random #import random
size = (700,500) # set up the screen
screen = pygame.display.set_mode((size))
BLACK = (0,0,0) #define colours
WHITE = (255,255,255)
GREEN = (0,255,0)
RED = (255, 0, 0)
class player(): #assign a player class
def __init__(self):
self.xpos = 450
self.ypos = 250
self.rect = pygame.Rect(self.xpos,self.ypos,5,5)
self.xvel = 0
self.yvel = 0
self.colour = GREEN
def update(self): #define a function to update the payer
#self.xpos +=self.xvel Ignore this bit. I implemented velocity, but it quickly flew off the screen
#self.ypos +=self.yvel
if player.rect.colliderect(obstacle.rect): #<--------- this is the bit I think might be wrong?
print("collision!")
def draw(self): #define a function to draw the player
pygame.draw.rect(screen, self.colour,[self.xpos,self.ypos,5,5])
class obstacle(): #define an obstacle class
def __init__ (self):
self.xpos = random.uniform(0,700)
self.ypos = random.uniform(0,500)
self.rect = pygame.Rect(self.xpos,self.ypos,20,20)
self.colour = RED
def draw(self): #define a function to draw the obstacle
pygame.draw.rect(screen, self.colour,[self.xpos,self.ypos, 20,20])
player = player() #run an instance of the player class
obstacle = obstacle() #run an instance of the obstacle class
clock = pygame.time.Clock()
while True: #game loop
for event in pygame.event.get(): #quit
if event.type == pygame.QUIT:
pygame.display.quit()
#-----Game logic
keys = pygame.key.get_pressed() #check for key presses and do whatever
if keys[pygame.K_LEFT]:
player.xpos -= 1
if keys[pygame.K_RIGHT]:
player.xpos += 1
if keys[pygame.K_UP]:
player.ypos -= 1
if keys[pygame.K_DOWN]:
player.ypos += 1
player.update() #Update the player - obstacle shouldn't need updating
#-----Drawing code
screen.fill(BLACK) #draw screen black
obstacle.draw() #draw the obstacle from the function
player.draw() #draw the player from the function
pygame.display.flip() #update
clock.tick(60)'''
The problem is you are not updating the position of your player's rectangle, which what colliderect looks at when detecting a collision. You were drawing the rectangle as you changed xpos and ypox but the coordinates for your rectangle rect.x and rect.y were not being updated accordingly. I changed the lines
def draw(self): #define a function to draw the player
pygame.draw.rect(screen, self.colour,[self.xpos,self.ypos,5,5])
to
def draw(self): #define a function to draw the player
pygame.draw.rect(screen, self.colour,[self.rect.x,self.rect.y,5,5])
and
if keys[pygame.K_LEFT]:
player.xpos -= 1
if keys[pygame.K_RIGHT]:
player.xpos += 1
if keys[pygame.K_UP]:
player.ypos -= 1
if keys[pygame.K_DOWN]:
player.ypos += 1
to
if keys[pygame.K_LEFT]:
player.rect.x -= 1
if keys[pygame.K_RIGHT]:
player.rect.x += 1
if keys[pygame.K_UP]:
player.rect.y -= 1
if keys[pygame.K_DOWN]:
player.rect.y += 1
so that the player's rectangle coordinates would be updated.
In these cases always print out what is not working, i.e. player.rect and obstacle.rect. You will see that you are not updating player.rect, which is always
<rect(150, 150, 5, 5)>
Since it does not overlap with obstacle.rect, which is always
<rect(34, 204, 20, 20)>
the collision is not detected.
I'm making a "duck hunt" game in pygame. I have everything working, my sprites move and respawn when needed, cursor is a crosshair with sound when clicked etc. The issue I'm having is trying to add points when the mouse is click on a duck. Any idea how I would do this? Posted all of the code, its a bit of a mess until I get thank working, check the main loop specifically. Thanks.
import pygame
import random
import duck_code
# Define some colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
BLUE = (0, 0, 255)
GREEN = (0, 255, 0)
DUCK_BACK = (59, 202, 255)
class Player(pygame.sprite.Sprite):
""" The class is the player-controlled sprite. """
# -- Methods
def __init__(self, x, y, filename):
"""Constructor function"""
# Call the parent's constructor
super().__init__()
# Set height, width
self.image = pygame.Surface([15, 15])
self.image.fill(BLACK)
self.image = pygame.image.load(filename).convert()
# Make our top-left corner the passed-in location.
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
# -- Attributes
# Set speed vector
self.change_x = 0
self.change_y = 0
def changespeed(self, x, y):
""" Change the speed of the player"""
self.change_x += x
self.change_y += y
def update(self):
""" Find a new position for the player"""
self.rect.x += self.change_x
self.rect.y += self.change_y
# boarders for walls, reset player, play bump sound
if self.rect.x in range(1060, 1085):
self.rect.x -= 25
if self.rect.x in range(-5, 0):
self.rect.x += 25
if self.rect.y in range(-5, 0):
self.rect.y += 25
if self.rect.y in range(480, 505):
self.rect.y -= 25
# Initialize Pygame
# Loading sounds
pygame.init()
game_background = pygame.image.load("game_background.jpg")
duck_hit = pygame.mixer.Sound("duck_hit.wav")
player_click = pygame.mixer.Sound("shot_gun.ogg")
# Set the height and width of the screen
screen_width = 1280
screen_height = 1024
screen = pygame.display.set_mode([screen_width, screen_height])
# Starting score and font settings
font = pygame.font.Font(None, 36)
score = 0
# This is a list of every sprite.
all_sprites_list = pygame.sprite.Group()
duck_list = pygame.sprite.Group()
duck_hit_list = pygame.sprite.Group()
"""DUCKS"""
for i in range(5):
# This represents a block
ducks = duck_code.Duck("duck1.png")
ducks.rect.x = random.randrange(screen_width)
ducks.rect.y = random.randrange(50, 350)
# Add the block to the list of objects
duck_list.add(ducks)
all_sprites_list.add(ducks)
"""PLAYER"""
player_image = pygame.image.load("crosshair.png")
player_image.set_colorkey(WHITE)
# Loop until the user clicks the close button.
done = False
# Used to manage how fast the screen updates
clock = pygame.time.Clock()
score = 0
# Hide the mouse cursor
pygame.mouse.set_visible(0)
# -------- Main Program Loop -----------
while not done:
mouse = pygame.mouse.get_pos()
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
blocks_hit_list = pygame.sprite.spritecollide(mouse, duck_list, True)
score += 100
print(score)
player_click.play()
# --- Game logic should go here
# --- Screen-clearing code goes here
# Here, we clear the screen to white. Don't put other drawing commands
# above this, or they will be erased with this command.
# If you want a background image, replace this clear with blit'ing the
# background image.
screen.blit(game_background, [0, 0])
player_position = pygame.mouse.get_pos()
x = player_position[0]
y = player_position[1]
screen.blit(player_image, [x, y])
pos = pygame.mouse.get_pos()
pressed1, pressed2, pressed3 = pygame.mouse.get_pressed()
# Check if the rect collided with the mouse pos
# and if the left mouse button was pressed.
all_sprites_list.draw(screen)
duck_list.update()
# Showing scoreboard
text = font.render("Score: " + str(score), True, WHITE)
screen.blit(text, [10, 10])
# Go ahead and update the screen with what we've drawn.
pygame.display.flip()
# Limit to 60 frames per second
clock.tick(60)
pygame.quit()
pygame.sprite.spritecollide only works with a sprite as the first argument and a sprite group as the second argument. To check if the mouse collides with a duck, you can iterate over the duck_list with a for loop and call the collidepoint method of the current duck's rect:
if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
for duck in duck_list:
if duck.rect.collidepoint(event.pos): # event.pos is the mouse position.
score += 100
Having trouble with my PyGame experimental game - I'm learning how to work with sprites.
I have been trying to code 'collision' detection between sprites (ball and paddle) and have managed to get the collision detection working but my ball sprite seems to reset its position instead of carrying on. Could anyone take a look and see where my error is?
Here is my code:
import pygame
BLACK = ( 0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
#variables, constants, functions
x = 1
y = 1
x_vel = 10
y_vel = 10
bat_x = 1
bat_y = 1
bat_x_vel = 0
bat_y_vel = 0
score = 0
class Ball(pygame.sprite.Sprite):
"""
This class represents the ball.
It derives from the "Sprite" class in Pygame.
"""
def __init__(self, width, height):
""" Constructor. Pass in the color of the block,
and its x and y position. """
# Call the parent class (Sprite) constructor
super().__init__()
# Set the background color and set it to be transparent
self.image = pygame.Surface([width, height])
self.image.fill(WHITE)
self.image.set_colorkey(WHITE)
# Draw the ellipse
pygame.draw.ellipse(self.image, (255,0,0), [0,0,width,height], 10)
# Fetch the rectangle object that has the dimensions of the image
# image.
# Update the position of this object by setting the values
# of rect.x and rect.y
self.rect = self.image.get_rect()
# Instance variables that control the edges of where we bounce
self.left_boundary = 0
self.right_boundary = 0
self.top_boundary = 0
self.bottom_boundary = 0
# Instance variables for our current speed and direction
self.vel_x = 5
self.vel_y = 5
def update(self):
""" Called each frame. """
self.rect.x += self.vel_x
self.rect.y += self.vel_y
if self.rect.right >= self.right_boundary or self.rect.left <= self.left_boundary:
self.vel_x *= -1
if self.rect.bottom >= self.bottom_boundary or self.rect.top <= self.top_boundary:
self.vel_y *= -1
class Paddle(pygame.sprite.Sprite):
"""
This class represents the ball.
It derives from the "Sprite" class in Pygame.
"""
def __init__(self, width, height):
""" Constructor. Pass in the color of the block,
and its x and y position. """
# Call the parent class (Sprite) constructor
super().__init__()
# Set the background color and set it to be transparent
self.image = pygame.Surface([width, height])
self.image.fill(WHITE)
self.image.set_colorkey(WHITE)
# Draw the rectangle
pygame.draw.rect(self.image, (0, 255, 0), [0, 0, width, height], 0)
# Fetch the rectangle object that has the dimensions of the image
# image.
# Update the position of this object by setting the values
# of rect.x and rect.y
self.rect = self.image.get_rect()
# Instance variables for our current speed and direction
self.x_vel = 0
self.y_vel = 0
def update(self):
# Get the current mouse position. This returns the position
# as a list of two numbers.
self.rect.x = self.rect.x + self.x_vel
self.rect.y = self.rect.y + self.y_vel
#initialise ball and paddle
paddle = Paddle(20, 100)
ball = Ball(100,100)
# This is a list of every sprite.
# All blocks and the player block as well.
all_sprites_list = pygame.sprite.Group()
all_sprites_list.add(ball)
all_sprites_list.add(paddle)
ball_sprites_list = pygame.sprite.Group()
ball_sprites_list.add(ball)
# Initialize Pygame
pygame.init()
# Set the height and width of the screen
screen_width = 700
screen_height = 400
screen = pygame.display.set_mode((screen_width, screen_height))
# Used to manage how fast the screen updates
clock = pygame.time.Clock()
# Loop until the user clicks the close button.
done = False
# -------- Main Program Loop -----------
while not done:
# --- Events code goes here (mouse clicks, key hits etc)
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
paddle.y_vel = -3
if event.key == pygame.K_DOWN:
paddle.y_vel = 3
if event.type == pygame.KEYUP:
if event.key == pygame.K_UP:
paddle.y_vel = 0
if event.key == pygame.K_DOWN:
paddle.y_vel = 0
# --- Game logic should go here
# Calls update() method on every sprite in the list
all_sprites_list.update()
# collision check
ball_hit_list = pygame.sprite.spritecollide(paddle, ball_sprites_list, False)
# Check the list of collisions.
for ball in ball_hit_list:
score +=1
print(score)
# --- Clear the screen
screen.fill((255,255,255))
# --- Draw all the objects
all_sprites_list.draw(screen)
# render text
myfont = pygame.font.SysFont("monospace", 15)
label = myfont.render(str(score), 1, (0,0,0))
screen.blit(label, (100, 100))
# --- Update the screen with what we've drawn.
pygame.display.flip()
# --- Limit to 60 frames per second
clock.tick(60)
pygame.quit()
Sorry,
Have found the error.
Didn't set the boundaries of the window properly.
# Instance variables that control the edges of where we bounce
self.left_boundary = 0
self.right_boundary = 700
self.top_boundary = 0
self.bottom_boundary = 400
My problem with the code is that I created a sprite that is able to move a tile each time when an arrow key is pressed, the problem is when the sprite moves onto a tile that has a wall on it, it still goes onto the tile instead of staying on the tile that it is on. I can't seem to get the right collision detection code.
import pygame
import random
# Define some colors
black = ( 0, 0, 0)
white = ( 255, 255, 255)
red = ( 255, 0, 0)
GREEN = ( 0, 255, 0)
wall = ( 66, 66, 66)
# This class represents the ball
# It derives from the "Sprite" class in Pygame
class Main(pygame.sprite.Sprite):
walls = None
def __init__(self, filename):
# Calls the parent class (Sprite) constructor
pygame.sprite.Sprite.__init__(self)
# Creates the 'block' that will contain the image
self.image = pygame.image.load(filename).convert()
# Set background colour so its transparent
self.image.set_colorkey(black)
# Sets parameters so you can adjust the x and y values
self.rect = self.image.get_rect()
def update (self,):
# Moving left or right
self.rect.x += self.change_y
# Did something collide into wall ?
wall_hit_list = pygame.sprite.spritecollide(self, self.walls, False)
for wall in wall_hit_list:
# If we are moving right, set our right side to the left side of the item we hit
if self.change_y > 0:
self.rect.right = wall.rect.left
else:
# Otherwise if we are moving left, do the opposite
self.rect.left = wall.rect.right
# Move up/down
self.rect.y += self.change_x
# Check and see if we hit anything
wall_hit_list = pygame.sprite.spritecollide(self, self.walls, False)
for wall in wall_hit_list:
# Reset our position based on the top/bottom of the object.
if self.change_x > 0:
self.rect.bottom = wall.rect.top
else:
self.rect.top = wall.rect.bottom
class Wall(pygame.sprite.Sprite):
# Wall that the player can run into.
def __init__(self, filename):
# Constructor
pygame.sprite.Sprite.__init__(self)
# Make a wall
self.image = pygame.image.load(filename).convert()
# Sets parameters so you adjust the x and y values
self.rect = self.image.get_rect()
# Initialize Pygame
pygame.init()
# Set the height and width of the screen
screen_width = 700
screen_height = 400
screen = pygame.display.set_mode([screen_width, screen_height])
# List of all the sprites
all_sprites_list = pygame.sprite.Group ()
# List of the main sprite ( squirtle )
main_sprite = pygame.sprite.Group ()
# List of Walls
wall_list = pygame.sprite.Group ()
wall = Wall("wall2.png",)
wall.rect.x = 100
wall.rect.y = 150
wall_list.add(wall)
all_sprites_list.add(wall)
# Sets player to the class 'Main' which thanks to the parameter, is squirtle
Hero = Main ("Character.png")
player = Main ("Character.png")
# Spawns squirtle in a random position
Hero.rect.x = 4
Hero.rect.y = 1
# Adds squirtle to the lists that we made
main_sprite.add(Hero)
all_sprites_list.add(Hero)
#Loop until the user clicks the close button.
done = False
# Used to manage how fast the screen updates
clock = pygame.time.Clock()
# -------- Main Program Loop -----------
while done == False:
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:
if event.key == pygame.K_LEFT:
Hero.rect.x -= 50
elif event.key == pygame.K_RIGHT:
Hero.rect.x += 50
elif event.key == pygame.K_UP:
Hero.rect.y -= 50
elif event.key == pygame.K_DOWN:
Hero.rect.y += 50
# Clear the screen
screen.fill(white)
# Drawing Code
y_offset = 0
x_offset = 0
while x_offset < 750:
pygame.draw.line(screen,GREEN, [0+x_offset,0], [0+x_offset,500],1)
x_offset = x_offset + 50
while y_offset < 550:
pygame.draw.line(screen, GREEN, [0,0+y_offset], [700,0+y_offset],1)
y_offset = y_offset + 50
# Draw all the sprites
all_sprites_list.draw(screen)
pygame.display.flip ()
clock.tick (60)
pygame.quit ()`
First of all, you never call the update method of your sprites, so your collision check is never performed.
If you would call it, it would fail, because you try to read self.change_y, which you never set.
If you would, it would still fail, because you try to check the collision against the sprites in self.walls, but you never set it thus self.walls is always None.