This question already has an answer here:
How do I get the snake to grow and chain the movement of the snake's body?
(1 answer)
Closed 2 years ago.
I am remaking snake game. And have a moving function and don't know where to call it. The snake is the green rect
the function is just before the while loop.
it is to make other segments of the snake move into the pos of the last segment.
here is the code so far:
import pygame, sys, random
from pygame.locals import *
pygame.init()
movement_x = movement_y = 0
RED = (240, 0, 0)
GREEN = (0, 255, 0)
ran = [0,25,50,75,100,125,150,175,200,225,250,275,300,325,350,375,400,425,450,475]
ax = 0
ay = 0
x = 0
y = 0
sa = 0
sizex = 500
sizey = 500
tilesize = 25
screen = pygame.display.set_mode((sizex,sizey))
pygame.display.set_caption('Snake')
pygame.display.set_icon(pygame.image.load('images/tile.png'))
tile = pygame.image.load('images/tile.png')
tile = pygame.transform.scale(tile, (tilesize, tilesize))
x2 = 0
pag = 0
clock = pygame.time.Clock()
sx = 0
sy = 0
vel_x = 0
vel_y = 0
ap = True
snake_parts = [] # /N/ Pygame rects
def slither( new_head_coord ):
# Move each body part to the location of the previous part
# So we iterate over the tail-parts in reverse
for i in range( len( snake_parts )-1, 0, -1 ):
x, y = snake_parts[i-1].centerx, snake_parts[i-1].centery
snake_parts[i].center = ( x, y )
# Move the head
snake_parts[0].centre = new_head_coord
while True:
sx = x
sy = y
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
for row in range(sizex):
for column in range(sizey):
screen.blit(tile,(column*tilesize, row*tilesize,tilesize,tilesize))
for event in pygame.event.get():
if event.type == KEYDOWN:
if event.key == K_UP:
vel_y = -25
vel_x = 0
elif event.key == K_DOWN:
vel_y = 25
vel_x = 0
elif event.key == K_LEFT:
vel_x = - 25
vel_y = 0
elif event.key == K_RIGHT:
vel_x= 25
vel_y = 0
elif event.key == K_y:
pag = 1
elif event.key == K_n:
pag = 2
inBounds = pygame.Rect(0, 0, sizex, sizey).collidepoint(x+vel_x, y+vel_y)
if inBounds:
y += vel_y
x += vel_x
else:
basicFont = pygame.font.SysFont(None, 48)
text = basicFont.render('Game Over! Play again? y/n', True, GREEN, RED)
textRect = text.get_rect()
textRect.centerx = screen.get_rect().centerx
textRect.centery = screen.get_rect().centery
pygame.draw.rect(screen, RED, (textRect.left - 20, textRect.top - 20, textRect.width + 40, textRect.height + 40))
screen.blit(text, textRect)
ay = -25
ax = -25
x = -25
y = -25
if pag == 1:
pag = 0
inBounds = True
x = 0
y = 0
vel_x = 0
vel_y = 0
ax = random.choice(ran)
ay = random.choice(ran)
pygame.draw.rect(screen, RED, pygame.Rect(ax,ay,tilesize,tilesize))
if pag == 2:
pygame.quit()
sys.exit()
if ap:
pygame.draw.rect(screen, RED, pygame.Rect(ax,ay,tilesize,tilesize))
if x == ax and y == ay:
pygame.draw.rect(screen, RED, pygame.Rect(ax,ay,tilesize,tilesize))
ax = random.choice(ran)
ay = random.choice(ran)
sa += 1
pygame.draw.rect(screen, GREEN, pygame.Rect(x,y,tilesize,tilesize))
pygame.display.update()
clock.tick(100)
I am not quite sure on how to use functions yet as I have only been learning python for a few weeks.
Add a new function which draws the snake:
def drawSnake():
for p in snake_parts:
screen.blit(shake, p.topleft)
Of course you can draw an image, instead of the recatangl. snake is an image of type pygame.Surface:
def drawSnake():
for p in snake_parts:
pygame.draw.rect(screen, RED, p)
Add the head to the list snake_parts before the main loop (before while True:):
snake_parts.append(pygame.Rect(x,y,tilesize,tilesize))
ax, ay = random.choice(ran), random.choice(ran)
Use drawSnake to draw the snake and update the positions of the parts right before:
slither( (x, y) )
if ap:
pygame.draw.rect(screen, RED, pygame.Rect(ax,ay,tilesize,tilesize))
if x == ax and y == ay:
pygame.draw.rect(screen, RED, pygame.Rect(ax,ay,tilesize,tilesize))
ax, ay = random.choice(ran), random.choice(ran)
sa += 1
snake_parts.append(pygame.Rect(x, y, tilesize, tilesize))
drawSnake()
pygame.display.update()
There is a typo in slither. It has to be snake_parts[0].center rather than snake_parts[0].centre.
But anyway, in your case the origin of the pars of the snake is topleft, rather than center. Change the function slither:
def slither( new_head_coord ):
for i in range( len(snake_parts)-1, 0, -1 ):
snake_parts[i] = snake_parts[i-1].copy()
snake_parts[0].topleft = new_head_coord
Do only 1 event loop in the main loop:
e.g.
run = True
while run:
sx, sy = x, y
for row in range(sizex):
for column in range(sizey):
screen.blit(tile,(column*tilesize, row*tilesize,tilesize,tilesize))
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
run = False
if event.type == KEYDOWN:
if event.key == K_UP:
vel_y = -25
vel_x = 0
# [...]
Demo
import pygame, sys, random
from pygame.locals import *
pygame.init()
movement_x = movement_y = 0
RED = (240, 0, 0)
GREEN = (0, 255, 0)
ran = [0,25,50,75,100,125,150,175,200,225,250,275,300,325,350,375,400,425,450,475]
sizex, sizey = 500, 500
tilesize = 25
screen = pygame.display.set_mode((sizex,sizey))
pygame.display.set_caption('Snake')
tile = pygame.Surface((tilesize, tilesize))
tile.fill((0, 0, 64))
tile = pygame.transform.scale(tile, (tilesize, tilesize))
x2 = 0
pag = 0
clock = pygame.time.Clock()
sx, sy = 0, 0
vel_x, vel_y = 0, 0
x, y = 0, 0
sa = 0
ap = True
snake_parts = [] # /N/ Pygame rects
def slither( new_head_coord ):
for i in range( len(snake_parts)-1, 0, -1 ):
snake_parts[i] = snake_parts[i-1].copy()
snake_parts[0].topleft = new_head_coord
def drawSnake():
for p in snake_parts:
pygame.draw.rect(screen, GREEN, p)
snake_parts.append(pygame.Rect(x,y,tilesize,tilesize))
ax, ay = random.choice(ran), random.choice(ran)
run = True
while run:
sx, sy = x, y
for row in range(sizex):
for column in range(sizey):
screen.blit(tile,(column*tilesize, row*tilesize,tilesize,tilesize))
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
run = False
if event.type == KEYDOWN:
if event.key == K_UP:
vel_x, vel_y = 0, -25
elif event.key == K_DOWN:
vel_x, vel_y = 0, 25
elif event.key == K_LEFT:
vel_x, vel_y = -25, 0
elif event.key == K_RIGHT:
vel_x, vel_y = 25, 0
elif event.key == K_y:
pag = 1
elif event.key == K_n:
pag = 2
inBounds = pygame.Rect(0, 0, sizex, sizey).collidepoint(x+vel_x, y+vel_y)
if inBounds:
y += vel_y
x += vel_x
else:
basicFont = pygame.font.SysFont(None, 48)
text = basicFont.render('Game Over! Play again? y/n', True, GREEN, RED)
textRect = text.get_rect()
textRect.centerx = screen.get_rect().centerx
textRect.centery = screen.get_rect().centery
pygame.draw.rect(screen, RED, (textRect.left - 20, textRect.top - 20, textRect.width + 40, textRect.height + 40))
screen.blit(text, textRect)
ax, ay = -25, -25
x, y = -25, -25
if pag == 1:
pag = 0
inBounds = True
x, y = 0, 0
vel_x, vel_y = 0, 0
ax, ay = random.choice(ran), random.choice(ran)
pygame.draw.rect(screen, RED, pygame.Rect(ax,ay,tilesize,tilesize))
if pag == 2:
pygame.quit()
sys.exit()
slither( (x, y) )
if ap:
pygame.draw.rect(screen, RED, pygame.Rect(ax,ay,tilesize,tilesize))
if x == ax and y == ay:
pygame.draw.rect(screen, RED, pygame.Rect(ax,ay,tilesize,tilesize))
ax, ay = random.choice(ran), random.choice(ran)
sa += 1
snake_parts.append(pygame.Rect(x, y, tilesize, tilesize))
drawSnake()
pygame.display.update()
clock.tick(100)
Related
This question already has answers here:
How can i controll collision from sprites?
(1 answer)
Pygame "pop up" text
(2 answers)
Closed 4 months ago.
Ive been making a frogger game on pygame and im confused on how to make the game display a message only when the frog hits the drawing (car, which has the variable "thing"). Right now it displays the message when it collides with the drawing however it also displays this message if the frog is above the drawing.
i tried making it so that it takes Y and X into account in order to determine if it has collided or not however this has not worked
here is my code:
import pygame
import random
pygame.init()
display_width = 800
display_height = 600
black = (0,0,0)
white = (255,255,255)
red = (200,0,0)
green = (0,200,0)
gameDisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption('lazy frog')
clock = pygame.time.Clock()
carimg = pygame.image.load('car.png')
carimg = pygame.transform.scale(carimg, (60, 60))
frogimg = pygame.image.load('frog.jpg')
frogimg = pygame.transform.scale(frogimg, (30, 30))
background = pygame.image.load('frogbackground.png').convert()
background = pygame.transform.scale(background,(800,600))
gameDisplay.fill(white)
pygame.display.update()
clock.tick(60)
def things(thingx, thingy, thingw, thingh, color):
pygame.draw.rect(gameDisplay, color, [thingx, thingy, thingw, thingh])
def things2(thing2x, thing2y, thing2w, thing2h, color):
pygame.draw.rect(gameDisplay, color, [thing2x, thing2y, thing2w, thing2h])
def things3(thing3x, thing3y, thing3w, thing3h, color):
pygame.draw.rect(gameDisplay, color, [thing3x, thing3y, thing3w, thing3h])
def things4(thing4x, thing4y, thing4w, thing4h, color):
pygame.draw.rect(gameDisplay, color, [thing4x, thing4y, thing4w, thing4h])
def things5(thing5x, thing5y, thing5w, thing5h, color):
pygame.draw.rect(gameDisplay, color, [thing5x, thing5y, thing5w, thing5h])
def things6(thing6x, thing6y, thing6w, thing6h, color):
pygame.draw.rect(gameDisplay, color, [thing6x, thing6y, thing6w, thing6h])
def things7(thing7x, thing7y, thing7w, thing7h, color):
pygame.draw.rect(gameDisplay, color, [thing7x, thing7y, thing7w, thing7h])
def things8(thing8x, thing8y, thing8w, thing8h, color):
pygame.draw.rect(gameDisplay, color, [thing8x, thing8y, thing8w, thing8h])
def things9(thing9x, thing9y, thing9w, thing9h, color):
pygame.draw.rect(gameDisplay, color, [thing9x, thing9y, thing9w, thing9h])
def things10(thing10x, thing10y, thing10w, thing10h, color):
pygame.draw.rect(gameDisplay, color, [thing10x, thing10y, thing10w, thing10h])
def frog(x,y):
gameDisplay.blit(frogimg, (x,y))
def died():
message_display("you died")
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))
gameDisplay.blit(TextSurf, TextRect)
pygame.display.update()
def text_objects(text, font):
textSurface = font.render(text, True, black)
return textSurface, textSurface.get_rect()
frogwidth = 15
x = (display_width * 0.45)
y = (display_height * 0.8)
xchange = 0
ychange = 0
thing_startx = 5
thing_starty = 95
thing_speed = 6
thing_width = 25
thing_height = 25
thing_start2x = 5
thing_start2y = 135
thing_speed2 = 4
thing_width2 = 25
thing_height2 = 25
thing_start3x = 5
thing_start3y = 215
thing_speed3 = 6
thing_width3 = 25
thing_height3 = 25
thing_start4x = 5
thing_start4y = 255
thing_speed4 = 9
thing_width4 = 25
thing_height4 = 25
thing_start5x = 5
thing_start5y = 350
thing_speed5 = 7
thing_width5 = 25
thing_height5 = 25
thing_start6x = 5
thing_start6y = 390
thing_speed6 = 5
thing_width6 = 25
thing_height6 = 25
thing_start7x = 5
thing_start7y = 430
thing_speed7 = 7
thing_width7 = 25
thing_height7 = 25
thing_start8x = 5
thing_start8y = 470
thing_speed8 = 4
thing_width8 = 25
thing_height8 = 25
thing_start9x = 5
thing_start9y = 510
thing_speed9 = 6
thing_width9 = 25
thing_height9 = 25
thing_start10x = 5
thing_start10y = 95
thing_speed10 = 4
thing_width10 = 25
thing_height10 = 25
crashed = False
while not crashed:
for event in pygame.event.get():
if event.type == pygame.quit:
crashed = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
xchange = -5
ychange = 0
elif event.key == pygame.K_RIGHT:
xchange = 5
ychange = 0
elif event.key == pygame.K_UP:
ychange = -5
xchange = 0
elif event.key == pygame.K_DOWN:
ychange = 5
xchange = 0
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT or event.key == pygame.K_UP or event.key == pygame.K_DOWN:
xchange = 0
x += xchange
y += ychange
gameDisplay.blit(background,(0,0))
things(thing_startx, thing_starty, thing_width, thing_height, red)
thing_startx += thing_speed
things2(thing_start2x, thing_start2y, thing_width2, thing_height2, red)
thing_start2x += thing_speed2
things3(thing_start3x, thing_start3y, thing_width3, thing_height3, red)
thing_start3x += thing_speed3
things4(thing_start4x, thing_start4y, thing_width4, thing_height4, red)
thing_start4x += thing_speed4
things5(thing_start5x, thing_start5y, thing_width5, thing_height5, red)
thing_start5x += thing_speed5
things6(thing_start6x, thing_start6y, thing_width6, thing_height6, red)
thing_start6x += thing_speed6
things7(thing_start7x, thing_start7y, thing_width7, thing_height7, red)
thing_start7x += thing_speed7
things8(thing_start8x, thing_start8y, thing_width8, thing_height8, red)
thing_start8x += thing_speed8
things9(thing_start9x, thing_start9y, thing_width9, thing_height9, red)
thing_start9x += thing_speed9
things10(thing_start10x, thing_start10y, thing_width10, thing_height10,red)
thing_start10x += thing_speed10
frog(x,y)
if x > display_width - frogwidth or x < 0:
died()
if thing_startx > display_height:
thing_starty = 95
thing_startx = 5
if thing_start2x > display_height:
thing_start2y = 135
thing_start2x = 5
if thing_start3x > display_height:
thing_start3y = 215
thing_start3x = 5
if thing_start4x > display_height:
thing_start4y = 255
thing_start4x = 5
if thing_start5x > display_height:
thing_start5y = 350
thing_start5x = 5
if thing_start6x > display_height:
thing_start6y = 390
thing_start6x = 5
if thing_start7x > display_height:
thing_start7y = 430
thing_start7x = 5
if thing_start8x > display_height:
thing_start8y = 470
thing_start8x = 5
if thing_start9x > display_height:
thing_start9y = 510
thing_start9x = 5
if thing_start10x > display_height:
thing_start10y = 95
thing_start10x = 4
if y < thing_start10y+thing_height10 and x > thing_start10y+thing_height10:
print('y crossover')
if x > thing_start10x and x < thing_start10x + thing_width10 or x+frogwidth > thing_start10x and x + frogwidth < thing_start10x+thing_width10:
print('x crossover')
died()
pygame.display.update()
clock.tick(60)
pygame.quit()
quit()
this specifically is the piece of code that i need help with:
if y < thing_start10y+thing_height10 and x > thing_start10y+thing_height10:
print('y crossover')
if x > thing_start10x and x < thing_start10x + thing_width10 or x+frogwidth > thing_start10x and x + frogwidth < thing_start10x+thing_width10:
print('x crossover')
died()
So I have this code that's my main game:
def game():
running = True
import pygame, sys
import random
import math as m
mainClock = pygame.time.Clock()
pygame.init()
pygame.font.init
pygame.display.set_caption('Ping Pong')
SCREEN = width, height = 900,600
white = (255, 255, 255)
green = (0, 255, 0)
blue = (0, 0, 128)
black = (0,0,0)
speed = [4,4]
font = pygame.font.Font('freesansbold.ttf', 32)
score = 0
score = str(score)
font.size(score)
font.set_bold(True)
text = font.render(score, True, white)
textRect = text.get_rect()
textRect.center = ((width/2 - width / 20), (height/60 + height/20))
screen = pygame.display.set_mode(SCREEN, 0,32)
height1 = height/4
score = int(score)
ball = pygame.Rect(width/2, height/2, 50,50)
player = pygame.Rect(0,(height/2),25,height1)
player_1 = pygame.Rect(width - 25,(height/2),25,height1)
font1 = pygame.font.Font('freesansbold.ttf', 32)
score1 = 0
score1 = str(score)
font1.size(score1)
font1.set_bold(True)
text1 = font1.render(score1, True, white)
score1 = int(score1)
textRect1 = text1.get_rect()
textRect1.center = ((width/2 + width / 15), (height/60 + height/20))
up = False
down = False
up_1 = False
down_1 = False
RED = (255,0,0)
particles = []
while running:
color = (192,192,192)
# clear display #
screen.fill((0,0,0))
screen.blit(text, textRect)
screen.blit(text1, textRect1)
bx = ball.centerx
by = ball.centery
particles.append([[bx, by],[random.randint(0,20) / 10 - 1, -1], random.randint(4,6)])
for particle in particles:
particle[0][0] += particle[1][0]
particle[0][1] += particle[1][1]
particle[2] -= 0.1
particle[1][1] += 0.1
pygame.draw.circle(screen, color, [int(particle[0][0]), int(particle[0][1])], int(particle[2]))
if particle[2] <= 0:
particles.remove(particle)
if up == True:
player.y -= 5
if down == True:
player.y += 5
if up_1 == True:
player_1.y -= 5
if down_1 == True:
player_1.y += 5
if player.top < 0 :
player.y = 0
if player.bottom > height:
player.bottom = height
if player_1.top < 0 :
player_1.y = 0
if player_1.bottom > height :
player_1.bottom = height
for i in range(-90,(height + 130), 120):
rectangle = pygame.Rect((width/2), i, 13, 60)
pygame.draw.rect(screen, (255,255,255), rectangle)
pygame.draw.rect(screen,(191, 224, 255),player)
pygame.draw.rect(screen,(191, 224, 255),player_1)
color = (192,192,192)
r = random.randint(0, 255)
g = random.randint(0, 255)
b = random.randint(0, 255)
pygame.draw.rect(screen,color,ball, 3)
import time
ball.x += speed[0]
ball.y += speed[1]
if ball.top < 0 or ball.bottom > height:
speed[1] = -speed[1]
r = random.randint(0,255)
g = random.randint(0,255)
b = random.randint(0,255)
pygame.draw.rect(screen,(r,b,g),ball, 3)
pygame.draw.circle(screen, (r,b,g), [int(particle[0][0]), int(particle[0][1])], int(particle[2]))
dab = random.randint(0,1)
if ball.left < 0 :
font = pygame.font.Font('freesansbold.ttf', 32)
score1 = int(score1)
score1 += 1
score1 = str(score1)
font.set_bold(True)
text1 = font.render(score1, True, white)
textRect1 = text.get_rect()
textRect1.center = ((width/2 + width / 15), (height/60 + height/20))
screen.blit(text1, textRect1)
ball.x = width/2
ball.y = height/2
if dab == 1:
ball.x += -speed[0]
ball.y += -speed[1]
elif dab == 0:
ball.x += speed[0]
ball.y += speed[1]
if ball.right > width:
font = pygame.font.Font('freesansbold.ttf', 32)
score = int(score)
score += 1
score = str(score)
font.set_bold(True)
text = font.render(score, True, white)
textRect = text.get_rect()
textRect.center = ((width/2 - width / 20), (height/60 + height/20))
screen.blit(text, textRect)
ball.x = width/2
ball.y = height/2
if dab == 1:
ball.x += -speed[0]
ball.y += -speed[1]
elif dab == 0:
ball.x += speed[0]
ball.y += speed[1]
# event handling #
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == KEYDOWN:
if event.key == K_s:
down = True
if event.key == K_w:
up = True
if event.key == K_UP:
up_1 =True
if event.key == K_ESCAPE:
running = False
if event.key == K_DOWN:
down_1 = True
if event.type == KEYUP:
if event.key == K_s:
down = False
if event.key == K_w:
up = False
if event.key == K_UP:
up_1 = False
if event.key == K_DOWN:
down_1 = False
if ball.colliderect(player_1):
dab = random.randint(0,1)
if dab == 1:
speed[1] = -speed[1]
speed[0] = -speed[0]
r = random.randint(0,255)
g = random.randint(0,255)
b = random.randint(0,255)
pygame.draw.rect(screen,(r,b,g),ball, 3)
if ball.colliderect(player):
speed[0] = -speed[0]
speed[0] = random.randint(4,6)
r = random.randint(0,255)
g = random.randint(0,255)
b = random.randint(0,255)
pygame.draw.rect(screen,(r,b,g),ball, 3)
# update display #
pygame.display.update()
mainClock.tick(60)
and I have a menu screen that displays some options. Only button_1 works.:
def main_menu():
while True:
white = (255,255,255)
font = pygame.font.Font('freesansbold.ttf', 32)
font.set_bold(True)
screen.fill((0,0,0))
button_1 = pygame.Rect(width/2, (height/2), width/2, 50)
button_1.centerx = width/2
button_2 = pygame.Rect(width/2, height/1.5, width/2, 50)
button_2.centerx = width/2
pygame.draw.rect(screen, (255, 0, 0), button_1)
pygame.draw.rect(screen, (255, 0, 0), button_2)
#draw_text('Start!', font, (255, 255, 255), screen, button_1.centerx, button_1.centery)
font = pygame.font.Font('freesansbold.ttf', 32)
font.set_bold(True)
text1 = font.render('Start!', True, white)
textRect1 = text1.get_rect()
textRect1.center = (button_1.centerx, button_1.centery)
screen.blit(text1, textRect1)
mx, my = pygame.mouse.get_pos()
if button_1.collidepoint((mx, my)):
if click:
game()
if button_2.collidepoint((mx, my)):
if click:
options()
click = False
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
pygame.quit()
sys.exit()
if event.type == MOUSEBUTTONDOWN:
if event.button == 1:
click = True
pygame.display.update()
clock.tick(60)
How do I make it so that after button_1 is pressed, there's a 3,2,1 countdown on the screen, and then the game starts?
In order to do the countdown, you import the time module:
import time
...then you need a for loop, with a step -1, counting down from 3 to 1. Inside the for loop, print the numbers and sleep one second, using the time module:
for a in range(3,0,-1):
print(a)
time.sleep(1)
After this for loop, you put the rest of your code.
I am currently making a game where you run around as a bear, collect fish, and get points. However, when the bear runs into the fish, it does not pick it up as the bear has run into the fish.
I have tried having the function running in some of the loops where the fish has been made and even making it a function but it does not seem to work.
global screen, grasspic, bearImg, fishpic, screen_width, screen_height, score_number, bearRect
import random
import pygame
import sys
import time
import math
pygame.init()
screen_width = 640
screen_height = 480
sw2 = screen_width/2
sh2 = screen_height/2
bearImg = pygame.image.load('bear.png')
bearImg = pygame.transform.scale(bearImg, (150,150))
green = (24, 255, 0)
bearImg_width = 150
def text_objects(text, font):
textSurface = font.render(text, True, (0,0,0))
return textSurface, textSurface.get_rect()
def message_display(text):
clocktxt = pygame.font.Font('freesans.ttf', 20)
TextSurf, TextRect = text_objects(text, clocktxt)
TextRect.center = (55, 15)
screen.blit(TextSurf, TextRect)
pygame.display.update()
white = (255, 255, 255)
black = (0,0,0)
#NOTE: DOWNLOAD FISH, BEAR, AND GRASS PICTURES|| IT WILL NOT WORK WITHOUT IT
grasspic = []
for i in range(1, 5):
grasspic.append(pygame.image.load('grass%s.png' % i))
fishpic = []
for i in range(1, 3):
fishpic.append(pygame.image.load('fish%s.png' % i))
fishpic[0] = pygame.transform.scale(fishpic[0], (50,50))
fishpic[1] = pygame.transform.scale(fishpic[1], (50,50))
screen = pygame.display.set_mode((screen_width,screen_height))
pygame.display.set_caption('Hungry Boi')
clock = pygame.time.Clock()
camerax = 0
cameray = 0
def getRandomOffCameraPos(camerax, cameray, objWidth, objHeight):
cameraRect = pygame.Rect(camerax, cameray, screen_width, screen_height)
while True:
x = random.randint(camerax - screen_width, camerax + (2*screen_width))
y = random.randint(cameray - screen_height, cameray + (2*screen_height))
objRect = pygame.Rect(x, y, objWidth, objHeight)
if not objRect.colliderect(cameraRect):
return x, y
def makeNewGrass(camerax, cameray):
gr = {}
gr['grassImage'] = random.randint(0, len(grasspic) - 1)
gr['width'] = 80
gr['height'] = 80
gr['x'], gr['y'] = getRandomOffCameraPos(camerax, cameray, gr['width'], gr['height'])
gr['rect'] = pygame.Rect((gr['x'], gr['y'], gr['width'], gr['height']))
return gr
def makeNewFish(camerax, cameray):
fi = {}
fi['fishImage'] = random.randint(0, len(fishpic) - 1)
fi['width'] = 150
fi['height'] = 150
fi['x'], fi['y'] = getRandomOffCameraPos(camerax, cameray, fi['width'], fi['height'])
fi['rect'] = pygame.Rect((fi['x'], fi['y'], fi['width'], fi['height']))
return fi
def bear(x,y):
screen.blit(bearImg,(x,y))
allgrass = []
def makegrass():
for i in range(15):
allgrass.append(makeNewGrass(camerax, cameray))
allgrass[i]['x'] = random.randint(0, screen_width)
allgrass[i]['y'] = random.randint(0, screen_height)
makegrass()
allfish = []
def makefish():
for i in range(2):
allfish.append(makeNewFish(camerax, cameray))
allfish[i]['x'] = random.randint(0, screen_width)
allfish[i]['y'] = random.randint(0, screen_height)
makefish()
def game_loop():
x = (screen_width * 0.4)
y = (screen_height * 0.4)
STARTINGX = (screen_width * 0.4)
STARTINGY = (screen_height * 0.4)
x_change = 0
y_change = 0
vel = 5
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_LEFT:
x_change -= vel
STARTINGX -= vel
elif event.key == pygame.K_RIGHT:
x_change += vel
STARTINGX += vel
elif event.key == pygame.K_UP:
y_change -= vel
STARTINGY -= vel
elif event.key == pygame.K_DOWN:
y_change += vel
STARTINGY += vel
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
x_change = 0
elif event.key == pygame.K_UP or event.key == pygame.K_DOWN:
y_change = 0
#print (event) #see events, basically a console, makes a mess
x += x_change
y += y_change
screen.fill(green)
bearRect = pygame.Rect((STARTINGX, STARTINGY, STARTINGX+150, STARTINGY+150))
for grass in allgrass:
gRect = pygame.Rect((grass['x'] - camerax,
grass['y'] - cameray,
grass['width'],
grass['height']))
screen.blit(grasspic[grass['grassImage']], gRect)
for fish in allfish:
fRect = pygame.Rect((fish['x'] - camerax,
fish['y'] - cameray,
fish['width'],
fish['height']))
screen.blit(fishpic[fish['fishImage']], fRect)
bear(x,y)
score_count()
if bearRect.colliderect(fRect):
makefish()
makegrass()
pygame.display.update()
clock.tick(30) #fps//may not be safe to run really fast
def score_count():
score_number = 0
message_display("Score is: " + str(score_number))
game_loop()
pygame.quit()
quit
Instead of getting a collision and have both the grass and fish images randomize on the screen again, the code will ignore the entire collision. Is there a way to fix it and have it know where the bear and the fish is correctly?
Thank you
Now it works correctly but I made so many changes that it is hard to describe it.
Code did't remove fishes and did't change score so it was hard to say if it checked collision. Now it removes fish (and add new in new place) and change score.
Code keeps position and size in Rect and use only one Rect for every item. I old code Bear had two rect - one to check collision and one to blit it.
In some functions I change names to show that they are very similar and it could be one function.
Every object has image and rect. When you read documentation for pygame.sprite.Sprite then you see that it also uses image and rect.
import random
import pygame
import sys
import time
import math
# --- constants --- (UPPER_CASE_NAMES)
GREEN = (24, 255, 0)
WHITE = (255, 255, 255)
BLACK = (0,0,0)
SCREEN_WIDTH = 640
SCREEN_HEIGHT = 480
SW2 = SCREEN_WIDTH/2
SH2 = SCREEN_HEIGHT/2
# --- functions ---
def text_objects(text, font):
surface = font.render(text, True, BLACK)
return surface, surface.get_rect()
def message_display(text):
surface, rect = text_objects(text, CLOCKTXT)
rect.center = (55, 15)
screen.blit(surface, rect)
#pygame.display.update() # use update() olny in one place
def getRandomOffCameraPos(camerax, cameray, objWidth, objHeight):
camera_rect = pygame.Rect(camerax, cameray, SCREEN_WIDTH, SCREEN_HEIGHT)
x1 = camerax - SCREEN_WIDTH
x2 = camerax + (2*SCREEN_WIDTH)
y1 = cameray - SCREEN_HEIGHT
y2 = cameray + (2*SCREEN_HEIGHT)
while True:
x = random.randint(x1, x2)
y = random.randint(y1, y2)
obj_rect = pygame.Rect(x, y, objWidth, objHeight)
if not obj_rect.colliderect(camera_rect):
return x, y
def makeNewGrass(camerax, cameray):
w, h = 80, 80
x, y = getRandomOffCameraPos(camerax, cameray, w, h)
images = grasspic
item = {
'image': random.choice(images),
'rect': pygame.Rect(x, y, w, h),
}
return item
def makeNewFish(camerax, cameray):
w, h = 50, 50
x, y = getRandomOffCameraPos(camerax, cameray, w, h)
images = fishpic
item = {
'image': random.choice(images),
'rect': pygame.Rect(x, y, w, h),
}
return item
def makegrass(number=15):
for i in range(number):
item = makeNewGrass(camerax, cameray)
item['rect'].x = random.randint(0, SCREEN_WIDTH-item['rect'].width)
item['rect'].y = random.randint(0, SCREEN_HEIGHT-item['rect'].height)
allgrass.append(item)
def makefish(number=2):
for i in range(number):
item = makeNewFish(camerax, cameray)
item['rect'].x = random.randint(0, SCREEN_WIDTH-item['rect'].width)
item['rect'].y = random.randint(0, SCREEN_HEIGHT-item['rect'].height)
allfish.append(item)
def score_draw(score):
message_display("Score is: " + str(score))
#--- main ---
pygame.init()
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption('Hungry Boi')
CLOCKTXT = pygame.font.Font('freesans.ttf', 20)
# ---
bear_img = pygame.image.load('bear.png').convert()
bear_img = pygame.transform.scale(bear_img, (150, 150)).convert()
bear_rect = bear_img.get_rect()
bear_rect.x = SCREEN_WIDTH * 0.4
bear_rect.y = SCREEN_HEIGHT * 0.4
bear_vel = 5
grasspic = []
for i in range(1, 5):
image = pygame.image.load('grass%s.png' % i).convert()
grasspic.append(image)
fishpic = []
for i in range(1, 3):
image = pygame.image.load('fish%s.png' % i).convert()
image = pygame.transform.scale(image, (50, 50)).convert()
fishpic.append(image)
# ---
allgrass = []
makegrass()
allfish = []
makefish()
x_change = 0
y_change = 0
camerax = 0
cameray = 0
score = 0
# --- mainloop ---
gameExit = False
clock = pygame.time.Clock()
while not gameExit:
# --- events ---
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameExit = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x_change -= bear_vel
elif event.key == pygame.K_RIGHT:
x_change += bear_vel
elif event.key == pygame.K_UP:
y_change -= bear_vel
elif event.key == pygame.K_DOWN:
y_change += bear_vel
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT:
x_change += bear_vel
elif event.key == pygame.K_RIGHT:
x_change -= bear_vel
elif event.key == pygame.K_UP:
y_change += bear_vel
elif event.key == pygame.K_DOWN:
y_change -= bear_vel
# --- updates ---
bear_rect.x += x_change
bear_rect.y += y_change
keep_fish = []
for fish in allfish:
if not bear_rect.colliderect(fish['rect']):
keep_fish.append(fish)
else:
makefish(1)
#makegrass()
score += 1
allfish = keep_fish
# --- draws ---
screen.fill(GREEN)
for grass in allgrass:
screen.blit(grass['image'], grass['rect'].move(camerax, cameray))
for fish in allfish:
screen.blit(fish['image'], fish['rect'].move(camerax, cameray))
screen.blit(bear_img, bear_rect.move(camerax, cameray))
score_draw(score)
pygame.display.update()
# --- FPS ---
clock.tick(30) #fps//may not be safe to run really fast
# --- end ---
pygame.quit()
my quit button is working in my pygame but only partly. it works once i have just run the game, but after i have been killed in game and the game_loop is reset, the quit button just resets the game loop when i press it and doesn't close the window. it's like it has changed it's function to the same as the function of when the player get's killed if that makes sense.
i am just going to show you my whole games code to make it easier. (btw my game is being changed currently so some things might be in the wrong place and stuff just don't worry about it).
import pygame
import time
import random
pygame.init()
pygame.font.init()
dis_width = 500
dis_height = 500
game_exit = False
hit = False
FPS = 150
record = 0
game_display = pygame.display.set_mode((dis_width, dis_height))
pygame.display.set_caption('RACRZ')
clock = pygame.time.Clock()
#COLOURS
black = (0, 0, 0)
white = (255, 255, 255)
red = (255, 0 ,0)
green = (0, 255, 0)
blue = (0, 0, 255)
sky_blue = (0, 136, 239)
#VEHICLE
bg = pygame.image.load('c:\\users\\riley\\pictures\\Saved Pictures\\spaceImg_bg.png')
carImg = pygame.image.load('c:\\users\\riley\\pictures\\Saved Pictures\\space invader1.png')
car_width = 32
car_height = 33
vel = 3
#projectile
enemyImg = pygame.image.load('c:\\users\\riley\\pictures\\saved pictures\\projectile1.png')
explosionImg = pygame.image.load('c:\\users\\riley\\pictures\\saved pictures\\explosion 1.png')
def car(x, y):
game_display.blit(carImg, (x, y))
def enemy(enemyx, enemyy):
game_display.blit(enemyImg, (enemyx, enemyy))
def enemy2(enemyx, enemyy):
game_display.blit(enemyImg, (enemyx, enemyy))
def enemy3(enemyx, enemyy):
game_display.blit(enemyImg, (enemyx, enemyy))
def enemy4(enemyx, enemyy):
game_display.blit(enemyImg, (enemyx, enemyy))
def enemy5(enemyx, enemyy):
game_display.blit(enemyImg, (enemyx, enemyy))
def enemy6(enemyx, enemyy):
game_display.blit(enemyImg, (enemyx, enemyy))
def explode(x, y):
game_display.blit(explosionImg, (x, y))
#TEXT
def textobjects(text, font):
textsurface = font.render(text, True, green)
return textsurface, textsurface.get_rect()
#RESTART MESSAGE
def message_display(text, colour, locationX, locationY):
largeText = pygame.font.Font('freesansbold.ttf', 50)
text = largeText.render('HIT', True, (colour))
game_display.blit(text, (locationX, locationY))
pygame.display.update()
time.sleep(2)
game_loop()
def collision(ex, ey, ew, eh, x, y, w, h):
if x > ex and x < ex + ew or x + w > ex and x + w < ex + ew:
if y > ey and y < ey + eh or y + h > ey and y + h < ey + eh:
print ('HIT')
hit = True
game_loop()
def score(rounds):
font = pygame.font.SysFont(None, 35)
text = font.render(f'ROUND {rounds}', True, green)
game_display.blit(text, (0,0))
#GAME LOOP
def game_loop():
#beggining car location
x = dis_width * 0.45
y = dis_height * 0.8
#movement variables
x_change = 0
y_change = 0
loop_count = 0
enemy_startx = random.uniform(0, dis_width)
enemy_starty = -1000
enemy2_startx = -1000
enemy2_starty = random.uniform(0, dis_height)
enemy3_startx = random.uniform(0, dis_width)
enemy3_starty = -24
enemy4_startx = random.uniform(0, dis_width)
enemy4_starty = 500
#goes from top side diagonaly to bottom left
enemy5_startx = random.uniform(0, dis_width)
enemy5_starty = -24
#goes from bottom side diagonaly to top right
enemy6_startx = random.uniform(0, dis_width)
enemy6_starty = 500
enemy_speed = 3
enemy_width = 24
enemy_height = 24
#game has not been quit
game_exit = False
#while the game is running this will happen
while not game_exit:
#quit button
for event in pygame.event.get():
#assingning keys to movement
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x_change -= vel
elif event.key == pygame.K_RIGHT:
x_change += vel
elif event.key == pygame.K_DOWN:
y_change += vel
elif event.key == pygame.K_UP:
y_change -= vel
elif event.type == pygame.K_ESCAPE:
print ('escape')
game_exit = True
if event.type == pygame.QUIT:
game_exit = True
#stops vehicle from moving after key press
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
x_change = 0
if event.key == pygame.K_UP or event.key == pygame.K_DOWN:
y_change = 0
#moves vehicle
y += y_change
x += x_change
#display colour
game_display.blit(bg, (0,0))
#spawns objects
if loop_count >= 10:
enemy3_startx += enemy_speed
enemy3_starty += enemy_speed
enemy3(enemy3_startx, enemy3_starty)
if loop_count >= 15:
enemy4_startx -= enemy_speed
enemy4_starty -= enemy_speed
enemy4(enemy4_startx, enemy4_starty)
if loop_count >= 20:
enemy5_startx -= enemy_speed
enemy5_starty += enemy_speed
enemy5(enemy5_startx, enemy5_starty)
if loop_count >= 25:
enemy6_startx += enemy_speed
enemy6_starty -= enemy_speed
enemy6(enemy6_startx, enemy6_starty)
car(x,y)
enemy(enemy_startx, enemy_starty)
enemy2(enemy2_startx, enemy2_starty)
score(loop_count)
enemy2_startx += enemy_speed
enemy_starty += enemy_speed
if hit == True:
game_loop = 0
#MAKES DISPLAY BOUNDARIES
#car boundaries
if x > dis_width - car_width:
x = 0
elif x < 0:
x = dis_width - car_width
elif y > dis_height - car_height:
y = 0
elif y < 0:
y = dis_height - car_height
#boundaries for enemy1
if enemy_starty > dis_height:
enemy_starty = 0 - enemy_height
enemy_startx = random.uniform(0, dis_width - enemy_width)
#loop_count will count the number of times enemy1 passes through the screen
loop_count = loop_count + 1
print(loop_count)
# ex, ey, ew, eh, x, y, w, h
collision(enemy_startx, enemy_starty, enemy_width, enemy_height, x, y, car_width, car_height)
collision(enemy2_startx, enemy2_starty, enemy_width, enemy_height, x, y, car_width, car_height)
collision(enemy3_startx, enemy3_starty, enemy_width, enemy_height, x, y, car_width, car_height)
collision(enemy4_startx, enemy4_starty, enemy_width, enemy_height, x, y, car_width, car_height)
collision(enemy5_startx, enemy5_starty, enemy_width, enemy_height, x, y, car_width, car_height)
collision(enemy6_startx, enemy6_starty, enemy_width, enemy_height, x, y, car_width, car_height)
#boundaries for enemy2
if enemy2_startx > dis_width:
enemy2_startx = 0 - enemy_width
enemy2_starty = random.uniform(0, dis_height - enemy_height)
#enemy3 boundaries
if enemy3_startx > dis_width:
enemy3_startx = random.uniform(0, dis_width)
enemy3_starty = -24
#enemy4 boundaries
if enemy4_startx < 0 - enemy_width:
enemy4_startx = random.uniform(0, dis_width)
enemy4_starty = 500
#enemy5 boundaries
if enemy5_startx < 0 - enemy_width:
enemy5_startx = random.uniform(0, dis_width)
enemy5_starty = -24
#enemy6 boundaries
if enemy6_startx > dis_width:
enemy6_startx = random.uniform(0, dis_width)
enemy6_starty = 500
#record checker/ set
global record
roundnum = loop_count
if roundnum > record:
record = roundnum
#updates screen after movements
pygame.display.update()
#FPS
clock.tick(FPS)
#loops through code
if game_exit == True:
pygame.quit()
game_loop()
print (f'your record is {record}')
it would mean allot you could find the error in my code.
if you find any other issues please let me know thanks.
The bit of code here is quite wrong. Try this in a while True: loop:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
pygame.display.update()
[The pygame.display.update bit is in a different place so delete it where it was and copy and past this in isntead.]
I'm making a game with pygame, Space Invaders, and now I'm doing the collisions between the shoot of the eneimies and the player (those are images), but it doesn't work all time and I'd like to know why, and what's the solution.
Thanks for attention!
Here's the code:
# -*- coding: cp1252 -*-
import sys
import random
import pygame
import time
print pygame.init()
x_player, y_player = 650, 440
screen = pygame.display.set_mode((700, 500))
pygame.display.set_caption("Space Invaders v1.0.0")
invaders = pygame.image.load(
"C:\\Users\\bernardo\\Documents\\IFC\\Programação\\SpaceInvaders- my_own\\space-invaders.jpeg").convert_alpha()
player = pygame.image.load(
"C:\\Users\\bernardo\\Documents\\IFC\\Programação\\SpaceInvaders-my_own\\28006.png").convert_alpha()
mother_ship = pygame.image.load(
"C:\\Users\\bernardo\\Documents\\IFC\\Programação\\SpaceInvaders-my_own\\mother_ship.png").convert_alpha()
lifes = pygame.image.load(
"C:\\Users\\bernardo\\Documents\\IFC\\Programação\\SpaceInvaders-my_own\\28007.png").convert_alpha()
shoot_enemie = pygame.image.load(
"C:\\Users\\bernardo\\Documents\\IFC\\Programação\\SpaceInvaders-my_own\\shots_and_bombs2.png").convert_alpha()
shoot = pygame.image.load(
"C:\\Users\\bernardo\\Documents\\IFC\\Programação\\SpaceInvaders-my_own\\shots_and_bombs2.png").convert_alpha()
pygame.font.init()
clock = pygame.time.Clock()
move_x = 0
x_invaders, y_invaders = 60, 60
lifes_list = [lifes, lifes, lifes]
x_mother = 0
invaders_matrix = [[invaders] * 11] * 5
existe_nave = False
start = True
tru = False
tru3= True
x_shoot = x_player
y_shoot = 0
tru2 = True
shoot_enemie1, shoot_enemie2, shoot_enemie3 = shoot_enemie, shoot_enemie, shoot_enemie
shoot_list = [shoot_enemie1, shoot_enemie2, shoot_enemie]
tiros = {
"se1" : [0, 0],
"se2" : [0, 0],
"se3" : [0, 0]
}
cont = 0
while True:
invaders_matrix = [[invaders] * 11] * 5
if len(lifes_list) > 0:
clock.tick(40)
screen.fill((0, 0, 0))
screen.blit(player, ((x_player / 2), y_player))
if not tru:
invaders = pygame.image.load(
"C:\\Users\\bernardo\\Documents\\IFC\\Programação\\SpaceInvaders-my_own\\space- invader-motif.png"
).convert_alpha()
tru = True
else:
invaders = pygame.image.load(
"C:\\Users\\bernardo\\Documents\\IFC\\Programação\\SpaceInvaders-my_own\\space-invaders.jpeg"
).convert_alpha()
tru = False
x_invaders, y_invaders = 105, 125
for invader in range(len(invaders_matrix)):
for invad in range(len(invaders_matrix[invader])):
screen.blit(invaders_matrix[invader][invad], (x_invaders, y_invaders))
x_invaders += 45
x_invaders = 105
y_invaders += 30
if tru2:
for i in tiros.keys():
tiros[i][0] += tiros[i][0] + random.randint(0, 10) * 45 + 105
tiros[i][1] += tiros[i][1] + random.randint(0, 4) * 45 + 125
tru2 = False
elif tiros["se1"][1] >= 600 and tiros["se2"][1] >= 600 and tiros["se3"][1] >= 600:
tiros["se1"][1], tiros["se2"][1], tiros["se3"][1], \
tiros["se1"][0], tiros["se2"][0], tiros["se3"][0] = 0, 0, 0, 0, 0, 0
for i in tiros.keys():
tiros[i][0] += tiros[i][0] + random.randint(0, 10) * 45 + 105
tiros[i][1] += tiros[i][1] + random.randint(0, 4) * 45 + 125
for i in shoot_list:
for j in tiros.keys():
screen.blit(i, (tiros[j][0], tiros[j][1]))
for i in tiros.keys():
tiros[i][1] += 4
if existe_nave and (x_mother < 700):
screen.blit(mother_ship, [x_mother, 35])
x_mother += 4.5
screen.blit(mother_ship, [x_mother, 35])
elif random.randint(0, 800) == 0:
existe_nave = True
x_mother = 0
width_for_lifes = 680
for icon_lifes in lifes_list:
width_for_lifes -= 50
screen.blit(icon_lifes, (width_for_lifes, 15))
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
move_x -= 10
if event.key == pygame.K_RIGHT:
move_x += 10
if tru3:
if event.key == pygame.K_SPACE:
y_shoot = y_player - player.get_height()
x_shoot = x_player / 2 + 20
tru3 = False
elif not tru3:
if y_shoot <= 0 and event.key == pygame.K_SPACE:
y_shoot = y_player - player.get_height()
x_shoot = x_player / 2 + 20
if event.type == pygame.KEYUP and (event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT):
move_x = 0
if y_shoot > -50:
screen.blit(shoot, (x_shoot, y_shoot))
y_shoot -= 10
if x_player >= 1280:
x_player = 1280
if x_player <= 25:
x_player = 25
x_player += move_x
font = pygame.font.Font(None, 36)
text = font.render("Lifes", 1, (0, 255, 85))
screen.blit(text, (450, 15))
font = pygame.font.Font(None, 36)
text = font.render("Score", 1, (0, 255, 85))
screen.blit(text, (20, 15))
#Here is the problem
player_rect = pygame.Rect(x_player, y_player, player.get_height(), player.get_width())
shoot_enemie1_rect = pygame.Rect(tiros["se1"][0], tiros["se1"][1], shoot_enemie1.get_height(),
shoot_enemie1.get_width())
shoot_enemie2_rect = pygame.Rect(tiros["se2"][0], tiros["se2"][1], shoot_enemie2.get_height(),
shoot_enemie2.get_width())
shoot_enemie3_rect = pygame.Rect(tiros["se3"][0], tiros["se3"][1], shoot_enemie3.get_height(),
shoot_enemie3.get_width())
if player_rect.colliderect(shoot_enemie1_rect) or player_rect.colliderect(shoot_enemie2_rect) or \
player_rect.colliderect(shoot_enemie3_rect):
print True
print player_rect
pygame.display.update()
Here is a collision detection code that will sense if one rectangle collides with another rectangle, if the enemy's shot hits the player:
if player x < shot x + player width and player x + shot width > shot x and player y < shot y + player height and shot height + player_y > shot y:
It works by sensing if any of the edges of the bullet are touching any edges of the character. I hope this helps.