I'm writing this code to build a simple square which moves left and right and can jump on a stage using the colliderect function in pygame but the problem is when the player(square) jumps on the stage its y coordinate changes to the y coordinate of the stage permanently and never falls down. Another big issue is that when the player is below the stage it should not be able to jump over the top but it does. My code contains four pages, first contains the main loop, second contains the player class, third contains stage class and forth part contains the basic game functions
Main--Pg 01
import pygame
from player import Player
import game_functions as gf
import sys
from stage import Stage
from pygame.sprite import Group
def run_game():
# Intialise the game and start the screen
pygame.init()
screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption("AmarCreep")
player = Player(screen)
stage = Stage(screen)
clock = pygame.time.Clock()
# Main loop
while True:
clock.tick(60)
# Navy screen
screen.fill((173,216,249))
for event in pygame.event.get():
# Check if user wants to quit
if event.type == pygame.QUIT:
sys.exit()
gf.responses(screen, player, event)
# Update player's x-y coordinate
player.p_movements(stage)
stage.draw_stage()
# Make the player appear
player.draw_player()
# Make the newly made screen visible
pygame.display.flip()
run_game()
Player--Pg 02
import pygame
from pygame.sprite import Sprite
class Player(Sprite):
# Initialise the main player
def __init__(self, screen):
super(Player, self).__init__()
self.screen = screen
self.screen_rect = screen.get_rect()
# Specifying the position of the player at start
self.rect = pygame.Rect(0, 0, 30, 30)
self.rect.centerx = self.screen_rect.centerx
self.rect.bottom = 590
self.moving_left = False
self.moving_right = False
self.moving_up = False
self.vel_y = 18
def p_movements(self, stage):
dx = 0
dy = 0
# Predict the player movements beforehand
if self.moving_left and self.rect.x > 10:
dx -= 7
if self.moving_right and self.rect.x < 760:
dx += 7
if self.moving_up:
dy -= self.vel_y
self.vel_y -= 2
if self.vel_y < -18:
self.moving_up = False
self.vel_y = 18
# Check collisions in x direction
if stage.s_rect.colliderect(self.rect.x + dx, self.rect.y, 30, 30):
dx = 0
# Check collisions in y direction
if stage.s_rect.colliderect(self.rect.x, self.rect.y + dy, 30, 30):
if self.vel_y < 0:
dy = stage.s_rect.bottom - self.rect.top
self.vel_y = 0
elif self.vel_y > 0:
dy = stage.s_rect.top - self.rect.bottom
# Update the positionse
self.rect.x += dx
self.rect.y += dy
if self.rect.bottom > 590:
self.rect.bottom = 590
dy = 0
pygame.time.Clock().tick(60)
def draw_player(self):
''' Draw the player on the screen'''
pygame.draw.rect(self.screen, (245,245,245), self.rect)
Stage--Pg 03
import pygame
from pygame.sprite import Sprite
from random import randint
class Stage(Sprite):
"""Initialize the platform for player to jump on"""
def __init__(self, screen):
super(Stage, self).__init__()
self.screen = screen
self.screen_rect = screen.get_rect()
self.s_rect = pygame.Rect(0, 540, 80, 10)
self.s_rect.x = randint(10, 590)
def draw_stage(self):
''' Draw the platform for the player'''
pygame.draw.rect(self.screen, (0,0,0), self.s_rect)
Game functions--Pg 04
import pygame
def responses(screen, player, event):
''' Check for responses'''
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
player.moving_up = True
if event.key == pygame.K_LEFT:
player.moving_left = True
if event.key == pygame.K_RIGHT:
player.moving_right = True
elif event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT:
player.moving_left = False
if event.key == pygame.K_RIGHT:
player.moving_right = False
From what I can see about your code, you use colliderect with a collision box of 30x30: colliderect(self.rect.x + dx, self.rect.y, 30, 30)
Your level, or stage is 80x10: pygame.Rect(0, 540, 80, 10)
This means that the collision detection will only happen in a certain part of your stage. Here is a visual to help you better understand:
I believe this may be the source of your problems. After colliding with the red box, you have them teleport to around halfway, a time when they are still colliding with the box. This makes them constantly teleport back to where they were, as they are always getting put back into the red box, as they are colliding with it. This may cause some of your other errors.
Related
This question already has answers here:
Why is my PyGame application not running at all?
(2 answers)
Closed 1 year ago.
So I'm kinda new at Pygame, and just trying to create easy projects to learn.
I've created a basic rectangle first as player, and I want to implement a system where user clicks to somewhere in screen and game spawns a rectangle at that point. Here's my code:
import pygame
import sys
from pygame import *
from pygame.mouse import get_pos
pygame.init()
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
screen = pygame.display.set_mode((SCREEN_WIDTH,SCREEN_HEIGHT))
pygame.display.set_caption("Touch To Create Blocks!")
class Player(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.surf = pygame.Surface((50,50))
self.surf.fill((220,120,37))
self.rect = self.surf.get_rect()
def update(self,pressed_keys):
if pressed_keys[pygame.K_UP]:
self.rect.move_ip(0,-5)
elif pressed_keys[pygame.K_DOWN]:
self.rect.move_ip(0,5)
elif pressed_keys[pygame.K_LEFT]:
self.rect.move_ip(-5,0)
elif pressed_keys[pygame.K_RIGHT]:
self.rect.move_ip(5,0)
if self.rect.left < 0:
self.rect.left = 0
elif self.rect.right > SCREEN_WIDTH:
self.rect.right = SCREEN_WIDTH
elif self.rect.top <= 0:
self.rect.top = 0
elif self.rect.top >= SCREEN_HEIGHT - 50:
self.rect.bottom = SCREEN_HEIGHT
player = Player()
run = True
while run:
for event in pygame.event.get():
if event.type == QUIT:
run = False
sys.exit()
elif event.type == KEYDOWN:
if event.key == K_ESCAPE:
run = False
sys.exit()
elif event.type == MOUSEBUTTONDOWN:
mouse_x, mouse_y = pygame.mouse.get_pos()
rectangle = pygame.Rect(mouse_x, mouse_y, 40, 40)
pygame.draw.rect(screen, (255,255,255) , rectangle)
pygame.display.update()
screen.fill((0,0,0))
pressed_keys = pygame.key.get_pressed()
player.update(pressed_keys)
screen.blit(player.surf,player.rect)
pygame.display.update()
With that code, when I click, a block spawns and disappears immediately. How do I fix this? Thanks for your help.
(Sorry for my bad English)
The problem is that when the user clicks you draw the rectangle
(pygame.draw.rect), update the display (pygame.display.update) and
then, after the for loop, you empty the display
(screen.fill((0,0,0))). This explains why the rectangle disappears
immediately.
Instead of calling pygame.draw.rect each time the user clicks on the
screen, you can instead memorise the rectangle and save it into a
list. Then you have can draw all rectangles you memorised at each
iteration of your main loop.
Here is an implementation of this solution (I have added comments in
the code):
import pygame
import sys
from pygame import *
from pygame.mouse import get_pos
pygame.init()
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
screen = pygame.display.set_mode((SCREEN_WIDTH,SCREEN_HEIGHT))
pygame.display.set_caption("Touch To Create Blocks!")
class Player(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.surf = pygame.Surface((50,50))
self.surf.fill((220,120,37))
self.rect = self.surf.get_rect()
def update(self,pressed_keys):
if pressed_keys[pygame.K_UP]:
self.rect.move_ip(0,-5)
elif pressed_keys[pygame.K_DOWN]:
self.rect.move_ip(0,5)
elif pressed_keys[pygame.K_LEFT]:
self.rect.move_ip(-5,0)
elif pressed_keys[pygame.K_RIGHT]:
self.rect.move_ip(5,0)
if self.rect.left < 0:
self.rect.left = 0
elif self.rect.right > SCREEN_WIDTH:
self.rect.right = SCREEN_WIDTH
elif self.rect.top <= 0:
self.rect.top = 0
elif self.rect.top >= SCREEN_HEIGHT - 50:
self.rect.bottom = SCREEN_HEIGHT
player = Player()
run = True
rectangles = list() # list of the rectangles we have to draw
while run:
for event in pygame.event.get():
if event.type == QUIT:
run = False
sys.exit()
elif event.type == KEYDOWN:
if event.key == K_ESCAPE:
run = False
sys.exit()
elif event.type == MOUSEBUTTONDOWN:
# add a new rectangle to our list of rectangles
mouse_x, mouse_y = pygame.mouse.get_pos()
rectangles.append(pygame.Rect(mouse_x, mouse_y, 40, 40))
screen.fill((0,0,0))
pressed_keys = pygame.key.get_pressed()
player.update(pressed_keys)
screen.blit(player.surf,player.rect)
# draw all the rectangles we memorised
for rectangle in rectangles:
pygame.draw.rect(screen, (255,255,255) , rectangle)
pygame.display.update()
This is the code of a survive the horde type game I'm working on. I have been facing an issue where the alien(s) sometimes (enemy in code) randomly spawns at the bottom of the surface, even though I have specified their spawn location to be randomized (within a certain part of the surface).
What has made them spawn at the bottom of the surface, where they cannot be touched by bullets?
import pygame
import random
import math
# for initialising pygame (req for every pygame app)
pygame.init()
# making the basic window (dimensions must be written inside a tuple )
screen = pygame.display.set_mode((500, 500))
# background
background = pygame.image.load('C:/Users/aryan/Downloads/background.jpg')
# load and set the logo
logo = pygame.image.load('C:/Users/aryan/Downloads/bp.png') # directory of logo
pygame.display.set_icon(logo)
pygame.display.set_caption("space wars") # program name
# define a variable to control the main loop
running = True
# player
playerimg = pygame.image.load('C:/Users/aryan/Downloads/spaceship.png')
playerX = 218 # x and y coordinates of image
playerY = 350
playerxchange = 0 # this will be the change in movement in x direction of our image
playerychange = 0 # this will be the change in movement in y direction of our image
def player(x, y):
screen.blit(playerimg, (x, y)) # blit draws our image on the surface(basically the background)
# syntax for blit(imagename, (xcoordinate,ycoordinate))
class Enemy:
def __init__(self):
self.x = random.randint(0, 476)
self.y = random.randint(0, 300)
self.moveX = 0.2
self.moveY = 40
def move(self):
self.x += self.moveX
if self.y >= 476:
self.y = 476
self.moveY = 0
self.moveX = 0
if self.x <= 0:
self.moveX = 0.1
self.y += self.moveY
elif self.x >= 465:
self.moveX = -0.1
self.y += self.moveY
def draw(self):
screen.blit(enemyimg, (self.x, self.y))
# enemy
enemyimg = pygame.image.load('C:/Users/aryan/Downloads/enemy.png')
enemy_list = []
for i in range(5):
new_enemy = Enemy()
enemy_list.append(new_enemy)
# game over
overimg = pygame.image.load('C:/Users/aryan/Downloads/gameover.png')
# bullet
bulletimg = pygame.image.load('C:/Users/aryan/Downloads/bullet.png')
bulletX = 0
bulletY = 350
bulletxchange = 0
bulletychange = 1
bullet_state = "ready" # "ready" you cant see bullet on screen
# "fire" you can see bullet firing
bullets = [] # bullets is a list that contains the coordinates of every bullet
score = 0
font30 = pygame.font.SysFont(None, 30)
#class
# Functions
def enemy(x, y):
screen.blit(enemyimg, (x, y)) # blit draws our image on the surface(basically the background)
# syntax for blit(imagename, (xcoordinate,ycoordinate))
def firebullet(x, y):
global bullet_state
bullet_state = "ready"
bullets.append([x + 12, y + 6]) # Creating a new bullet
def iscollision(enemyX, enemyY, bulletX, bulletY):
distance = math.sqrt(math.pow(enemyX-bulletX, 2)+ math.pow(enemyY-bulletY,2)) # distance formula
if distance <= 20:
return True
else:
return False
def TextScore(game):
text2 = font30.render("Your Score is: " + str(game), True, (37, 97, 188))
screen.blit(text2, (10, 45))
# main loop
while running:
screen.fill((120, 120, 120)) # in order (r, g, b) . (0, 0, 0) is black (255, 0, 0) is red...
screen.blit(background, (0, 0))
# event handling, gets all event from the event queue
for event in pygame.event.get():
# only do something if the event is of type QUIT
if event.type == pygame.QUIT:
# change the value to False, to exit the main loop
running = False
# checking keystroke
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
playerxchange += 0.3 # change in movement will be 0.2 towards the right
if event.key == pygame.K_LEFT:
playerxchange -= 0.3 # change in movement will be 0.2 towards the right
if event.key == pygame.K_UP:
playerychange -= 0.3
if event.key == pygame.K_DOWN:
playerychange += 0.3
if event.key == pygame.K_SPACE:
bullet_state = "fire"
firebullet(playerX, playerY)
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT or event.key == pygame.K_DOWN or event.key == pygame.K_UP:
playerxchange = 0
playerychange = 0
playerY += playerychange
playerX += playerxchange # the value of playerx changes by +- 0.1 depending on keystroke
if playerX <= -64: # this teleports the spaceship from left end to right end
playerX = 564
elif playerX >= 564: # this teleports spaceship from right end to left
playerX = -64
if playerY >= 436: # this prevents spaceship from leaving vertically
playerY = 436
if playerY <= 0:
playerY = 0
# enemy movement
for enemy in enemy_list:
enemy.move()
# bullet movement
if bullet_state == "fire":
firebullet(playerX, playerY)
for bullet in bullets:
screen.blit(bulletimg, (bullet[0], bullet[1])) # Print a bullet
bullet[0] -= bulletxchange # Updates its position
bullet[1] -= bulletychange
if bullet[1] < 0:
bullets.remove(bullet)
# collision
for enemy in enemy_list:
for bullet in bullets: # Use a for-loop to iterate through all the bullets in the list.
collision = iscollision(enemy.x, enemy.y, bullet[0], bullet[1])
if collision: # Test if a single bullet collides with the enemy inside the loop.
score += 1
print(score)
bullets.remove(bullet) # Remove the bullet from the list when it collides with the enemy.
enemy.x = random.randint(0, 476) # if collision takes place, alien respawns
enemy.y = random.randint(0, 30)
TextScore(score)
player(playerX, playerY) # player method is called AFTER screen.fill otherwise the screen will fill after image has been blitted
for enemy in enemy_list: # new edit
enemy.draw()
pygame.display.update() # necessary for events to keep updating
The problem is that you are generating number out out of bounds defined in the move method of Enemy class. Specifically, the problem is with x for which the upper bound seems to be 465, but you are generating numbers up to 476.
I obviously can't test this, but replace
enemy.x = random.randint(0, 476) # if collision takes place, alien respawns
enemy.y = random.randint(0, 30)
with
enemy.x = random.randint(1, 464) # if collision takes place, alien respawns
enemy.y = random.randint(1, 30)
and the problem should go away.
After looking through your code, it seems like after a collision you set the respawn y coordinate to be between 0 and 30, which I assume is what you want. Although, your original y coordinate for spawning aliens goes from 0 to 300; this may be your issue as to why they are spawning farther down the screen?
Right now my game works as so: My sprite can move right or left, jump and shoot fireballs (bullets). However, once my sprite walks past the limit of my background surface, it goes off-screen. So I want to make the background move along with my sprite. As soon as my player sprite moves about 50 pixels towards the edges of the screen, the background moves too. How do I create this with Pygame? I've found quite an amount of sources which shows you how to do this but with a plain colour background. But my background is an image I load into the game, so I would like to learn how to do so with an image as background. How to make it repeat once the sprite comes near the limit of both sides. I separated my codes into 3 different files: a Main.py, settings.py and Sprite1.py. Here's Main.py:
import pygame
import os
import sys
import time
from pygame import mixer
from Sprite1 import *
from settings import *
'''
Setup
'''
pygame.init()
clock = pygame.time.Clock()
pygame.mixer.music.load('.\\sounds\\Fairy.mp3')
pygame.mixer.music.play(-1, 0.0)
all_sprites = pygame.sprite.Group()
player = Player(all_sprites)
player.rect.x = 50
player.rect.y = 500
showStartScreen(surface)
'''
Main loop
'''
main = True
while main == True:
background = pygame.image.load(os.path.join('images', 'Bg.png'))
surface.blit(background, (0,0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
main = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT or event.key == ord('a'):
player.control(-steps,0)
if event.key == pygame.K_RIGHT or event.key == ord('d'):
player.control(steps,0)
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == ord('a'):
player.control(steps,0)
if event.key == pygame.K_RIGHT or event.key == ord('d'):
player.control(-steps,0)
keys = pygame.key.get_pressed()
if not(isJump):
if keys[pygame.K_UP]:
isJump = True
else:
if jumpCount >= -10:
player.rect.y -= (jumpCount * abs(jumpCount)) * 1
jumpCount -= 2
else:
jumpCount = 10
isJump = False
# dt = time since last tick in milliseconds.
dt = clock.tick(60) / 1000
all_sprites.update(dt)
player.update(dt)
all_sprites.draw(surface) #refresh player position
pygame.display.flip()
Here's settings.py:
import pygame
isJump = False
jumpCount = 10
width = 960
height = 720
fps = 40 # frame rate
#ani = 4 # animation cycles
pygame.display.set_caption('B.S.G.')
surface = pygame.display.set_mode((width, height))
PLAYER_ACC = 0.5
PLAYER_FRICTION = -0.12
PLAYER_GRAV = 0.8
PLAYER_JUMP = 20
PLAYER_LAYER = 2
PLATFORM_LAYER = 1
steps = 10 # how fast to move
And here's Sprite1.py:
import pygame
import sys
import os
import time
from pygame import mixer
from pygame.locals import *
from settings import *
vec = pygame.math.Vector2
def showStartScreen(surface):
show = True
while (show == True):
background = pygame.image.load(os.path.join('images', 'Starting_scr.png'))
# rect = surface.get_rect()
surface.blit(background, (0,0))
pygame.display.flip()
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONDOWN:
show = False
class Player(pygame.sprite.Sprite):
def __init__(self, all_sprites):
pygame.sprite.Sprite.__init__(self)
self.movex = 0
self.movey = 0
self.frame = 0
self.health = 10
self.jumping = False
self.images = []
self.imagesleft = []
self.imagesright = []
self.direction = "right"
self.alpha = (0,0,0)
self.ani = 4 # animation cycles
self.all_sprites = all_sprites
self.add(self.all_sprites)
self.bullet_timer = .1
for i in range(1,5):
img = pygame.image.load(os.path.join('images','hero' + str(i) + '.png')).convert()
img.convert_alpha()
img.set_colorkey(self.alpha)
self.imagesright.append(img)
self.image = self.imagesright[0]
self.rect = self.image.get_rect()
for i in range(1,5):
img = pygame.image.load(os.path.join('images','hero' + str(i) + '.png')).convert()
img = pygame.transform.flip(img, True, False)
img.convert_alpha()
img.set_colorkey(self.alpha)
self.imagesleft.append(img)
self.image = self.imagesleft[0]
self.rect = self.image.get_rect()
def control(self,x,y):
'''
control player movement
'''
self.movex += x
self.movey -= y
def update(self, dt):
'''
Update sprite position
'''
self.rect.x = self.rect.x + self.movex
self.rect.y = self.rect.y + self.movey
# moving left
if self.movex < 0:
self.frame += 1
if self.frame > 3*self.ani:
self.frame = 0
self.image = self.imagesleft[self.frame//self.ani]
self.direction = "left"
# moving right
if self.movex > 0:
self.frame += 1
if self.frame > 3*self.ani:
self.frame = 0
self.image = self.imagesright[self.frame//self.ani]
self.direction = "right"
#enemy_hit_list = pygame.sprite.spritecollide(self,enemy_list, False)
#for enemy in enemy_hit_list:
#self.health -= 1
#print(self.health)
keys = pygame.key.get_pressed()
if keys[pygame.K_SPACE]:
self.bullet_timer -= dt # Subtract the time since the last tick.
if self.bullet_timer <= 0:
self.bullet_timer = 100 # Bullet ready.
if keys: # Left mouse button.
# Create a new bullet instance and add it to the groups.
if self.direction == "right":
Bullet([self.rect.x + self.image.get_width(), self.rect.y + self.image.get_height()/2], self.direction, self.all_sprites)
else:
Bullet([self.rect.x, self.rect.y + self.image.get_height()/2], self.direction, self.all_sprites)
self.bullet_timer = .1 # Reset the timer.
class Bullet(pygame.sprite.Sprite):
IMAGE = None
FLIPPED_IMAGE = None
def __init__(self, pos, direction, *sprite_groups):
super().__init__(*sprite_groups)
# cache images
if not Bullet.IMAGE:
Bullet.IMAGE = pygame.image.load(os.path.join('images','fireball.png'))
Bullet.FLIPPED_IMAGE = pygame.transform.flip(Bullet.IMAGE, True, False)
if direction == "right":
self.vel = pygame.math.Vector2(750, 0)
self.image = Bullet.IMAGE
else:
self.vel = pygame.math.Vector2(-750, 0)
self.image = Bullet.FLIPPED_IMAGE
self.pos = pygame.math.Vector2(pos)
self.rect = self.image.get_rect(center=pos)
def update(self, dt):
# Add the velocity to the position vector to move the sprite
self.pos += self.vel * dt
self.rect.center = self.pos # Update the rect pos.
if not pygame.display.get_surface().get_rect().colliderect(self.rect):
self.kill()
I'm open to any suggestions. Thanks beforehand!
Here's how I would approach this...
set up a scrolling background as in the tutorial and make sure you can get that working OK by moving the background back & forth instead of the player (just freeze the player's x coordinate in the center and move the background with your left/right keys.
Add some constants into your settings for an edge buffer (the number of x-increments you want the player to avoid the boundaries by
AFTER you get the key input (left or right) set up a conditional statement. For this, you will have to access the player's x-coordinate and compare it to the buffer. Well, either 0+buffer or width-buffer actually and then based on those cases either move the player or the background. See if you can get that working.
Then, you will realize that when you move the background, you are moving the frame of reference for everything else, meaning things like the fireball, so if you are moving the background left or right, you will need to apply those updates to the other objects as well so it looks correct.
If yer stuck, make those updates to code above & message me back in a comment.
project game
import pygame
import os
import random from pygame.locals import * # Constants
import math
import sys
import random
pygame.init()
screen=pygame.display.set_mode((1280,720)) #(length,height)
screen_rect=screen.get_rect()
background = pygame.Surface(screen.get_size())
background.fill((255,255,255)) # fill the background white
White = (255,255,255)
---------------------------------------------------------------------
background = pygame.image.load('stage.png').convert()
screen.blit(background, (0, 0))
class Player(pygame.sprite.Sprite):
def __init__(self):
self.rect = pygame.draw.rect(screen, (0,0,128), (50,560,50,25)) #(colour)(x-position,y-position,width,height)
self.dist = 100
def draw_rect(self,x,y): # This is my code which should make the player move
screen.blit(background, (0, 0)) #If this isn't included then when the rectangle moves it's old positon will still be on the screen
self.rect = self.rect.move(x*self.dist, y*self.dist); pygame.draw.rect(screen, (0, 0, 128), self.rect)
pygame.display.update()
def handle_keys(self): # code to make the character move when the arrow keys are pressed
for e in pygame.event.get():
if e.type == KEYDOWN:
key = e.key
if key == K_LEFT:
self.draw_rect(-0.5,0)
elif key == K_RIGHT:
self.draw_rect(0.5,0)
elif key == K_UP:
self.draw_rect(0,-0.5)
elif key == K_DOWN:
self.draw_rect(0,0.5)
elif key == K_SPACE:
self.draw_rect(2,-3)
if self.rect.right > 1400:
self.rect.right = 1400
if self.rect.left < 0:
self.rect.left = 0
if self.rect.bottom > 500:
self.rect.bottom = 500
if self.rect.top < 0:
self.rect.top = 0
player = Player()
------------------------------------------------------------------------
class Enemy(pygame.sprite.Sprite): # the enemy class which works fine
def __init__(self):
x = random.randint(50,450)
self.rect = pygame.draw.rect(screen, (128,0,0), (300,x,50,25))
enemy = Enemy()
pygame.display.flip() #updates the whole screen
def main(): #my main loop
while True:
player.handle_keys()
for event in pygame.event.get
if event.type == pygame.QUIT:
running = False
if __name__ == '__main__': main()
The player does move but when the keys are pressed and the player moves the enemy disappears so i need help to fix it
Ext the player doesn't move when the arrow keys are held only when pressed
You were checking for keydown events in your player's handle_keys method. Any keydown events only register once until the next keyup. You want to use pygame.key.get_pressed() which returns a dict of all the pressed keys at any given moment. I've fixed it for you as well as cleaned the code up a little bit. You may want to consider using a delay or pygame's built-in Clock class for controlling framerates. If you notice, I had to change your movements to very tiny numbers (0.05 from 0.5) because of how quickly you update your frames. Adding in time.sleep() or the pygame clock would fix this.
import pygame
import os
import random
from pygame.locals import * # Constants
import math
import sys
import random
pygame.init()
screen=pygame.display.set_mode((1280,720)) #(length,height)
screen_rect=screen.get_rect()
background = pygame.Surface(screen.get_size())
background.fill((255,255,255)) # fill the background white
White = (255,255,255)
class Player(pygame.sprite.Sprite):
def __init__(self):
self.rect = pygame.draw.rect(screen, (0,0,128), (50,560,50,25)) #(colour)(x-position,y-position,width,height)
self.dist = 100
def draw_rect(self,x,y): # This is my code which should make the player move
screen.blit(background, (0, 0)) #If this isn't included then when the rectangle moves it's old positon will still be on the screen
self.rect = self.rect.move(x*self.dist, y*self.dist); pygame.draw.rect(screen, (0, 0, 128), self.rect)
pygame.display.update()
def handle_keys(self): # code to make the character move when the arrow keys are pressed
keys = pygame.key.get_pressed()
if keys[K_LEFT]:
self.draw_rect(-0.05,0)
elif keys[K_RIGHT]:
self.draw_rect(0.05,0)
elif keys[K_UP]:
self.draw_rect(0,-0.05)
elif keys[K_DOWN]:
self.draw_rect(0,0.05)
elif keys[K_SPACE]:
self.draw_rect(2,-3)
if self.rect.right > 1400:
self.rect.right = 1400
if self.rect.left < 0:
self.rect.left = 0
if self.rect.bottom > 500:
self.rect.bottom = 500
if self.rect.top < 0:
self.rect.top = 0
class Enemy(pygame.sprite.Sprite): # the enemy class which works fine
def __init__(self):
x = random.randint(50,450)
self.rect = pygame.draw.rect(screen, (128,0,0), (300,x,50,25))
player = Player()
enemy = Enemy()
def main(): #my main loop
running = True
while running:
player.handle_keys()
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
pygame.display.flip() #updates the whole screen
if __name__ == '__main__': main()
I've tried everything and cannot get how I check if my two blocks have collided.
Here's my code:
import pygame
import random
pygame.init()
display_width = 600
display_height = 300
class player:#Just info for player
width = 30
height = 30
x = display_width // 2
y = display_height - height - 5
a = x + 30
pic = 'SnakePart.png'
thing = pygame.image.load(pic)
def place(x,y):#function for placing player object
gameDisplay.blit(player.thing, (player.x,player.y))
class enemy:#enemy info class
width = 30
height = 30
x = random.randint(0,display_width - width)
y = 1
a = x + 30
pic = 'Apple.png'
thing = pygame.image.load(pic)
speed = 10#sets speed
def change_x():
enemy.x = random.randint(0,display_width - enemy.width)
def change_y():
enemy.y += enemy.speed
def make(x,y):#set up funtion
gameDisplay.blit(enemy.thing, (x,y))
def respawn():#reseting enemy entity
enemy.y = 1
gameDisplay.blit(enemy.thing, (enemy.x,enemy.y))
player.thing#uses the variables in the classes to set up the images for use
enemy.thing
black = (0,0,0)
white = (255,255,255)
player_height = 30
player_width = 30
clock = pygame.time.Clock()
x_change = 0#This is to make movment
gameDisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption('Bullet Hell.')
dodged = 0#counter will be used in the more polished vesion.
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:#Checks for keypress, to make player entity move
if event.key == pygame.K_RIGHT:
x_change = 5
if event.key == pygame.K_LEFT:
x_change = -5
if event.type == pygame.KEYUP:
if event.key == pygame.K_RIGHT or pygame.K_LEFT:
x_change = 0
player.x += x_change
gameDisplay.fill(black)
enemy.make(enemy.x,enemy.y)
player.place(player.x,player.y)
enemy.change_y()
if enemy.y > display_height:#Brings enemy back to top once it has gotten to th bottom
enemy.change_x()
dodged += 1
enemy.respawn()
pygame.display.update()
clock.tick(60)
It's all really the collision and I think I'll be good. Oh yeah, if you guys could also tell me how to display text that would be great!
Take a look at the pygame.Rect class and its collision detection methods. Give your objects rects as attributes which you get by calling the .get_rect() method of the images/surfaces. Update the coordinates of these rects each frame and in your main loop call player.rect.colliderect(enemy.rect) to check if the two rects collide.
import pygame
import random
pygame.init()
BLACK = pygame.Color('black')
display = pygame.display.set_mode((600, 300))
# Create a rect with the dimensions of the screen at coords (0, 0).
display_rect = display.get_rect()
clock = pygame.time.Clock()
# SNAKE_IMAGE = pygame.image.load('SnakePart.png').convert_alpha()
# APPLE_IMAGE = pygame.image.load('Apple.png').convert_alpha()
# Replacement images.
SNAKE_IMAGE = pygame.Surface((30, 30))
SNAKE_IMAGE.fill((30, 150, 0))
APPLE_IMAGE = pygame.Surface((30, 30))
APPLE_IMAGE.fill((150, 30, 0))
class Player:
def __init__(self):
self.x = display_rect.w // 2
self.y = display_rect.h - 30 - 5
self.image = SNAKE_IMAGE
# Create a rect with the size of the image at coords (0, 0).
self.rect = self.image.get_rect()
# Set the topleft coords of the rect.
self.rect.x = self.x
self.rect.y = self.y
self.x_change = 0
def update(self):
"""Move the player."""
self.x += self.x_change
# Always update the rect, because it's
# needed for the collision detection.
self.rect.x = self.x
def draw(self, display):
display.blit(self.image, self.rect)
class Enemy:
def __init__(self):
self.x = random.randint(0, display_rect.w - 30)
self.y = 1
self.image = APPLE_IMAGE
# You can also pass the coords directly to `get_rect`.
self.rect = self.image.get_rect(topleft=(self.x, self.y))
self.speed = 10
def change_x(self):
self.x = random.randint(0, display_rect.w - self.rect.w)
self.rect.x = self.x
def change_y(self):
self.y += self.speed
self.rect.y = self.y
def draw(self, display):
display.blit(self.image, self.rect)
def reset(self):
"""Reset self.y position."""
self.y = -30
player = Player()
enemy = Enemy()
dodged = 0
done = False
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
player.x_change = 5
if event.key == pygame.K_LEFT:
player.x_change = -5
if event.type == pygame.KEYUP:
if event.key == pygame.K_RIGHT or pygame.K_LEFT:
player.x_change = 0
# Game logic.
player.update()
enemy.change_y()
# Brings enemy back to top once it has gotten to th bottom
if enemy.y > display_rect.h:
enemy.change_x()
dodged += 1
enemy.reset()
# Check if the player and the rect collide.
if player.rect.colliderect(enemy.rect):
print('Collided!')
# Draw everything.
display.fill(BLACK)
enemy.draw(display)
player.draw(display)
pygame.display.update()
clock.tick(60)
pygame.quit()
I've changed some more things (btw, better call the images self.image not thing ;)) especially in the classes:
The attributes of the classes should be in __init__ methods to make them instance attributes instead of class attributes (which get shared by all instances). Also, check out how to create instances of your classes.
The methods should all have self as their first parameter (that's a reference to the instance). To access the attributes inside of the classes prepend them with self, e.g. self.x += self.x_change.
The player.x += x_change line fits better inside the Player class' update method, so you can just update the position and other player attributes by calling player.update().
There's a convention that class names should be uppercase MyClass whereas instances should have lowercase names my_instance.