Separate draw and update loops for more smooth animation? - python

I want to design a snake game with smoother movement than others, using the pygame library. My issue does not concern the movement part - I have been able to move the snake, but this came at the cost of 2 FPS and changing the speed to TILE_SIZE, creating an effect of lag/choppiness which I don't like. Is there a solution, such that I can move the snake more often in smaller intervals to create smoother movement? I know about LERP / interpolation but I am not too sure how to use it / if this is the best solution. Thanks
import pygame as pg
import random
# Initialising
pg.init()
# Creating screen
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 800
screen = pg.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
# Creating clock
clock = pg.time.Clock()
fps = 60
# Creating game variables
TILE_SIZE = 40
right = left = down = up = False
# Colours
black = (0, 0, 0)
class Snake(pg.sprite.Sprite):
def __init__(self, x, y):
super().__init__()
self.body = [[x, y]]
self.length = len(self.body)
self.direction = pg.math.Vector2()
self.speed = TILE_SIZE // 5
def update(self):
# Movement
self.direction.x = 1 if right else -1 if left else 0
self.direction.y = 1 if down else -1 if up else 0
self.body[0][0] += self.speed * self.direction.x
self.body[0][1] += self.speed * self.direction.y
def draw(self):
pg.draw.rect(screen, "green", (self.body[0][0], self.body[0][1], TILE_SIZE, TILE_SIZE))
# Creating snake at a random tile starting point
snake = Snake(random.randrange(0, SCREEN_WIDTH, TILE_SIZE), (random.randrange(0, SCREEN_WIDTH, TILE_SIZE)))
running = True
while running:
# Set frame rate
clock.tick(fps)
# Fill screen
screen.fill("beige")
# Draw grid
for i in range(0, SCREEN_WIDTH, TILE_SIZE):
pg.draw.line(screen, black, (i, 0), (i, SCREEN_HEIGHT))
for i in range(0, SCREEN_HEIGHT, TILE_SIZE):
pg.draw.line(screen, black, (0, i), (SCREEN_WIDTH, i))
# Draw snake
snake.update()
snake.draw()
for e in pg.event.get():
if e.type == pg.QUIT:
running = False
keys = pg.key.get_pressed()
if (keys[pg.K_RIGHT] or keys[pg.K_d]) and not left:
right = True
left = down = up = False
if (keys[pg.K_LEFT] or keys[pg.K_a]) and not right:
left = True
right = down = up = False
if (keys[pg.K_DOWN] or keys[pg.K_s]) and not up:
down = True
right = left = up = False
if (keys[pg.K_UP] or keys[pg.K_w]) and not down:
up = True
right = left = down = False
pg.display.update()

Solved - I decided to only change the snake's direction when the snake is inside the grid pattern (using MOD operator %) -
if self.rect.topleft[0] % TILE_SIZE == 0 and self.rect.topleft[1] % TILE_SIZE == 0:
# change direction

Related

Why is my platform moving when my player is moving right or left

