I am creating a simple Pygame game and the character was moving around the screen when I pressed the arrow keys. I have added an intro which has the title and 2 buttons and when the green button is pressed to start the game, the game loads but the character no longer moves when the keys are pressed. Can someone please help tell me why the arrow keys no longer move the character? Thank you!
Code:
import time
#we need to initiate pygame at the start of all our code
pygame.init()
display_width = 800
display_height = 600
#creating window, in tuple is width and height of screen
win = pygame.display.set_mode((display_width, display_height))
x = (display_width * 0.45)
y = (display_height * 0.8)
black = (0,0,0)
white = (255,255,255)
red = (200,0,0)
green = (0,200,0)
bright_red = (255, 0, 0)
bright_green = (0,255,0)
def crash():
message_display('Item collected')
#button
def button(msg,x,y,w,h,ic,ac, action=None):
mouse = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
#print(mouse)
if x + w > mouse[0] > x and y+h > mouse[1] > y:
pygame.draw.rect(win, ac, (x,y,w,h))
if click[0] == 1 and action != None:
action()
def collect_item():
message_display('Do you want to pick up item?')
button("YES",150,450,100,50,green, bright_green, game_loop)
button("NO",550,450,100, 50, red, bright_red, game_loop)
#def game_loop():
#x = (display_width * 0.45)
#y = (display_height * 0.8)
#x_change = 0
#dodged = 0
#run = True
#good idea to create a screen width variable
screenWidth = 800
#Name of our window
pygame.display.set_caption("First Game")
#Code for importing multiple images of the animated sprite
#walk right animation
walkRight = [pygame.image.load('R1.PNG'), pygame.image.load('R2.PNG'), pygame.image.load('R3.PNG')]
#walk left animation
walkLeft = [pygame.image.load('L1.PNG'), pygame.image.load('L2.PNG'), pygame.image.load('L3.PNG')]
#back ground image load in
bg = pygame.image.load('grass11.jpg')
#Basic standing sprite, it is the still image. shows this character when they are not moving
char = pygame.image.load('front.PNG')
def puff(x,y):
win.blit(char (x,y))
#allows us to change our fps in the game
clock = pygame.time.Clock()
swordIMG = pygame.image.load('smallsword.png')
staffIMG = pygame.image.load('staff.png')
chestIMG = pygame.image.load('chest.png')
coinIMG = pygame.image.load('coin.png')
def text_objects(text, font):
textSurface = font.render(text, True, black)
return textSurface, textSurface.get_rect()
def message_display(text):
largeText = pygame.font.Font('freesansbold.ttf', 115)
TextSurf, TextRect = text_objects(text, largeText)
TextRect.center = ((display_width/2)), ((display_height/2))
win.blit(TextSurf, TextRect)
pygame.display.update()
time.sleep(2)
def quitgame():
pygame.quit()
quit()
def game_intro():
intro = True
while intro:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
win.fill(white)
largeText = pygame.font.Font('freesansbold.ttf', 115)
TextSurf, TextRect = text_objects("TITLE", largeText)
TextRect.center = ((display_width/2)), ((display_height/2))
win.blit(TextSurf, TextRect)
#Button
button("GO!",150,450,100,50,green, bright_green, game_loop)
button("Quit",550,450,100, 50, red, bright_red, quitgame)
pygame.display.update()
#creating character
#x = 50
#y = 400
#width and height of sprite
width = 100
height = 100
#staff
staffwidth = 94
staffheight = 106
#coin
coinwidth = 74
coinheight = 74
#chest
chestwidth = 84
chestheight = 84
#velocity is how fast the character moves
vel = 5
left = False
right = False
walkCount = 0
#function which redraws the game window, this area is for drawing, we do not draw in main loop
def redrawGameWindow():
#x = (display_width * 0.45)
#y = (display_height * 0.8)
global walkCount
win.blit(bg, (0,0)) #back ground image
win.blit(swordIMG,(600,400))
win.blit(staffIMG, (70, 60))
win.blit(chestIMG, (600, 100))
win.blit(coinIMG, (350,300))
if walkCount + 1 >= 0:
walkCount = 0
if left:
win.blit(walkLeft[walkCount], (x,y)) #displaying walk left sprite
walkCount += 1
elif right:
win.blit(walkRight[walkCount], (x,y))
walkCount += 1
#repeat for up and down
else:
win.blit(char, (x,y)) #if we are not moving we blit our character
pygame.display.update() #if we want something to show on the screen in pygame, we must update the screen
#main loop for program
#main loop
#run the variable
#def game_loop():
#redrawGameWindow()
#x = (display_width * 0.45)
#y = (display_height * 0.8)
#x_change = 0
#dodged = 0
def game_loop():
x = (display_width * 0.45)
y = (display_height * 0.8)
x_change = 0
dodged = 0
run = True
while run:
#redrawGameWindow()
#game_intro()
clock.tick(27) #sets fps to 20 seconds
#pygame.time.delay(100) #clock in pgyame, parameter is milliseconds
for event in pygame.event.get(): #event is what player does eg. mouse click or key press
if event.type == pygame.QUIT: #if they click the x button (quit)
run = FALSE #loop = false
#using arrow keys to move shape
# all of the and's mean the shape cannot move off the screen
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT] and x > vel:
x -= vel
left = True
right = False
elif keys[pygame.K_RIGHT] and x < 800 - width - vel: #screen width - width of character
x += vel
right = True
left = False
elif keys[pygame.K_UP] and y > vel:
y -= vel
up = True
down = False
elif keys[pygame.K_DOWN] and y < 600 - height - vel:
y += vel
down = True
up = False
else:
right = False
left = False
up = False
down = False
walkCount = 0
if x < 100 - vel and x > 50 - vel and y > 40 - vel and y < 70:
crash()
if x > 600 - vel and x < 703 - vel and y > 400 - vel and y < 502 - vel:
crash()
if x > 330 - vel and x < 420 - vel and y > 280 - vel and y < 300 - vel:
crash()
if x > 600 - vel and x < 684 - vel and y > 100 - vel and y < 184 - vel:
crash()
redrawGameWindow()
#if y < 160 - vel and y > 90 - vel:
#crash()
game_intro()
#game_loop()
#redrawGameWindow() #call function
pygame.quit #game ends
The variables x, y, right, left, up, down and walkCount are variables in global name space. You have to use the global statement, if you want to write to the variables in global namespace, from within the function game_loop:
def game_loop():
global x, y, left, right, up, down, walkCount
x = (display_width * 0.45)
y = (display_height * 0.8)
x_change = 0
dodged = 0
run = True
while run:
# [...]
Furthermore, the buttons are not drawn, if the mouse is not on the buttons:
def button(msg,x,y,w,h,ic,ac, action=None):
mouse = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
pygame.draw.rect(win, ic, (x,y,w,h)) # <--- This line is missing
if x + w > mouse[0] > x and y+h > mouse[1] > y:
pygame.draw.rect(win, ac, (x,y,w,h))
if click[0] == 1 and action != None:
action()
Related
This question already has answers here:
How can i shoot a bullet with space bar?
(1 answer)
How do I detect collision in pygame?
(5 answers)
How do I stop more than 1 bullet firing at once?
(1 answer)
Closed 1 year ago.
This program currently makes two squares appear on the screen when you press start, the one on the left is controlled using WASD whilst the one on the right is controlled using the arrow keys. I want to make it so that when you click spacebar, the square on the left shoots a red rectangle (the bullet) to the right of the screen and if it hits the other square, then the health goes down by one. If it doesn't hit the other square, the bullet hits the edge of the screen and disappears (I would also like the other square to do this too but the other way around and instead of pressing space you press right control). The health variable for both squares is on lines 9 and 10. Can somebody please tell me how to do this?
Full Code (The two key presses that I would like to make the chosen character shoot are lines 60 and 72):
import pygame
import sys
import os
pygame.init()
FPS = 60
HEALTH_L = 3
HEALTH_R = 3
start_smallfont = pygame.font.SysFont('Corbel', 45)
start_text = start_smallfont.render('Start', True, (255, 255, 255))
rect_smallfont = pygame.font.SysFont('Corbel', 33)
rect_text = rect_smallfont.render('You', True, (255, 255, 255))
x = 630
y = 325
x2 = 170
y2 = 325
vel = 0.1
startWIDTH, startHEIGHT = 170, 80
screenWIDTH, screenHEIGHT = 800, 720
WIN = pygame.display.set_mode((screenWIDTH, screenHEIGHT))
pygame.display.set_caption(":D")
def main():
clock = pygame.time.Clock()
run = True
while run:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
pygame.quit()
if event.type == pygame.MOUSEBUTTONDOWN:
if 800/2-85 <= mouse[0] <= 800/2-85+startWIDTH and 720/2-40 <= mouse[1] <= 720/2-40+startHEIGHT:
clock.tick(FPS)
run = False
while True:
global x, y, x2, y2, movingx
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
WIN.fill((0, 0, 0))
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT] and x > vel:
x -= vel
if keys[pygame.K_RIGHT] and x < screenWIDTH - 50 - vel:
x += vel
if keys[pygame.K_UP] and y > vel:
y -= vel
if keys[pygame.K_DOWN] and y < screenHEIGHT - 50 - vel:
y += vel
if keys[pygame.K_SPACE]:
#PUT BULLET FUNCTION HERE
if keys[pygame.K_a] and x2 > vel:
x2 -= vel
if keys[pygame.K_d] and x2 < screenWIDTH - 50 - vel:
x2 += vel
if keys[pygame.K_w] and y2 > vel:
y2 -= vel
if keys[pygame.K_s] and y2 < screenHEIGHT - 50 - vel:
y2 += vel
if keys[pygame.K_RCTRL]:
#PUT BULLET FUNCTION HERE
pygame.draw.rect(WIN, (255, 0, 0), (x, y, 50, 50))
pygame.draw.rect(WIN, (255, 0, 0), (x2, y2, 50, 50))
pygame.display.update()
mouse = pygame.mouse.get_pos()
if 800/2-85 <= mouse[0] <= 800/2-85+startWIDTH and 720/2-40 <= mouse[1] <= 720/2-40+startHEIGHT:
pygame.draw.rect(WIN, (255, 91, 91), (800/2-85, 720/2-40, startWIDTH, startHEIGHT))
else:
pygame.draw.rect(WIN, (255, 0, 0), (800/2-85, 720/2-40, startWIDTH, startHEIGHT))
WIN.blit(start_text, (800/2-85+42,720/2-40+20))
pygame.display.update()
if __name__ == "__main__":
main()
This question already has answers here:
pygame 2 dimensional movement of an enemy towards the player, how to calculate x and y velocity?
(1 answer)
Pygame make sprite walk in given rotation
(1 answer)
How to make smooth movement in pygame
(2 answers)
Closed 1 year ago.
I created a circle in pygame. The circle moves to wherever you click, but instead of "walking" over there, it just appears. I tried some ways, but it doesn't work. If you could find out a way to do it, that would be great. The moving function is in the move function in the Player class.
# import
import pygame
# initialize pygame
pygame.init()
# frame rate variables
FPS = 120
clock = pygame.time.Clock()
# game variables
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 800
mouse_pos = ''
# colors
BLUE = (0, 0, 255)
# activate screen
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption('Bonker')
class Player(pygame.sprite.Sprite):
def __init__(self, x, y):
# init the sprite class
pygame.sprite.Sprite.__init__(self)
self.x = x
self.y = y
self.mouse_x = 0
self.mouse_y = 0
def move(self):
# delta x and delta y
dx = 0
dy = 0
# extract info from tuple
(x, y) = mouse_pos
self.mouse_x = x
self.mouse_y = y
# create tuple destination and current position tuple
destination = (self.mouse_x, self.mouse_y)
current_pos = [self.x, self.y]
# draw the rectangle
if current_pos[0] >= SCREEN_WIDTH // 2:
dx = 10
self.x += dx
if current_pos[0] < SCREEN_WIDTH // 2:
dx = -10
self.x += dx
if current_pos[1] >= SCREEN_HEIGHT // 2:
dy = 10
self.y += dy
if current_pos[1] < SCREEN_HEIGHT // 2:
dy = -10
self.y += dy
pygame.draw.circle(screen, BLUE, (self.x, self.y), 20)
def draw(self):
# draw the circle
pygame.draw.circle(screen, BLUE, (SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2), 20)
# create instances
# player instance
player = Player(SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2)
player.draw()
# main loop
run = True
while run:
# run frame rate
clock.tick(FPS)
# events
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.MOUSEBUTTONDOWN:
screen.fill((0, 0, 0))
mouse_pos = pygame.mouse.get_pos()
player.move()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
run = False
pygame.display.update()
pygame.quit()
I think some code is not needed
Help would be appreciated
This will move the circle to the mouse position. It doesn't move in one diagonal, but that can be changed.
# import
import pygame
# initialize pygame
pygame.init()
# frame rate variables
FPS = 120
clock = pygame.time.Clock()
# game variables
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 800
# colors
BLUE = (0, 0, 255)
# activate screen
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption('Bonker')
class Player(pygame.sprite.Sprite):
def __init__(self, x, y):
# init the sprite class
pygame.sprite.Sprite.__init__(self)
self.rect = pygame.Rect(0, 0, 40, 40)
self.rect.x = x
self.rect.y = y
self.radius = 20
self.destination = None
self.moving = False
self.dx = 0
self.dy = 0
def set_destination(self, pos):
self.destination = pos
# delta x and delta y
self.dx = self.destination[0] - self.rect.centerx
self.dy = self.destination[1] - self.rect.centery
self.moving = True
def move(self):
if self.rect.centerx != self.destination[0]:
if self.dx > 0:
self.rect.centerx += 1
elif self.dx < 0:
self.rect.centerx -= 1
if self.rect.centery != self.destination[1]:
if self.dy > 0:
self.rect.centery += 1
elif self.dy < 0:
self.rect.centery -= 1
elif self.rect.center == self.destination:
self.moving = False
def draw(self):
# draw the circle
pygame.draw.circle(screen, BLUE, self.rect.center, self.radius)
# create instances
# player instance
player = Player(SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2)
player.draw()
# main loop
run = True
movetime = 100
move = False
while run:
# run frame rate
dt = clock.tick(FPS)
movetime -= dt
if movetime <= 0:
move = True
movetime = 400
# events
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.MOUSEBUTTONDOWN:
mouse_pos = pygame.mouse.get_pos()
player.set_destination(mouse_pos)
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
run = False
if player.moving:
player.move()
screen.fill((0, 0, 0))
player.draw()
pygame.display.update()
pygame.quit()
I have been following this tutorial to build a simple 2D game using pygame.
I have checked multiple times my code but I still can't figure out what this error means
import pygame as pygame
pygame.init()
window = pygame.display.set_mode((500, 500))
pygame.display.set_caption('First Game')
pygame.display.update()
Here I set up all commands in response to the user's imput
walkRight = [pygame.image.load('R1.png'), pygame.image.load('R2.png'), pygame.image.load('R3.png'),
pygame.image.load('R4.png'), pygame.image.load('R5.png'), pygame.image.load('R6.png'),
pygame.image.load('R7.png'), pygame.image.load('R8.png'), pygame.image.load('R9.png')]
walkLeft = [pygame.image.load('L1.png'), pygame.image.load('L2.png'), pygame.image.load('L3.png'),
pygame.image.load('L4.png'), pygame.image.load('L5.png'), pygame.image.load('L6.png'),
pygame.image.load('L7.png'), pygame.image.load('L8.png'), pygame.image.load('L9.png')]
bg = pygame.image.load('bg.jpg')
char = pygame.image.load('standing.png')
clock = pygame.time.Clock()
x = 50
y = 50
width = 64
height = 64
vel = 5
isJump = False
jumpCount = 10
left = False
right = False
walkCount = 0
run = True
Here I defined the frames and the corresponding pictures with each movement. The problem is coming from here but I don't understand why
def redrawgamewindow():
global walkCount
window.blit(bg, (0, 0))
pygame.draw.rect(window, (255, 255, 255), (x, y, width, height))
if walkCount + 1 >= 27:
walkCount = 0
if left:
window.blit(walkLeft[walkCount // 3], (x, y))
walkCount += 1
elif right:
window.blit(walkRight[walkCount // 3], (x, y))
walkCount += 1
else:
window.blit(char, (x, y))
walkCount = 0
pygame.display.update()
while run:
clock.tick(27)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT] and x > vel:
x -= vel
right = False
left = True
elif keys[pygame.K_RIGHT] and x < 500 - (width + vel):
x += vel
right = True
left = False
else:
right = False
left = False
walkCount = 0
if not isJump:
if keys[pygame.K_UP] and y > vel:
y -= vel
if keys[pygame.K_DOWN] and y < 500 - (height + vel):
y += vel
if keys[pygame.K_SPACE]:
isJump = True
right = False
left = False
else:
if jumpCount >= -10:
neg = 1
if jumpCount < 0:
neg = -1
y -= (jumpCount * abs( jumpCount))*0.5
jumpCount -= 1
else:
isJump = False
jumpCount = 10
redrawgamewindow()
pygame.quit()
The error displayed is
/Users/Thomas.V/Documents/Documents/Perso/Coding /Python /Pycharm Projects/Pygame.py:40: DeprecationWarning: an integer is required (got type float). Implicit conversion to integers using __int__ is deprecated and may be removed in a future version of Python.
pygame.draw.rect(window, (255, 255, 255), (x, y, width, height))
The warning is caused because y is not an integral value, because of
y -= (jumpCount * abs( jumpCount))*0.5
Get rid of the warning by rounding y (see round):
pygame.draw.rect(window, (255, 255, 255), (x, round(y), width, height))
import math
import random
import pygame
from pygame.locals import *
import sys
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()
pygame.init()
W = 700
H = 400
updater = pygame.time.Clock()
display = pygame.display.set_mode((700, 400))
pygame.display.set_caption("Skating_Game")
x = y = 0
surface = pygame.image.load("man2.png")
pygame.display.set_icon(surface)
class player:
def __init__(self, velocity, maxJumpRange):
self.velocity = velocity
self.maxJumpRange = maxJumpRange
def setLocation(self, x, y):
self.x = x
self.y = y
self.xVelocity = 0
self.jumping = False
self.jumpCounter = 0
self.falling = True
def keys(self):
k = pygame.key.get_pressed()
if k[K_LEFT]:
self.xVelocity = -self.velocity
elif k[K_RIGHT]:
self.xVelocity = self.velocity
else:
self.xVelocity = 0
if k[K_SPACE] and not self.jumping and not self.falling:
self.jumping = True
self.jumpCounter = 0
def move(self):
self.x += self.xVelocity
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 - 60 and self.y + self.velocity >= H - 60:
self.y = H - 60
self.falling = False
else:
self.y += self.velocity
def draw(self):
display = pygame.display.get_surface()
character = pygame.image.load("man3.png").convert_alpha()
display.blit(character, (self.x, self.y - 100))
#pygame.draw.circle(display, (255, 255, 255), (self.x, self.y - 25), 25, 0)
def do(self):
self.keys()
self.move()
self.draw()
P = player(3, 50)
P.setLocation(350, 0)
BLACK = ( 0, 0, 0)
g=0
font = pygame.font.SysFont("Plump", 30)
obstacle = pygame.image.load("obstacle.png").convert_alpha()
background = pygame.image.load("Road.png").convert()
x = 0
while True:
events()
rel_x = x % background.get_rect().width
display.blit(background, (rel_x - background.get_rect().width,0))
if rel_x < 700:
display.blit(background, (rel_x, 0))
x -= 1
g += 0.01
pygame.draw.rect(display, (255,255,255,128), [rel_x, 275, 150, 50])
display.blit(obstacle, (rel_x, 250))
text = font.render("Score: "+str(int(g)), True, (255, 255, 255))
display.blit(text, (0,0))
P.do()
if P.rect.collidepoint(self.x,self.y):
pygame.quit()
pygame.display.update()
updater.tick(200)
So if the player collides with the obstacle image the game should stop. How do i do this? I have made a class for the player and the obstacle is just an image which is constantly moving.
I was thinking maybe I could track the x and y coordinate of the player and obstacle and when their radius overlaps the game could stop.
Here's a working (simplified) version of your program with some comments. You have to create rects for the obstacle and the player and then check if the rects collide with the help of the colliderect method.
import sys
import pygame
from pygame.locals import *
pygame.init()
W = 700
H = 400
updater = pygame.time.Clock()
display = pygame.display.set_mode((700, 400))
PLAYER_IMAGE = pygame.Surface((30, 50))
PLAYER_IMAGE.fill(pygame.Color('dodgerblue1'))
class Player:
def __init__(self, x, y, velocity, maxJumpRange):
self.velocity = velocity
self.maxJumpRange = maxJumpRange
self.image = PLAYER_IMAGE # Give the player an image.
# Create a rect with the size of the PLAYER_IMAGE and
# pass the x, y coords as the topleft argument.
self.rect = self.image.get_rect(topleft=(x, y))
self.x = x
self.y = y
self.xVelocity = 0
self.jumping = False
self.jumpCounter = 0
self.falling = True
def keys(self):
k = pygame.key.get_pressed()
if k[K_LEFT]:
self.xVelocity = -self.velocity
elif k[K_RIGHT]:
self.xVelocity = self.velocity
else:
self.xVelocity = 0
if k[K_SPACE] and not self.jumping and not self.falling:
self.jumping = True
self.jumpCounter = 0
def move(self):
self.x += self.xVelocity
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 - 160: # Simplified a little.
self.y = H - 160
self.falling = False
else:
self.y += self.velocity
# Update the position of the rect, because it's
# used for the collision detection.
self.rect.topleft = self.x, self.y
def draw(self, display):
# Just draw the image here.
display.blit(self.image, (self.x, self.y))
def do(self):
self.keys()
self.move()
player = Player(350, 0, 3, 50)
obstacle = pygame.Surface((150, 50))
obstacle.fill(pygame.Color('sienna1'))
# Create a rect with the size of the obstacle image.
obstacle_rect = obstacle.get_rect()
g = 0
x = 0
FPS = 60 # Cap the frame rate at 60 or 30 fps. 300 is crazy.
while True:
for event in pygame.event.get():
if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):
pygame.quit()
sys.exit()
# --- Update the game ---
player.do()
rel_x = x % display.get_width()
x -= 7
g += 0.01
obstacle_rect.topleft = rel_x, 250 # Update the position of the rect.
# --- Draw everything ---
display.fill((30, 30, 30))
display.blit(obstacle, (rel_x, 250))
if g > 30:
display.blit(obstacle, (rel_x+350, 250))
# Check if the obstacle rect and the player's rect collide.
if obstacle_rect.colliderect(player.rect):
print("Game over!") # And call pygame.quit and sys.exit if you want.
# Draw the image/surface of the player onto the screen.
player.draw(display)
# Draw the actual rects of the objects (for debugging).
pygame.draw.rect(display, (200, 200, 0), player.rect, 2)
pygame.draw.rect(display, (200, 200, 0), obstacle_rect, 2)
pygame.display.update()
updater.tick(FPS)
Pygame rectangles include a collidepoint and colliderect method that allows you to check to see if something intersects with a rectangle. So you could have rectangles drawn beneath the obstacle and check to see if the player's coordinates intersect with the rectangle. Like this:
if self.rect.collidepoint(self.x,self.y):
pygame.quit()
So I have been searching for a long time online to try and find out how to get my two sprite classes in pygame to collide. I am trying to make a basic game where the player has to dodge the squares. I would like some code for when the player hits one of the squares gameOver is true. Here's the code the player.
class Player(pygame.sprite.Sprite):
def __init__(self, x, y, image):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load('Tri.png')
self.image = pygame.transform.scale (self.image, (int(width/16), int(width/15)))
self.rect = self.image.get_rect()
self.width, self.height = self.image.get_size()
self.rect.x = x
self.rect.y = y
def update(self):
mx, my = pygame.mouse.get_pos()
self.rect.x = mx - self.width/2
self.rect.y = (height * 0.8)
if self.rect.x <= 0 - self.width/2 + 10:
self.rect.x += 10
if self.rect.x + self.width >= width:
self.rect.x = width - self.width
def draw(self, screen):
if bgColour == black:
self.image = pygame.image.load('Tri2.png')
self.image = pygame.transform.scale (self.image, (int(width/16), int(width/15)))
else:
self.image = pygame.image.load('Tri.png')
self.image = pygame.transform.scale (self.image, (int(width/16), int(width/15)))
self.width, self.height = self.image.get_size()
gameDisplay.blit(self.image, self.rect)
Here's the code for the squares
class Square(pygame.sprite.Sprite):
def __init__(self, box_x, box_y, box_width, box_height,colour, box_speed, box_border, BC):
self.box_x = box_x
self.box_y = box_y
self.box_width = box_width
self.box_height = box_height
self.colour = colour
self.box_speed = box_speed
self.box_border = box_border
self.BC = BC
border = pygame.draw.rect(gameDisplay, self.BC, [self.box_x - self.box_border/2, self.box_y - self.box_border/2, self.box_width + self.box_border, self.box_height + self.box_border])
box = pygame.draw.rect(gameDisplay, self.colour, [self.box_x, self.box_y, self.box_width, self.box_height])
def Fall(self):
if self.box_y < height:
self.box_y += box_speed
elif self.box_y > height + 100:
del square[0]
border = pygame.draw.rect(gameDisplay, self.BC, [self.box_x - self.box_border/2, self.box_y - self.box_border/2, self.box_width + self.box_border, self.box_height + self.box_border])
box = pygame.draw.rect(gameDisplay, self.colour, [self.box_x, self.box_y, self.box_width, self.box_height])
And the main game loop. Sorry for the messy code and probably redundant variables but I'm still learning :)
def game_loop():
mx, my = pygame.mouse.get_pos()
x = mx
y = (height * 0.8)
player = Player(x, y, 'Tri.png')
box_width = int(width/15)
if round(box_width/5) % 10 == 0:
box_border = round(box_width/5)
else:
box_border = round(box_width/5 + 1)
box_x = random.randrange(0, width)
box_y = 0 - box_width
min_gap = box_width/4
global box_speed
box_col = False
box_start = random.randrange(0, width)
delay = 0
global square
square = []
move_speed = 10
#level variables
box_speed = 6
max_gap = box_width/2
score = 0
bgColourList = [white, black, white, white]
global bgColour
bgColour = bgColourList[0]
Blist = [red, green, black, pink, white]
BC = Blist[0]
Clist = [red, black, black, pink, white]
box_colour = red
text_colour = black
z = 60
level = 0
delayBG = 0
levelChange = 400
gameExit = False
while not gameExit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameExit = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
gameExit = True
gameDisplay.fill(bgColour)
#blitting the player
player.update()
player.draw(gameDisplay)
#sets delay for level change
if score % levelChange == 0:
delayBG = 120
z = 120
if delayBG == 0:
bgColour = bgColourList[level]
BC = Blist[level]
box_colour = Clist[level]
if delay == 0:
score += 1
delay += 3
if delayBG == 0:
level += 1
box_speed += 1
max_gap -= 1
#creating a new square
if z == 0:
new = random.randint(0, width)
square.append(Square(new, box_y, box_width, box_width , box_colour, box_speed, box_border, BC))
z = random.randint(int(min_gap), int(max_gap))
last = new
lasty = box_y
#calling the Square.fall() function
for i in square:
i.Fall()
"""tris.remove(i)
i.checkCollision(tris)
tris.add(i)"""
pygame.draw.rect(gameDisplay, bgColour, [0,0, width, int(height/23)])
message_to_screen(str(score), text_colour, -height/2 + 15, 0)
delayBG -= 1
z -= 1
delay -= 1
pygame.display.update()
clock.tick(FPS)
game_loop()
pygame.quit()
quit()
Thank you in advance!
Create a group to hold all your Square objects:
square_group = pygame.sprite.Group()
Every time you create a Square object, add it to the group:
steven = Square(new, box_y, box_width, box_width , box_colour, box_speed, box_border, BC)
square_group.add(steven)
Then you can use spritecollide to check for collisions and act accordingly.
collisions = pygame.sprite.spritecollide(player, square_group, False)
if collisions:
gameExit = True