1) In my code the problem is that my Platform underneath my player class are connected and when the player moves so does the platform and if so the player moves on the platform the entire time. Can someone tell me how to fix that? If you are wondering where to look for all the code and where it is going to be it is all the code here because I didn't Know what was causing the problem in my code.
import math
import os
import sys
# It is importing everything
import pygame
from pygame.locals import *
#The platform class is the problem I'm having
class Platform:
def __init__(self, size, x, y, length, color, velocity):
self.length = length
self.size = size
self.x = x
self.y = y
self.color = color
self.velocity = velocity
self.xVelocity = 0
# This is what the platform class has and what it does
def draw(self):
display = pygame.display.get_surface()
pygame.draw.rect(display, self.color, (int(self.x) - 80, int(self.y) + 225, int(self.x), int(self.y) - 45))
# This is def draw function is showing that how I want my Platform to look like
def do(self):
self.draw()
2) When my player reaches the "end" of the screen it stops but I want to make it a scrolling screen and nothing happens and then there is no game when the player moves and scroll by itself. After someone tells me how to fix my second problem then I want the Background to kill the player if the background goes past the player.
# The def do function is running def draw function
class Player:
def __init__(self, velocity, maxJumpRange, x, y, size):
self.falling = True
self.jumpCounter = 0
self.xVelocity = 0
self.y = y
self.x = x
self.jumping = False
self.velocity = velocity
self.maxJumpRange = maxJumpRange
self.jump_offset = 0
self.size = size
# The player class is making how the Player is going to look and what are his limits
def keys(self):
k = pygame.key.get_pressed()
# The def keys(self): is creating a variable for pygame.key.get_pressed() and underneath is a function to make the player move around
if k[K_LEFT]:
self.xVelocity = -self.velocity
elif k[K_RIGHT]:
self.xVelocity = self.velocity
else:
self.xVelocity = 0
if k[K_SPACE] or k[K_UP] and not self.jumping and not self.falling:
self.jumping = True
self.jumpCounter = 0
# The if k[K_Space] or k[K_UP] is making sure the player has a jump limit and can't continue jumping forever.
def move(self):
self.x += self.xVelocity
# This to make sure that the player can move while he is jumping.
if self.jumping:
self.y -= self.velocity
self.jumpCounter += 1
if self.jumpCounter == self.maxJumpRange:
self.jumping = False
self.falling = True
elif self.falling:
if self.y <= h - 10 <= self.y + self.velocity:
self.y = h - 10
self.falling = False
else:
self.y += self.velocity
def draw(self):
display = pygame.display.get_surface()
pygame.draw.circle(display, White, (int(self.x), int(self.y) - 25), 25, 0)
def do(self):
self.keys()
self.move()
self.draw()
# This Function is doing all of the Functions self.keys(), self.move(), self.draw()
def events():
for event in pygame.event.get():
if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):
pygame.quit()
sys.exit()
# This is to make sure that you can exit the game is needed
def keys(player):
keys = pygame.key.get_pressed()
if keys[K_UP] or keys[K_SPACE] and player.jumping == False and player.jump_offset == 0:
player.jumping = True
# The function here to make sure that the player can jump
def do_jumping(player):
jump_height = 25
# Def do_jumping(player): is to adjust the jump_height of the player
if player.jumping:
player.jump_offset += 1
if player.jump_offset >= jump_height:
player.jumping = False
elif player.jump_offset > 0 and player.jumping == False:
player.jump_offset -= 1
# The above is showing how the makes sure the player doesn't jump higher then the jump height
w = 576
h = 516
hw = w / 2
hh = h / 2
AREA = w * h
# The above is showing the width the height and Area
os.environ['SDL_VIDEO_WINDOW_POS'] = "50,50"
p = Player(hh, hw, 290, 250, 30)
# the above is showing what the graphics are
pygame.init()
Clock = pygame.time.Clock()
DS = pygame.display.set_mode((w, h)) # This is what the display size is
pygame.display.set_caption("Try to get point B")
FPS = 120
Black = (0, 0, 0, 255)
White = (255, 255, 255, 255)
pl = Platform(290, 250, 50, 70, White, 0)
Red = (255, 0, 0)
Solid_Fill = 0
# Bkgd stands for background
bkgd = pygame.image.load("scroll.png").convert() # scroll.png is the png im using to use as the background
bkgdWidth = bkgd.get_rect().size[0]
print(bkgdWidth)
bkgdHeight = bkgd.get_rect().size
stageWidth = bkgdWidth * 2
StagePosX = 0
startScollingPosx = hw
circleRadius = 25
circlePosX = circleRadius
playerPosX = circleRadius
playerPosY = 377
playerVelocityX = 0
playerVelocityY = 0
platformVelocityX = 0
platformVelocityY = 0
x = 0
# The above is showing the player Velocity, player position y and x and what the stage position is, Ignore platform
# velocity.
# What the while true loop is doing is to make sure that the background moves while the player moves
while True:
events()
k = pygame.key.get_pressed()
if k[K_RIGHT]:
playerVelocityX = 1
pl.xVelocity = 0
elif k[K_LEFT]:
playerVelocityX = -1
pl.xVelocity = 0
else:
playerVelocityX = 0
pl.xVelocity = 0
playerPosX += playerVelocityX
if playerPosX > stageWidth - circleRadius:
playerPosX = stageWidth - circleRadius
if playerPosX < circleRadius:
playerPosX = circleRadius
if playerPosX < startScollingPosx:
circlePosX = playerPosX
elif playerPosX > stageWidth - startScollingPosx:
circlePosX - stageWidth + w
else:
circlePosX = startScollingPosx
StagePosX -= playerVelocityX
# The code below show is working how to balance the Display size and rel x is the easier of saying that
rel_x = StagePosX % bkgdWidth
DS.blit(bkgd, (rel_x - bkgdWidth, 0))
if rel_x < w:
DS.blit(bkgd, (rel_x, 0))
events()
keys(p)
do_jumping(p)
pygame.draw.circle(DS, White, (math.floor(p.x), math.floor(p.y) - math.floor(p.jump_offset)), math.floor(p.size), math.floor(Solid_Fill))
platform_color = Red
pl.color = Red
pl.draw()
if p.jump_offset == 0:
pl.color = White
pl.do()
pygame.display.update()
Clock.tick(FPS)
DS.fill(Black)
3) Lastly sorry for the lack of good code and where to look around the code because I didn't Know what was causing the problem in my code so I had to put out all of it.
I edited your code a bit so fix the problems you had, I did change the image as i didn't have it, but i fixed jumping and standing on platform by making player constantly fall and check if the player collides with the platform. I also added the scrolling background. Got rid of the unnecessary code as mentioned in my comments. changed the player move to do the jump from there. changed the size in platform to a list so it has width and height. got rid of velocity too as platforms didn't move.
import math
import os
import sys
# It is importing everything
import pygame
from pygame.locals import *
class Platform:
def __init__(self, size, x, y, color):
#size is a list, this means it has width and height
self.size = size
self.x = x
self.y = y
self.color = color
# This is what the platform class has and what it does
def draw(self):
display = pygame.display.get_surface()
pygame.draw.rect(display, self.color, (int(self.x), int(self.y), self.size[0], self.size[1]))
# This is def draw function is showing that how I want my Platform to look like
def do(self):
self.draw()
# The def do function is running def draw function
class Player:
def __init__(self, velocity, maxJumpRange, x, y, size):
self.falling = True
self.jumpCounter = 0
self.xVelocity = 0
self.y = y
self.x = x
self.jumping = False
self.velocity = velocity
self.maxJumpRange = maxJumpRange
self.jump_offset = 0
self.size = size
self.TouchedGround = False
# The player class is making how the Player is going to look and what are his limits
def keys(self):
k = pygame.key.get_pressed()
# The def keys(self): is creating a variable for pygame.key.get_pressed() and underneath is a function to make the player move around
if k[K_LEFT]:
self.xVelocity = -self.velocity
elif k[K_RIGHT]:
self.xVelocity = self.velocity
else:
self.xVelocity = 0
if (k[K_SPACE] or k[K_UP]) and not self.jumping and self.TouchedGround:
self.jumping = True
self.jumpCounter = 0
self.TouchedGround = False
# The if k[K_Space] or k[K_UP] is making sure the player has a jump limit and can't continue jumping forever.
def move(self):
self.x += self.xVelocity
# if the player is jumping, change y value
if self.jumping:
self.y -= self.velocity
self.jumpCounter += 1
if self.jumpCounter == self.maxJumpRange:
self.jumping = False
self.falling = True
elif self.falling:
self.y += self.velocity
self.jumpCounter -= 1
def draw(self):
display = pygame.display.get_surface()
pygame.draw.circle(display, White, (int(self.x), int(self.y)), self.size)
def do(self):
self.keys()
self.move()
self.draw()
# This Function is doing all of the Functions self.keys(), self.move(), self.draw()
def events():
for event in pygame.event.get():
if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):
pygame.quit()
sys.exit()
#window size
w = 576
h = 516
# The above is showing the width the height and Area
os.environ['SDL_VIDEO_WINDOW_POS'] = "50,50"
# the above is showing what the graphics are
#player
p = Player(1, 100, 290, 250, 30)
#start pygame
pygame.init()
Clock = pygame.time.Clock()
DS = pygame.display.set_mode((w, h)) # This is what the display size is
pygame.display.set_caption("Try to get point B")
#variables
FPS = 120
Black = (0, 0, 0, 255)
White = (255, 255, 255, 255)
Red = (255, 0, 0)
# Bkgd stands for background
bkgd = pygame.Surface((w,h)) # didnt have the image so i made it blue
bkgd.fill((0,0,255))
#platforms
pl = Platform([290,20], 250, 350, White)
#this is a list that holds all the platforms
platforms_list = [pl,Platform([200,20], 100, 450, White), Platform([200,20], 400, 250, White)]
#this is how much to scroll the background by
background_scroll = 0
# What the while true loop is doing is to make sure that the background moves while the player moves
while True:
events()
#blit the background, since the image is same size as window blit twice so when scrolls, you dont have blackness
DS.blit(bkgd, (-background_scroll, 0))
DS.blit(bkgd, (w-background_scroll, 0))
#check for x button clicked
events()
#update the player
p.do()
#update platforms and check for collision with player
platform_color = Red
for platform in platforms_list:
platform.color = platform_color
if p.jumping == 0:
platform.color = White
platform.do()
#if bottom of player is in the platform, move the player on top of the platform
if p.y + p.size > platform.y and p.y + p.size < platform.y + platform.size[1]:
if p.x > platform.x and p.x < platform.x + platform.size[0]:
p.y = platform.y - p.size
p.TouchedGround = True
#if the player reaches the side of the screen, move the background and platforms to make it look like it is moving
if p.x + p.size >= w:
p.x = w - p.size
background_scroll += 1
for platform in platforms_list:
platform.x -= 1
if background_scroll == w:
background_scroll = 0
#same but for the left
if p.x - p.size <= 0:
p.x = 0 + p.size
background_scroll -= 1
for platform in platforms_list:
platform.x += 1
if background_scroll == 0:
background_scroll = w
#update screen
pygame.display.update()
Clock.tick(FPS)
DS.fill(Black)

Is there a way to make a function for all the code relating to drawing a bouncing ball in pygame?

The ball bounces around and I can draw it but I want to draw multiple and have them start at random places without having to type every scenario. Is there a way to write a function to do this?
import pygame
import sys
import random
pygame.init()
screenSize = (800,600)
screen = pygame.display.set_mode(screenSize)
pygame.display.set_caption("Jacob Cardoso Basic Drawing")
WHITE = (255,255,255)
BLACK = (0,0,0)
RED = (255,0,0)
GREEN = (0,255,0)
BLUE = (0,0,255)
COLOUR = (random.randint(0,255), random.randint(0,255),random.randint(0,255))
x = random.randint(50,750)
y = random.randint(50,550)
dx = random.randint(1, 3)
dy = random.randint(-1, 3)
screen.fill(WHITE)
go = True
while go:
for event in pygame.event.get():
if event.type == pygame.QUIT:
go = False
x = x + dx
y = y + dy
if (y <= 50) or (y >= 550):
dy = -dy
COLOUR = (random.randint(0,255), random.randint(0,255),random.randint(0,255))
if (x <= 50) or (x >= 750):
dx = -dx
COLOUR = (random.randint(0,255), random.randint(0,255),random.randint(0,255))
screen.fill(WHITE)
pygame.draw.circle (screen, COLOUR, (x,y), 50, 0)
pygame.display.update()
pygame.quit()
sys.exit()
Create a Class for the balls. The coordinates, moving direction and color become instance attributes. Move the code which handles the movement to an update method. Do the drawing of the ball in a draw method.
class Ball:
def __init__(self):
self.x = random.randint(50,750)
self.y = random.randint(50,550)
self.dx = random.randint(1, 3)
self.dy = random.randint(-1, 3)
self.color = (random.randint(0,255), random.randint(0,255),random.randint(0,255))
def update(self):
self.x = self.x + self.dx
self.y = self.y + self.dy
bounce = False
if (self.y <= 50) or (self.y >= 550):
self.dy = -self.dy
bounce = True
if (self.x <= 50) or (self.x >= 750):
self.dx = -self.dx
bounce = True
if bounce:
self.color = (random.randint(0,255), random.randint(0,255),random.randint(0,255))
def draw(self, surf):
pygame.draw.circle(surf, self.color, (self.x, self.y), 50, 0)
Create a number of (max_balls) ball instances in a loop and append them to a list (balls), before the application loop. Update the position of the balls and draw them in for-loops in the application loop:
# crate the balls
max_balls = 5
balls = []
for _ in range(max_balls):
balls.append(Ball())
screen.fill(WHITE)
go = True
while go:
for event in pygame.event.get():
if event.type == pygame.QUIT:
go = False
# update the ball positions
for ball in balls:
ball.update()
screen.fill(WHITE)
# draw the balls
for ball in balls:
ball.draw(screen)
pygame.display.update()

Collision Between two sprites - Python 3.5.2

I have an image of a ufo and a missile. I'm trying to get it to where if the missile hits the ufo they both would explode and disappear and then a few moments later another ufo would respawn but the collision code isn't working. can someone explain to me how to make the code work?
pygame.display.init()
pygame.font.init()
screen = pygame.display.set_mode((800, 600))
clock = pygame.time.Clock()
ufo = pygame.image.load("ufo.png")
rocket = pygame.image.load("rocket.png")
done = False
debug = False
fontObj = pygame.font.SysFont("Courier New", 20)
#Making my Empty Lists
missiles = [] #[x,y]
ufo_list = [] #[x,y,hspeed]
particle_list = []
#UFO Respawn Info
ufoRespawn = True
ufoHits = 0
ufoSpawnTimer = 0.0
ufoSpeed = 500.0
#MISSILE Info
launchX = 400
launchY = 550
missileSpeed = 100.0
missileDirection = 0
#creating the Starfield
myStars = [] # An (initially) empty list
for i in range(1000):
x = random.randint(0, 800)
y = random.randint(0, 600)
newStar = [x, y] # A 2-element list
myStars.append(newStar)
starSpeed = 100.0 # Rate of star movement (px / s)
starDirection = 0 # 0 = not moving, -1 = left, +1 = right
#input
while not done:
event = pygame.event.poll()
if event.type == pygame.QUIT:
done = True
keys = pygame.key.get_pressed()
if keys[pygame.K_ESCAPE]:
done = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_d:
debug = not debug
dt = clock.tick() /1000.0
#the missile range (making it disappear after it hits the top)
for missile in missiles:
missile[1] -= missileSpeed * dt
if missile[1] < 0: missiles.remove(missle)
#triangle following mouse position
mx, my = pygame.mouse.get_pos()
if mx > launchX:
launchX += .3
if mx < launchX:
launchX -= .3
#bullets firing when pressing with mouse
mbuttons = pygame.mouse.get_pressed()
if mbuttons [0]:
x = launchX
y = launchY
newMissiles = [x,y]
missiles.append(newMissiles)
#Creating the UFOs
ufoSpawnTimer -= dt
if ufoSpawnTimer <= 0:
if random.choice (("head", "tail")) == "head":
x = 0
hspeed = random.randint (10,50)
else:
x = 800
hspeed = random.randint (-50, -10)
y = random.randint (0,300)
new_ufo = [x,y,hspeed]
ufo_list.append(new_ufo)
ufoSpawnTimer = 5.0
#Moving the Starfield
for i in range(len(myStars)):
myStars[i][0] += starSpeed * dt * starDirection
if myStars[i][0] < 0: myStars[i][0] = 800
if myStars[i][0] > 800: myStars[i][0] = 0
screen.fill ((0,0,0))
#drawing the triangle a.k.a missle launcher :D
pygame.draw.polygon(screen, (255,255,255), [[launchX, launchY], [launchX + 10, launchY + 10], \
[launchX - 10, launchY + 10]], 3)
for missile in missiles:
x = int(missile[0])
y = int(missile[1])
screen.blit(rocket, (x,y))
#drawing the ufo
for v in ufo_list:
v[0] += v[2] * dt
screen.blit(ufo,(v[0],v[1]))
#Missle distance from UFO - NEED HELP ON THIS PORTION
#Hit Detection
missileDist = ((x - v[0]) ** 2 + (y - v[1]) ** 2) ** 0.5
if **????** :
ufoRespawn = True
ufoHits += 10
#drawing th starfield
for star in myStars:
x = int(star[0])
y = int(star[1])
pygame.draw.circle(screen, (255,255,255), (x,y), 2)
pygame.display.flip()
pygame.font.quit()
pygame.display.quit()
Well there are many different ways to detect collision, And it might be worth looking at libraries that would do so, but the simplest method by far is to use pygame.sprite.spritecollide().
But before I can show how to use the function, you need to know what a pygame.sprite.Group() is and what a sprite class is.
Basicly, what a pygame.sprite.Group() is, is a way to keep track of and hold multiple sprites. In your case, it seems making a missile group for your missiles would be the best choice.
So I would create a group to hold your missiles:
missiles_group = pygame.sprite.Group(). You can add missiles to the group by saying missiles_group.add(<sprite instance name>).
As for the sprite class, please see this answer I gave to a question. To be terse, a Sprite class is a modular way to create a sprite. Instead of using just a plain image, a sprite class would hold necessary methods and attributes of a sprite. I will be using a sprite class in my example below, so if more detail is needed, please read the answer I linked to above.
With that out of the way, and without going into too much detail, here is how you fill in each function parameter to the above function.
sprite: This is the sprite that will be tested against a group of sprites
group: This is the group that will be used to test with the sprite.
dokill: This is a boolean value. If set to true, each time the sprite parameter collides with something in the group parameter, and object from the group parameter will be deleted. And visa versa if the dokill argument is set to false.
The is one more parameter that the function takes, but for what you're trying to do, it is not needed.
Incorporating the above information, here is an example. The example creates a sprite and a list of sprites. Each time the sprite collides with a sprite from the group, HIT is printed to the screen:
import pygame #import the pygame module into the namespace <module>
WIDTH = 640 # define a constant width for our window
HEIGHT = 480 # define a constant height for our window
#create a pygame window, and
#initialize it with our WIDTH and HEIGHT constants
display = pygame.display.set_mode((WIDTH, HEIGHT))
clock = pygame.time.Clock() # create a game clock
class Sprite(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface((20, 20))
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 = -1
elif key[pygame.K_RIGHT]:
self.vx = 1
if key[pygame.K_UP]:
self.vy = -1
elif key[pygame.K_DOWN]:
self.vy = 1
self.rect.x += self.vx
self.rect.y += self.vy
# cretae a player sprite
player = Sprite()
# create a group to hold all of our sprites
sprites = pygame.sprite.Group()
# create a group to hold sprites we want to
# test collions against. These sprites will
# still be added to the sprites list
# but we need a seperate group to test for
# collisions against
collision_sprites = pygame.sprite.Group()
# add a sprite to out collison sprite group
# We also add the sprite to our sprites group
# that holds all sprites
tmp = Sprite()
tmp.update = lambda: None
sprites.add(tmp)
collision_sprites.add(tmp)
# add a player sprites to the player group
player.rect.x = 10
sprites.add(player)
running = True # our variable for controlling our game loop
while running:
for e in pygame.event.get(): # iterate ofver all the events pygame is tracking
clock.tick(60) # make our clock keep pour game at 60 FPS
if e.type == pygame.QUIT: # is the user trying to close the window?
running = False # if so break the loop
pygame.quit() # quit the pygame module
quit() # quit is for IDLE friendliness
sprites.update()
# here is where we test for collision
if pygame.sprite.spritecollide(player, collision_sprites, False):
print("HIT!")
display.fill((180, 180, 180)) # fill the pygame screen with white
sprites.draw(display)
pygame.display.flip() # update the screen
My example if fairly big, so take your time and step through it carefully. I tried to add as many good comments as I could. Good luck!

Collisions detection in pygame

I'm trying to detect collisions between the player and the floor. This is part of my school project so any insight would be helpful. Also suggestions to improve the code will be appreciated. Here is my code:
import pygame
#initialise pygame
pygame.init()
#variables
level = 0
velx = 0
vely = 0
health = 1
floor_group = set([])
clock = pygame.time.Clock()
#collisions
def detectCollisions(x1, y1, w1,h1, x2, y2, w2, h2):
if (x2 + w2 >= x1 >= x2 and y2 + h2 >= y1 >= y2):
return True
elif (x2 + w2 >= x1 + w1 >= x2 and y2 + h2 >= y1 >= y2):
return True
elif (x2 + w2 >= x1 >= x2 and y2 + h2 >= y1 + h1 >= y2):
return True
elif (x2 + w2 >= x1 + w1 >= x2 and y2 + h2 >= y1+ h1 >= y2):
return True
else:
return False
#screen size the same size as my background
window = pygame.display.set_mode((900,563))
#Load Images: Backgrounds
background0 = pygame.image.load("background0.png").convert()
#Load Sprites
halfspike = pygame.image.load("halfspike.png").convert_alpha()
spike = pygame.image.load("spike.png").convert_alpha()
platform = pygame.image.load("platform.png").convert_alpha()
spider = pygame.image.load("spider.png").convert_alpha()
char1 = pygame.image.load("char1.png").convert_alpha()
char2 = pygame.image.load("char2.png").convert_alpha()
#Window title
pygame.display.set_caption("Super Boshy Brothers")
# character class
class Sprite:
def __init__(self,x,y):
self.x = x
self.y = y
self.width = 42
self.height = 44
self.velx = 0
self.vely = 0
self.image0 = pygame.image.load("char1.png")
self.image1 = pygame.image.load("char2.png")
self.timeTarget = 10
self.timeNumber = 0
self.currentImage = 0
def update(self):
self.timeNumber += 1
if (self.timeNumber == self.timeTarget):
if (self.currentImage == 0):
self.currentImage = 1
else:
self.currentImage = 0
self.timeNumber = 0
self.render()
def render(self):
if (self.currentImage == 0):
window.blit(self.image0, (self.x, self.y))
else:
window.blit(self.image1, (self.x, self.y))
# Floor class
class Floor:
def __init__(self,x,y):
self.x = x
self.y = y
self.width = 43
self.height = 44
self.image0 = pygame.image.load("floor.png")
def update(self):
self.render()
def render(self):
window.blit(self.image0, (self.x, self.y))
def floor_spawner(row):
global floor_group
for i in range(0,946,43):
floor_group.add(Floor(i,row))
#Create first level floor
floor_spawner(519)
floor_spawner(475)
#player
player = Sprite(0,431)
#create our main loop
gameloop = True
while gameloop:
for event in pygame.event.get(): #get function handles events
if (event.type == pygame.QUIT): #if Quit (red x) pressed exit loop
gameloop = False
if (event.type == pygame.KEYDOWN): #If a key is pressed down
if (event.key ==pygame.K_LEFT): #If Left Arrow
velx = -7
if (event.key ==pygame.K_RIGHT): #If Right Arrow
velx = 7
if (event.key ==pygame.K_UP): #If Up Arrow
vely = -7
if (event.type == pygame.KEYUP): #If a key is pressed down
if (event.key ==pygame.K_LEFT): #If Left Arrow
velx = 0
if (event.key ==pygame.K_RIGHT): #If Right Arrow
velx = 0
if (event.key ==pygame.K_UP): #If Up Arrow
vely = 0
#Level 0
if level == 0:
window.blit(background0, (0,0)) #Bottom bricks
for f in list(floor_group):
f.render()
if player.x <= 0: #Left side collision
player.x = 0
if player.x >= 900: #Level change
level = 1
player.x = 0
#Level 1
if level == 1:
window.blit(background0, (0,0)) #Bottom bricks
for f in list(floor_group):
f.render()
player.x += velx
player.y += vely
player.update()
clock.tick(50) #Tick Tock Tick Tock
pygame.display.flip() #Updates the window
pygame.quit()
It's better if you use pygame sprite to do your assignment.
For managing the floor collision problem, just detect the collision as I do in the code below, if a collision between player and floor occurs then simply move the player back to the previous position.
Here's my code:
import pygame
import random
BLACK = (0, 0, 0)
RED = (255, 0, 0)
BLUE = (0, 255, 0)
WHITE = (255, 255, 255)
#Sprite are basically game images in pygame
#Through sprites collision detection and rendering becomes much easier
class Block(pygame.sprite.Sprite):
#Here I've a block class which is a subclass of the pygame's sprite class
def __init__(self, image):
pygame.sprite.Sprite.__init__(self)
# Here I've initialised he superclass Sprite
self.image = image
#Image of sprite = image .. that's it
self.rect = self.image.get_rect()
#It get's all dimesion's of image which will help it in detecting collision
pygame.init()
infoObject = pygame.display.Info()
# pygame.display.Info() provides us with the information about cureent resolution and a bunch of other stuff
screen = pygame.display.set_mode((infoObject.current_w, infoObject.current_h))
char1 = pygame.image.load("char1.png").convert_alpha()
char2 = pygame.image.load("char2.png").convert_alpha()
char2_list = pygame.sprite.Group()
# Sprite groups are sets for sprites
# i.e. We have different types of object stored in different groups
# In our game the char1 and char2 are of different
#internal interaction between all char2 does'nt matter
#It's the interaction between the char1 and char2 that we've to deal with
all_list = pygame.sprite.Group()
#I've made a group which contains all the blocks which helps me in rendering them all together
for i in range(50):
block = Block(char1)
block.rect.x = random.randrange(infoObject.current_w)
block.rect.y = random.randrange(infoObject.current_h)
charimport pygame
import random
BLACK = (0, 0, 0)
RED = (255, 0, 0)
BLUE = (0, 255, 0)
WHITE = (255, 255, 255)
#Sprite are basically game images in pygame
#Through sprites collision detection and rendering becomes much easier
class Block(pygame.sprite.Sprite):
#Here I've a block class which is a subclass of the pygame's sprite class
def __init__(self, image):
pygame.sprite.Sprite.__init__(self)
# Here I've initialised he superclass Sprite
self.image = image
#Image of sprite = image .. that's it
self.rect = self.image.get_rect()
#It get's all dimesion's of image which will help it in detecting collision
pygame.init()
infoObject = pygame.display.Info()
# pygame.display.Info() provides us with the information about cureent resolution and a bunch of other stuff
screen = pygame.display.set_mode((infoObject.current_w, infoObject.current_h))
char1 = pygame.image.load("char1.png").convert_alpha()
char2 = pygame.image.load("char2.png").convert_alpha()
char2_list = pygame.sprite.Group()
# Sprite groups are sets for sprites
# i.e. We have different types of object stored in different groups
# In our game the char1 and char2 are of different
#internal interaction between all char2 does'nt matter
#It's the interaction between the char1 and char2 that we've to deal with
all_list = pygame.sprite.Group()
#I've made a group which contains all the blocks which helps me in rendering them all together
for i in range(50):
block = Block(char1)
block.rect.x = random.randrange(infoObject.current_w)
block.rect.y = random.randrange(infoObject.current_h)
char2_list.add(block)
all_list.add(block)
player = Block(char2)
running = True
clock = pygame.time.Clock()
score = 1
all_list.add(player)
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
screen.fill(BLACK)
pos = pygame.mouse.get_pos()
#Gets position of the mouse
player.rect.x = pos[0]
player.rect.y = pos[1]
char_hit_list = pygame.sprite.spritecollide(player, char2_list, True)#Set it to false and see the result
#Checks collision
for block in char_hit_list:
score += 1
print score
all_list.draw(screen)
#renders(draw) all the sprites onto screen
pygame.display.update()
#update's display
clock.tick(60)
# Sets Frame Rate to 60
pygame.quit()2_list.add(block)
all_list.add(block)
player = Block(char2)
running = True
clock = pygame.time.Clock()
score = 1
all_list.add(player)
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
screen.fill(BLACK)
pos = pygame.mouse.get_pos()
#Gets position of the mouse
player.rect.x = pos[0]
player.rect.y = pos[1]
char_hit_list = pygame.sprite.spritecollide(player, char2_list, True)#Set it to false and see the result
#Checks collision
for block in char_hit_list:
score += 1
print score
all_list.draw(screen)
#renders(draw) all the sprites onto screen
pygame.display.update()
#update's display
clock.tick(60)
# Sets Frame Rate to 60
pygame.quit()
And one more thing try not to hard-code stuff like you did for screen dimension.
For learning more about pygame Sprites have a look at this.
If you have any problem, let me know by commenting in the comments section below, I'll try my best to help you out with your problem.
Keep pygaming :)

Pygame Sprite can jump but can't walk

I've been working through this online tutorial on Pygame (Python Version 3.3.1), and have come to a point where my sprite can jump, but can walk only a few pixels in either direction. I'd really like to move forward with this code as I like how it is structured (not a lot of code in the Main method). Can anyone spot what might be causing my sprite to get stuck?
import pygame
# Define some colors
black = ( 0, 0, 0)
white = ( 255, 255, 255)
green = ( 0, 255, 0)
red = ( 255, 0, 0)
class Player(pygame.sprite.Sprite):
def __init__(self, *groups):
super(Player, self).__init__(groups)
self.image = pygame.image.load('Images\player1.png')
self.rect = pygame.rect.Rect((50, 650), self.image.get_size())
self.resting = False
self.dy = 0 #dy represents change in y velocity
def update(self, dt, game):
last = self.rect.copy()
key = pygame.key.get_pressed()
if key[pygame.K_LEFT]:
self.rect.x -= 300 * dt
if key[pygame.K_RIGHT]:
self.rect.x += 300 * dt
#if key[pygame.K_UP]:
# self.rect.y -= 300 * dt
#if key[pygame.K_DOWN]:
# self.rect.y += 300 * dt
if self.resting and key[pygame.K_SPACE]:
self.dy = -500 #If space bar is pressed, increase velocity.
self.dy = min(400, self.dy + 40) #Speed capped at 400. Gravity set at 40.
self.rect.y += self.dy * dt
new = self.rect
self.resting = False
for cell in pygame.sprite.spritecollide(self, game.walls, False):
#self.rect = last
cell = cell.rect
if last.right <= cell.left and new.right > cell.left:
new.right = cell.left
if last.left >= cell.right and new.left < cell.right:
new.left = cell.right
if last.bottom <= cell.top and new.bottom > cell.top:
#if you hit something while jumping, stop.
self.resting = True
new.bottom = cell.top
self.dy = 0
if last.top >= cell.bottom and new.top < cell.bottom:
new.top = cell.bottom
self.dy = 0 #If you hit the floor while jumping, stop
class Game(object):
def main(self, screen):
clock = pygame.time.Clock()
dt = clock.tick(30)
#image = pygame.image.load('Images\player1.gif')
background = pygame.image.load('Images\_rec_bg.png')
sprites = pygame.sprite.Group()
self.player = Player(sprites)
self.walls = pygame.sprite.Group()
block = pygame.image.load('Images\dia_tile.png')
for x in range(0, 800, 20):
for y in range(0, 800, 20):
if x in (0, 800-20) or y in (0, 800-20):
wall = pygame.sprite.Sprite(self.walls)
wall.image = block
wall.rect = pygame.rect.Rect((x, y), block.get_size())
sprites.add(self.walls)
running = True
while running:
clock.tick(30) #run no more than 30 time per second
dt - clock.tick(30)
for event in pygame.event.get():
if event.type == pygame.QUIT or \
(event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE):
running = False
#sprites.update()
#sprites.update(dt / 1000.)
#screen.fill(black)
sprites.update(dt / 1000., self)
#screen.blit(image, (320, 240)) #Transfer to video RAM
screen.blit(background, (0,0))
sprites.draw(screen)
pygame.display.flip() #Dispaly to Screen
if __name__ == '__main__':
pygame.init()
screen = pygame.display.set_mode((800, 800))
Game().main(screen)
Im not sure but it looks like you're only letting the player move from side to side if the player is in the air (jumping)
If i'm right you need to enable youre player to move side to side even when self.resting = True
what happens if you do something like this:
if key[pygame.K_LEFT]:
self.rect.x -= 75
if key[pygame.K_RIGHT]:
self.rect.x += 75
the thing about that is the player will move from side to sdie but when you jump and press right or left the player will fly all over instead of going into a steady jump and fall
so you need to figure out how to include the *dt to regulate the players movement in air but at the same time have the player be able to move while on the ground to
try having two sets of if statments:
if key[pygame.K_LEFT]:
self.rect.x -= 300 * dt
if key[pygame.K_RIGHT]:
self.rect.x += 300 *dt
if key[pygame.K_LEFT]and self.resting:
self.rect.x -= 50
if key[pygame.K_RIGHT]and self.resting:
self.rect.x += 50
the first one is for in the air the second is for when the player is on the ground
try that and tell me if it works
i tried it on my computer and it worked but i probably used differnt art that could also be the problem becuase it might be blitting behind something so check everything
Good Luck!!

Categories

Resources