Black window pygame - python

I am writing a snake game with pygame but I am just prompted with a black window without any error.
I checked similar problems and they incorrectly used the screen object. However this does not seem to be the case here, since it is only created once?
Any idea what I am doing wrong? Since I am not given any error message I can't figure out why I am only shown a black screen. The key input events work just fine.
import pygame
import random
import sys
# Define colors
GRAY = (240, 240, 245)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLACK = (50, 50, 50)
# Field size
width = 400
height = 400
# Calculate the distance between two points
def calculate_distance(x1, x2, y1, y2):
return (x2 - x1)**2 + (y1 - y2)**2 ** 1/2
# Draws a label showing the current score in the top mid of the window
def draw_score_text(surface, text, font_size, x, y):
font_name = pygame.font.match_font('arial')
font = pygame.font.Font(font_name, font_size)
text_surface = pygame.font.render(text, True, WHITE)
text_rect = text_surface.get_rect()
text_rect.midtop = (x, y)
surf.blit(text_surface, text_rect)
class Snake(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface((12,12))
self.image.fill(WHITE)
self.rect=self.image.get_rect()
self.rect.center = (100,100)
self.speedx=0
self.speedy=0
self.score=0
self.tail=[]
def update(self):
if self.score == len(self.tail):
self.tail.append((self.rect.x, self.rect.y))
else:
self.tail.append((self.rect.x, self.rect.y))
self.tail.pop(0)
self.rect.x += self.speedx
self.rect.y += self.speedy
keys = pygame.key.get_pressed()
if(keys[pygame.K_RIGHT] and self.speedx >=0):
self.speedx = 10
self.speedy = 0
if(keys[pygame.K_LEFT] and self.speedx <=0):
self.speedx = -10
self.speedy = 0
if(keys[pygame.K_UP] and self.speedy <=0):
self.speedx = 0
self.speedy = -10
if(keys[pygame.K_DOWN] and self.speedy >=0):
self.speedx = 0
self.speedy = 10
if self.rect.left >= width:
self.rect.left = 1
if self.rect.top >= height:
self.rect.top = 0
if self.rect.bottom <= 0:
self.rect.bottom = height
if self.rect.left <= 0:
self.rect.left = width
def exit(self):
for i in range(1, len(self.tail)):
if dist(self.rect.x, self.rect.y, self.tail[i][0], self.tail[i][1]) < 1:
sys.exit()
class Food(pygame.sprite.Sprite):
def __init__(self, x, y):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface((12,12))
self.image.fill(RED)
self.rect=self.image.get_rect()
self.rect.center = (x, y)
# Start dah game
pygame.init()
screen = pygame.display.set_mode([width,height])
clock = pygame.time.Clock()
running = True
print("ok?")
all_sprites = pygame.sprite.Group()
player = Snake()
food = Food(random.randrange(20, width - 20), random.randrange(20, height - 20))
all_sprites.add(player)
all_sprites.add(food)
while running:
clock.tick(3)
#pygame.display.update()
keys_pressed = pygame.event.get()
print(keys_pressed)
for i in keys_pressed:
if i.type == pygame.QUIT:
print("quit")
running = False
if pygame.sprite.collide_rect(player, food):
food.kill()
player.score += 1
food = Food(random.randrange(20, width - 20), random.randrange(20, height - 20))
all_sprites.add(food)
all_sprites.update()
screen.fill(BLACK)
player.exit()
for i in range(1, len(player.tail)):
pygame.draw.rect(screen, WHITE, (player.tail[i][0], player.tail[i][2], 12, 12))
#draw_score_text(screen, str(player.score), 18, width/2, 10)
all_sprites.draw(screen)
pygame.display.flip()
pygame.quit()

The update of the display and the drawing of the sprites has to be done in the main loop rather than in the inner for loop:
while running:
# [...]
for i in range(1, len(player.tail)):
pygame.draw.rect(screen, WHITE, (player.tail[i][0], player.tail[i][2], 12, 12))
# <--
all_sprites.draw(screen)
pygame.display.flip()
Note, if the snake consists of a head only, then the inner loop is not executed. If the length of the tail would be > 1, then the display would be updated multiple times per frame, which is not what you want.
I am getting an out of range exception
Traceback (most recent call last): File "snake.py", line 132, in <module> >
pygame.draw.rect(screen, WHITE, (player.tail[i][0], player.tail[i][2], 12, 12))
IndexError: tuple index out of range `
The index of the 2nd (y) coordinate is 1 rather than 2. Ist has to be player.tail[i][1]:
for i in range(1, len(player.tail)):
pygame.draw.rect(screen, WHITE, (player.tail[i][0], player.tail[i][1], 12, 12))

Related

How I can add platform collision?

I'm newbe in programming and I'm still learn and i try make my first platform game.
In first steps everything was good but i have problem with detect collision with platform.
I add collision if player is falling and it work good, but if I try add collision with bottom, left and right side platform, is not working good :(
I add all code to cleary view. If player is falling, code work okay.
Do You have idea what I can do, to add collisions?
#main
# Project 1 - platform game
import pygame as pg
import random
from settings import *
from sprites import *
from os import path
class Game:
def __init__(self):
# inicjalizacja okna gry itd
pg.init()
pg.mixer.init()
self.screen = pg.display.set_mode((WIDTH, HEIGHT))
pg.display.set_caption(TITLE)
self.clock = pg.time.Clock()
self.running = True
self.font_name = pg.font.match_font(FONT_NAME) # fonts
def new(self):
# start a new game
self.all_sprites = pg.sprite.Group() # all sprite's
self.platforms = pg.sprite.Group()
self.player = Player(self) # dodaję gracza
self.all_sprites.add(self.player)
# dodaję platformy
for plat in PLATFORM_LIST:
p = Platform(*plat)
self.all_sprites.add(p)
self.platforms.add(p)
#ground generator
i = 0
x = 0
while i < 35:
ground = Platform(x, HEIGHT - 40, 50, 40)
self.all_sprites.add(ground)
self.platforms.add(ground)
i += 1
x += 50
self.run() # game loop start
def run(self):
# game loop
self.playing = True
while self.playing:
self.clock.tick(FPS)
self.events()
self.update()
self.draw()
def update(self):
# game loop udpate
self.all_sprites.update()
# collision if player is falling
if self.player.vel.y > 0:
hits = pg.sprite.spritecollide(self.player, self.platforms, False)
if hits:
self.player.pos.y = hits[0].rect.top
self.player.vel.y = 0
# still I don't have idea what I can make collision with right, left and bottom
platform
# if player reach 1/2 screen
if self.player.rect.right >= WIDTH / 2:
self.player.pos.x -= abs(self.player.vel.x)
for plat in self.platforms:
plat.rect.right -= abs(self.player.vel.x)
if plat.rect.right <= WIDTH:
plat.kill
# player die
if self.player.rect.bottom > HEIGHT:
self.playing = False
def events(self):
# game loop - events
for event in pg.event.get():
if event.type == pg.QUIT:
if self.playing:
self.playing = False
self.running = False
if event.type == pg.KEYDOWN:
if event.key == pg.K_SPACE:
self.player.jump()
def draw(self):
#game loop - draw
self.screen.fill(BLACK)
self.all_sprites.draw(self.screen)
pg.display.flip()
def show_start_screen(self):
# start screen not add yet
pass
def show_go_screen(self):
# game over screen
if not self.running:
return
self.screen.fill(BLUE)
self.draw_text("GAME OVER!", 48, WHITE, WIDTH / 2, HEIGHT / 4)
self.draw_text("Press button to play again", 22, WHITE, WIDTH / 2, HEIGHT * 3 / 4)
pg.display.flip()
self.wait_for_key()
def wait_for_key(self):
waiting = True
while waiting:
self.clock.tick(FPS)
for event in pg.event.get():
if event.type == pg.QUIT:
waiting = False
self.running = False
if event.type == pg.KEYUP:
waiting = False
def draw_text(self, text, size, color, x, y):
font = pg.font.Font(self.font_name, size)
text_surface = font.render(text, True, color)
text_rect = text_surface.get_rect()
text_rect.midtop = (x, y)
self.screen.blit(text_surface, text_rect)
g = Game()
g.show_start_screen()
while g.running:
g.new()
g.show_go_screen()
pg.quit()
#SPRITES
import pygame as pg
from settings import *
import random
vec = pg.math.Vector2
class Player(pg.sprite.Sprite):
def __init__(self, game):
pg.sprite.Sprite.__init__(self)
self.game = game
self.image = pg.Surface((30, 40))
self.image.fill(YELLOW)
self.rect = self.image.get_rect()
self.rect.center = (WIDTH / 2, HEIGHT / 2)
self.pos = vec(WIDTH / 2, HEIGHT / 2)
self.vel = vec(0, 0)
self.acc = vec(0, 0)
def jump(self):
self.rect.x += 1
hits = pg.sprite.spritecollide(self, self.game.platforms, False)
self.rect.x -= 1
if hits:
self.vel.y = - PLAYER_JUMP
def update(self):
self.acc = vec(0, PLAYER_GRAV) # PLAYER_GRAV - gravity
keys = pg.key.get_pressed()
if keys[pg.K_LEFT]:
self.acc.x = - PLAYER_ACC
if keys[pg.K_RIGHT]:
self.acc.x = PLAYER_ACC
# add friction
self.acc.x += self.vel.x * PLAYER_FRICTION
# równanie ruchu
self.vel += self.acc
if abs(self.vel.x) < 0.1:
self.vel.x = 0
self.pos += self.vel + 0.5 * self.acc
if self.pos.x > WIDTH:
self.pos.x = WIDTH
if self.pos.x < 0:
self.pos.x = 0
self.rect.midbottom = self.pos
class Platform(pg.sprite.Sprite):
def __init__(self, x, y, w, h):
pg.sprite.Sprite.__init__(self)
self.image = pg.Surface((w, h))
self.image.fill(GREEN)
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
# settings
TITLE = "Project One"
WIDTH = 800
HEIGHT = 600
FPS = 60
FONT_NAME = 'comic sans ms' # arial, verdana, times new roman, palatino, garamond, comic sans ms
# ustawienia gracza
PLAYER_FRICTION = -0.12
PLAYER_ACC = 0.5
PLAYER_JUMP = 20
PLAYER_GRAV = 0.8
# lista platform
GROUND_LIST =[(0, HEIGHT - 40, 50, 40),
(50, HEIGHT - 40, 50, 40),
(100, HEIGHT - 40, 50, 40),
(150, HEIGHT - 40, 50, 40),
(200, HEIGHT - 40, 50, 40),
(250, HEIGHT - 40, 50, 40),
(300, HEIGHT - 40, 50, 40),
(350, HEIGHT - 40, 50, 40),
(400, HEIGHT - 40, 50, 40)]
PLATFORM_LIST = [(300, 300, 75, 40),
(400, 350, 75, 40),
(600, 300, 75, 40),
(800, 250, 75, 40),
(1000, 350, 75, 40),
(1200, 400, 75, 40),
(1400, 200, 75, 40),]
# defined colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
YELLOW = (255, 255, 0)
I write again,
I did some work and found a solution to my problem :) I had to describe the collisions for x and y separately. Additionally, entering the collisions inside the Player class helped to eliminate the problem with the player jumping to the top platforms.

Check sprite collision only for one side

Hey I have a problem with my game code. Is there a way to check if, for example, the right side of my player sprite (hero) is colliding with the group obstacle_sprite?
I can only figure out how to check for collision in general but I want only a true output if the right side of the player is colliding wit the obstacle.
In my code I am using a invisible sprite as hitbox and draw the player inside this invisible sprite to check collisions but make it look like the obstacle denies moving of the player.
import pygame
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
PINK = (230, 77, 149)
FPS = 60
window_width = 900
window_height = 600
window_color = WHITE
window = pygame.display.set_mode((window_width, window_height))
window.fill(window_color)
pygame.display.set_caption("Bub - the game")
clock = pygame.time.Clock()
class Player(pygame.sprite.Sprite):
def __init__(self, x, y, width, height, velocity, color):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface((width + 2*velocity, height + 2*velocity))
self.rect = self.image.get_rect()
self.rect.topleft = (x - velocity, y - velocity)
self.velocity = velocity
self.is_jump = False
self.jump_count = 15
self.fall_count = 1
self.ground = self.rect.bottom
self.body = pygame.Rect(x, y, width, height)
pygame.draw.rect(window, color, self.body)
def move(self):
key = pygame.key.get_pressed()
if key[pygame.K_a] and self.rect.left >= 0:
self.rect.x -= self.velocity
if key[pygame.K_d] and self.rect.right <= window_width:
self.rect.x += self.velocity
if not self.is_jump:
if key[pygame.K_SPACE] and self.rect.bottom == self.ground:
self.is_jump = True
else:
if self.jump_count >= 0:
self.rect.y -= round((self.jump_count ** 2) * 0.1)
self.jump_count -= 1
else:
self.jump_count = 15
self.is_jump = False
def gravity(self):
if not self.is_jump and self.rect.bottom != self.ground:
self.rect.y += round((self.fall_count ** 2) * 0.1)
if self.fall_count <= 15:
self.fall_count += 1
else:
self.fall_count = 1
def update(self):
self.move()
self.gravity()
pygame.draw.rect(window, BLACK, self.body)
self.body.topleft = (self.rect.x + self.velocity, self.rect.y + self.velocity)
class Obstacle(pygame.sprite.Sprite):
def __init__(self, x, y, width, height, color):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface((width, height))
self.image.fill(color)
self.rect = self.image.get_rect()
self.rect.center = (x, y)
player_sprite = pygame.sprite.Group()
obstacle_sprite = pygame.sprite.Group()
hero = Player(0, 570, 30, 30, 5, BLACK)
player_sprite.add(hero)
obstacle_1 = Obstacle(100, 585, 120, 30, PINK)
obstacle_sprite.add(obstacle_1)
run = True
while run:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
window.fill(window_color)
player_sprite.update()
player_sprite.draw(window)
obstacle_sprite.update()
obstacle_sprite.draw(window)
pygame.display.update()
pygame.quit()
It's easier if you keep track of your player's velocity; this will make handling jumping also less complex.
A common technique AFAIK is to do two collision detection runs: one for the x-axis and one for the y-axis.
Here's how I changed your code. As you can see, checking for the side of a collision is as easy as checking xvel < 0 or xvel > 0:
import pygame
pygame.init()
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
PINK = (230, 77, 149)
FPS = 60
window_width = 900
window_height = 600
window_color = WHITE
window = pygame.display.set_mode((window_width, window_height))
window.fill(window_color)
pygame.display.set_caption("Bub - the game")
clock = pygame.time.Clock()
class Toast(pygame.sprite.Sprite):
def __init__(self, *grps):
super().__init__(*grps)
self.image = pygame.Surface((900, 200))
self.image.fill(WHITE)
self.rect = self.image.get_rect(topleft=(10, 10))
self.font = pygame.font.SysFont(None, 32)
def shout(self, message):
self.text = self.font.render(message, True, BLACK)
self.image.fill(WHITE)
self.image.blit(self.text, (0, 0))
class Player(pygame.sprite.Sprite):
def __init__(self, x, y, width, height, velocity, color, *grps):
super().__init__(*grps)
self.image = pygame.Surface((width + 2*velocity, height + 2*velocity))
self.image.fill(color)
self.rect = self.image.get_rect()
self.rect.topleft = (x - velocity, y - velocity)
self.velocity = velocity
self.on_ground = True
self.xvel = 0
self.yvel = 0
def collide(self, xvel, yvel, obstacle_sprites):
global toast
for p in pygame.sprite.spritecollide(self, obstacle_sprites, False):
if xvel > 0:
self.rect.right = p.rect.left
toast.shout('collide RIGHT')
if xvel < 0:
self.rect.left = p.rect.right
toast.shout('collide LEFT')
if yvel > 0:
self.rect.bottom = p.rect.top
self.on_ground = True
self.yvel = 0
toast.shout('collide BOTTOM')
if yvel < 0:
self.rect.top = p.rect.bottom
self.yvel = 0
toast.shout('collide TOP')
def update(self, obstacle_sprites):
global toast
key = pygame.key.get_pressed()
self.xvel = 0
if key[pygame.K_a]:
self.xvel =- self.velocity
if key[pygame.K_d]:
self.xvel = self.velocity
if self.on_ground:
if key[pygame.K_SPACE]:
toast.shout('JUMPING')
self.on_ground = False
self.yvel = -20
else:
self.yvel += 1
self.rect.left += self.xvel
self.collide(self.xvel, 0, obstacle_sprites)
self.rect.top += self.yvel
self.on_ground = False
self.collide(0, self.yvel, obstacle_sprites)
self.rect.clamp_ip(pygame.display.get_surface().get_rect())
if self.rect.bottom == pygame.display.get_surface().get_rect().bottom:
self.on_ground = True
class Obstacle(pygame.sprite.Sprite):
def __init__(self, x, y, width, height, color, *grps):
super().__init__(*grps)
self.image = pygame.Surface((width, height))
self.image.fill(color)
self.rect = self.image.get_rect(center=(x, y))
all_sprites = pygame.sprite.Group()
player_sprite = pygame.sprite.Group()
obstacle_sprites = pygame.sprite.Group()
toast = Toast(all_sprites)
hero = Player(0, 570, 30, 30, 5, GREEN, all_sprites, player_sprite)
for x in [
(100, 585, 120, 30),
(300, 535, 120, 30),
(500, 485, 120, 30)
]:
Obstacle(*x, PINK, all_sprites, obstacle_sprites)
run = True
while run:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
window.fill(window_color)
all_sprites.update(obstacle_sprites)
all_sprites.draw(window)
pygame.display.update()
pygame.quit()

I was trying to add an image to my game but Im getting pygame.error: Unsupported image format [duplicate]

This question already has answers here:
Could not open resource file, pygame error: "FileNotFoundError: No such file or directory."
(1 answer)
Is there any other way to load a resource like an image, sound, or font into Pygame? [closed]
(1 answer)
Closed 2 years ago.
I'm making a game and I tried to add some images instead of surfaces but I don't really know how it works I was wondering if some could explain to how its work cause I'm getting pygame.error: Unsupported image format and I don't know what that means or what I've done wrong.
Below is an image of the code in question as well as my directory files (on the left)
also im using a program called Pycharm idk if that might affect at all or not
# import images for sprites
img_dir = path.join(path.dirname(__file__), 'Img')
# load images
player_img = py.image.load(path.join(img_dir, "Playerimg.png")).convert()
class Player(py.sprite.Sprite):
def __init__(self):
py.sprite.Sprite.__init__(self)
self.image = player_img
self.rect = self.image.get_rect()
self.rect.centerx = WIDTH / 2
self.rect.bottom = HEIGHT / 2
self.Yspeed = 0
self.rotatableimage = self.image
The rest of the code is below if you need it also I know it might be hard to troubleshoot image-based stuff soo here the code but without the images (two parts btw)
import random
import math
import pygame as py
from PlayerSprite import *
WIDTH = 800
HEIGHT = 600
FPS = 60
# define colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
YELLOW = (255, 255, 0)
# initialize pygame and create window
py.init()
py.mixer.init()
screen = py.display.set_mode((WIDTH, HEIGHT))
py.display.set_caption("Dimensional Drifter")
clock = py.time.Clock()
all_sprites = py.sprite.Group()
NPCs = py.sprite.Group()
bullets = py.sprite.Group()
player = Player()
all_sprites.add(player)
for i in range(14):
n = NPC(player)
all_sprites.add(n)
NPCs.add(n)
# Game loop
running = True
while running:
# keep loop running at the right speed
clock.tick(FPS)
for event in py.event.get():
# check for closing window
if event.type == py.QUIT:
running = False
elif event.type == py.MOUSEBUTTONDOWN:
if event.button == 1:
New_bullet = player.Shoot()
all_sprites.add(New_bullet)
bullets.add(New_bullet)
# Update
all_sprites.update()
# # check if there a collision between the bullet and NPC
hits = py.sprite.groupcollide(NPCs, bullets, True, True)
# check if there a collision between the player and NPC
hits = py.sprite.spritecollide(player, NPCs, True)
if hits:
running = False
# updates the position of of mouse and rotates it towards the mouse position
mouse_x, mouse_y = py.mouse.get_pos()
player.rotate(mouse_x, mouse_y)
# render
screen.fill(BLACK)
all_sprites.draw(screen)
# flip the display
py.display.flip()
py.quit()
import pygame as py
import math
import random
WIDTH = 800
HEIGHT = 600
FPS = 60
# define colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
YELLOW = (255, 255, 0)
class Player(py.sprite.Sprite):
def __init__(self):
py.sprite.Sprite.__init__(self)
self.image = py.Surface((40, 40), py.SRCALPHA)
self.image.fill(GREEN)
self.rect = self.image.get_rect()
self.rect.centerx = WIDTH / 2
self.rect.bottom = HEIGHT / 2
self.Yspeed = 0
self.rotatableimage = self.image
def update(self):
self.Xspeed = 0
self.Yspeed = 0
# line below allow for key press to equate to move of sprite
keypreesed = py.key.get_pressed()
if keypreesed[py.K_a]:
self.Xspeed = - 11
if keypreesed[py.K_d]:
self.Xspeed = 11
if keypreesed[py.K_w]:
self.Yspeed = - 11
if keypreesed[py.K_s]:
self.Yspeed = 11
self.rect.x += self.Xspeed
self.rect.y += self.Yspeed
# line below allow the sprite to wrap around the screen
if self.rect.left > WIDTH:
self.rect.right = 0
if self.rect.right < 0:
self.rect.left = WIDTH
if self.rect.top > HEIGHT:
self.rect.top = 0
if self.rect.bottom < 0:
self.rect.bottom = HEIGHT
def rotate(self, mouse_x, mouse_y):
rel_x = mouse_x - self.rect.x
rel_y = mouse_y - self.rect.y
angle = (180 / math.pi) * -math.atan2(rel_y, rel_x)
self.image = py.transform.rotate(self.rotatableimage, int(angle))
self.rect = self.image.get_rect(center=(self.rect.centerx, self.rect.centery))
return
def Shoot(self):
pos = self.rect.centerx, self.rect.centery
mpos = py.mouse.get_pos()
direction = py.math.Vector2(mpos[0] - pos[0], mpos[1] - pos[1])
direction.scale_to_length(10)
return Bullet(pos[0], pos[1], round(direction[0]), round(direction[1]))
class NPC(py.sprite.Sprite):
def __init__(self, player):
py.sprite.Sprite.__init__(self)
self.player = player
self.image = py.Surface((30, 30)).convert_alpha()
self.image.fill(RED)
self.originalimage = self.image
self.rect = self.image.get_rect()
self.spawn()
# allows of spawning from all four side of the screen and set the x, y speed and spawn position
def spawn(self):
self.direction = random.randrange(4)
if self.direction == 0:
self.rect.x = random.randrange(WIDTH - self.rect.width)
self.rect.y = random.randrange(-100, -40)
self.Xspeed = random.randrange(-2, 2)
self.Yspeed = random.randrange(4, 8)
elif self.direction == 1:
self.rect.x = random.randrange(WIDTH - self.rect.width)
self.rect.y = random.randrange(HEIGHT, HEIGHT + 60)
self.Xspeed = random.randrange(-2, 2)
self.Yspeed = -random.randrange(4, 8)
elif self.direction == 2:
self.rect.x = random.randrange(-100, -40)
self.rect.y = random.randrange(HEIGHT - self.rect.height)
self.Xspeed = random.randrange(4, 8)
self.Yspeed = random.randrange(-2, 2)
elif self.direction == 3:
self.rect.x = random.randrange(WIDTH, WIDTH + 60)
self.rect.y = random.randrange(HEIGHT - self.rect.height)
self.Xspeed = -random.randrange(4, 8)
self.Yspeed = random.randrange(-2, 2)
def update(self):
self.rect.x += self.Xspeed
self.rect.y += self.Yspeed
# makes it so that NPC point to wards the player as it passes from side to side
dir_x, dir_y = self.player.rect.x - self.rect.x, self.player.rect.y - self.rect.y
self.rot = (180 / math.pi) * math.atan2(-dir_x, -dir_y)
self.image = py.transform.rotate(self.originalimage, self.rot)
# Respawns the NPC when they hit an side
if self.direction == 0:
if self.rect.top > HEIGHT + 10:
self.spawn()
elif self.direction == 1:
if self.rect.bottom < -10:
self.spawn()
elif self.direction == 2:
if self.rect.left > WIDTH + 10:
self.spawn()
elif self.direction == 3:
if self.rect.right < -10:
self.spawn()
class Bullet(py.sprite.Sprite):
def __init__(self, x, y, Xspeed, Yspeed):
py.sprite.Sprite.__init__(self)
self.image = py.Surface((5, 5))
self.image.fill(YELLOW)
self.rect = self.image.get_rect()
self.rect.bottom = y
self.rect.centerx = x
self.Xspeed = Xspeed
self.Yspeed = Yspeed
def update(self):
self.rect.x += self.Xspeed
self.rect.y += self.Yspeed
# kill if moved of screen
if self.rect.bottom > HEIGHT or self.rect.top < 0:
self.kill()
if self.rect.right > WIDTH or self.rect.left < 0:
self.kill()
it might be hard to help me on this one so because of images and what not but if could just explain it to me then i could implement on my own that could work too :)
edit 3:
Edit 2:
Edit: image of error

pygame sprite.spritecollide() doesn't work with moving sprite Group

When my player sprite collides with the coin group the coins disappear as wanted, but when it collides with the enemys group nothing happens. The code is the same. I don't know what I did wrong because I did the same thing twice but it only works once. Does it have anything to do with the enemys moving? Here is the the code:
import pygame as pg
import random
a_white = (245, 245, 245)
a_red = (10, 0, 0)
black = (0, 0, 0)
white = (255, 255, 255)
blue_grey = (51, 93, 127)
dark_red = (85, 0, 0)
red = (255, 0, 0)
green = (0, 255, 0)
blue = (0, 0, 255)
yellow = (255, 255, 0)
bg_color = dark_red
width = 600
height = 500
FPS = 60
p_width = 70
p_height = 70
c_width = 35
c_height = 35
score = 0
level = 0
lives = 3
title = 'This Is My Game!'
pg.init()
pg.mixer.init()
clock = pg.time.Clock()
screen = pg.display.set_mode((width, height))
pg.display.set_caption(title)
font_name = pg.font.match_font("arial")
coin_img = pg.image.load('coin3.png').convert()
player_img = pg.image.load('smiley.png').convert_alpha()
gegner_1 = pg.image.load('gegner_black.png').convert_alpha()
coin_snd = pg.mixer.Sound('coin_snd_2.ogg')
def new_coin():
x = random.randrange(c_width, width - c_width)
y = random.randrange(c_height, height - c_height)
coins = Coin(x, y)
all_sprites.add(player, coins)
coin_group.add(coins)
def draw_text(screen, text, t_color, size, t_x, t_y):
font = pg.font.Font(font_name, size)
text_surface = font.render(text, True, t_color)
text_rect = text_surface.get_rect()
text_rect.midtop = (t_x, t_y)
screen.blit(text_surface, text_rect)
def start_screen():
screen.fill(bg_color)
draw_text(screen, 'Welcome... !', white, 75, width / 2, height / 4 - 100)
draw_text(screen, 'ready to play my game*?', white, 24, width - 150, height / 4 - 20)
draw_text(screen, "Press any key to begin", white, 20, width / 2 + 60, height / 4 + 10)
draw_text(screen, "*The name of the game is \'MY GAME\' but that ",
white, 16, width / 2, height - 150)
draw_text(screen, " has nothing to do with the fact, that the game is", white, 16, width / 2, height - 130)
draw_text(screen, " my game. Yes, the game is actually my game, ", white, 16, width / 2, height - 110)
draw_text(screen, " but that\'s not the reason I named it my game. ", white, 16, width / 2, height - 90)
draw_text(screen, "...or is it?", white, 13, width - 28, height - 20)
pg.display.update()
waiting = True
while waiting:
clock.tick(FPS)
for event in pg.event.get():
if event.type == pg.QUIT:
pg.quit()
if event.type == pg.KEYUP:
waiting = False
class Player(pg.sprite.Sprite):
def __init__(self):
super().__init__()
self.image_orig = pg.transform.scale(player_img, (p_width, p_height))
self.image = self.image_orig.copy()
self.rect = self.image.get_rect()
self.rect.center = (width / 2), (height / 2)
self.radius = 35
def update(self):
keys = pg.key.get_pressed()
if keys[pg.K_RIGHT]:
self.rect.x += 5
if keys[pg.K_LEFT]:
self.rect.x -= 5
if keys[pg.K_UP]:
self.rect.y -= 5
if keys[pg.K_DOWN]:
self.rect.y += 5
if self.rect.right > width:
self.rect.right = width
if self.rect.left < 0:
self.rect.left = 0
if self.rect.top < 0:
self.rect.top = 0
if self.rect.bottom > height:
self.rect.bottom = height
class Coin(pg.sprite.Sprite):
def __init__(self, x, y):
super().__init__()
self.image = pg.transform.scale(coin_img, (c_width, c_height))
self.image.set_colorkey(white)
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
self.radius = 18
class Gegner_1(pg.sprite.Sprite):
def __init__(self, x, y, yon):
super().__init__()
self.image_orig = pg.transform.scale(gegner_1, (p_width, p_height))
self.image_orig.set_colorkey(white)
self.image = self.image_orig.copy()
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
self.radius = 35
self.yon = yon
if yon == 'yes':
self.speedx = 5
self.speed = self.speedx
elif yon == 'no':
self.speedy = 5
self.speed = self.speedy
def update(self):
if self.yon == 'yes':
self.rect.x += self.speed
if self.yon == 'no':
self.rect.y += self.speed
if self.rect.right > width:
self.speed = -5
if self.rect.left == 0:
self.speed = 5
if self.rect.bottom > height:
self.speed = -5
if self.rect.top < 0:
self.speed = 5
all_sprites = pg.sprite.Group()
coin_group = pg.sprite.Group()
enemys_group = pg.sprite.Group()
player = Player()
gegner1 = Gegner_1(0, 60, 'yes')
gegner2 = Gegner_1(width, 350, 'yes')
gegner3 = Gegner_1(50, p_height, 'no')
gegner4 = Gegner_1(width - p_width - 20, p_height, 'no')
enemys_group.add(gegner1, gegner2, gegner3, gegner4)
all_sprites.add(player)
for c in range(3):
new_coin()
start_game = True
game_over = False
done = False
while not done:
for event in pg.event.get():
if event.type == pg.QUIT:
done = True
if start_game:
start_screen()
start_game = False
screen.fill(bg_color)
if score >= 5:
all_sprites.add(gegner1)
if score >= 10:
all_sprites.add(gegner2)
if score >= 15:
all_sprites.add(gegner3)
if score >= 20:
all_sprites.add(gegner4)
all_sprites.draw(screen)
all_sprites.update()
draw_text(screen, 'SCORE: ' + str(score), white, 20, 55, 10)
hits = pg.sprite.spritecollide(player, coin_group, True, pg.sprite.collide_circle)
for hit in hits:
score += 1
coin_snd.play()
new_coin()
hits = pg.sprite.spritecollide(player, enemys_group, True, pg.sprite.collide_circle)
for hit in hits:
lives -= 1
pg.display.update()
clock.tick(FPS)
pg.quit()
I also don't get any errors because of this.
The way you add and remove the gegner instances causes this problem. The enemys_group contains the gegners in the beginning and is used for the collision detection. That means you can already collide with them before they are visible (print the groups and hit in the for hit in hits: loop to check this). If you hit an instance, it is removed from the enemys_group correctly.
Then if you reach a score of 5 or higher you keep adding the instances, that are still bound to the gegner1, etc. variables, to the all_sprites group each frame, so the sprites become visible, but if they're not in the enemys_group they can't collide anymore.
You need to restructure the code. I'd leave the enemys_group empty at the beginning and then add the gegner instances in the coin collision loop:
hits = pg.sprite.spritecollide(player, coin_group, True, pg.sprite.collide_circle)
for hit in hits:
score += 1
new_coin()
if score == 5:
gegner = Gegner_1(0, 60, 'yes')
all_sprites.add(gegner)
enemys_group.add(gegner)
elif score == 10:
gegner = Gegner_1(width, 350, 'yes')
all_sprites.add(gegner)
enemys_group.add(gegner)
elif score == 15:
gegner = Gegner_1(50, p_height, 'no')
all_sprites.add(gegner)
enemys_group.add(gegner)
elif score == 20:
gegner = Gegner_1(width - p_width - 20, p_height, 'no')
all_sprites.add(gegner)
enemys_group.add(gegner)

Pygame Start scren

im trying to create a game for class. and i want to add a start screen to it but it doesnt seem to work.
the whole code:
# To change this license header, choose License Headers in Project Properties.
# To change this template file, choose Tools | Templates
# and open the template in the editor.
import pygame
import random
from os import path
img_dir = path.join(path.dirname(__file__), 'Sprites')
snd_dir = path.join(path.dirname(__file__), 'sound')
WIDTH = 480
HEIGHT = 600
FPS = 30
car_img = pygame.image.load(path.join(img_dir, "copgreen20.bmp"))
mob_img = pygame.image.load(path.join(img_dir, "mob_zom.bmp"))
priv_img = pygame.image.load(path.join(img_dir, "copgreen20.bmp"))
# define colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
YELLOW = (255, 255, 0)
# initialize pygame and create window
pygame.init()
pygame.display.init()
screen = pygame.display.set_mode([800, 600])
test = "space.ogg"
pygame.mixer.init(frequency=22050, size=-16, channels=2, buffer=4096)
pygame.mixer.music.load(path.join(snd_dir, 'atari.ogg'))
pygame.mixer.music.play(-1)
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("My Game")
clock = pygame.time.Clock()
font_name = pygame.font.match_font('Arial')
def draw_text(surf, text, size, x, y):
font = pygame.font.Font(font_name, size)
text_surface = font.render(text, True, BLUE)
text_rect = text_surface.get_rect()
text_rect.midtop = (x, y)
surf.blit(text_surface, text_rect)
class Player(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface((80, 50))
self.images = []
self.image = car_img
self.rect = self.image.get_rect()
self.rect.centerx = WIDTH / 2
self.rect.bottom = HEIGHT - 50
self.speedx = 0
self.image = pygame.transform.scale(car_img, (50, 80))
self.image.set_colorkey(GREEN)
def update(self):
self.speedx = 0
keystate = pygame.key.get_pressed()
if keystate[pygame.K_LEFT]:
self.speedx = -8
if keystate[pygame.K_RIGHT]:
self.speedx = 8
if keystate[pygame.K_UP]:
self.speedy = -8
self.rect.x += self.speedx
if self.rect.right > WIDTH:
self.rect.right = WIDTH
if self.rect.left < 0:
self.rect.left = 0
def shoot(self):
bullet = Bullet(self.rect.centerx, self.rect.top)
all_sprites.add(bullet)
bullets.add(bullet)
class Mob(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface((30, 40))
self.image = mob_img
self.rect = self.image.get_rect()
self.rect.x = random.randrange(WIDTH - self.rect.width)
self.rect.y = random.randrange(-100, -40)
self.speedy = random.randrange(1, 9)
self.speedx = random.randrange(-3, 3)
self.image.set_colorkey(WHITE)
self.image.set_colorkey(YELLOW)
def update(self):
self.rect.x += self.speedx
self.rect.y += self.speedy
if self.rect.top > HEIGHT + 10 or self.rect.left < -25 or self.rect.right > WIDTH + 20:
self.rect.x = random.randrange(WIDTH - self.rect.width)
self.rect.y = random.randrange( -100, -40)
self.speedy = random.randrange(1, 8)
class Priv(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface((30, 40))
self.image = priv_img
self.rect = self.image.get_rect()
self.rect.x = random.randrange(WIDTH - self.rect.width)
self.rect.y = random.randrange(-100, -40)
self.speedy = random.randrange(1, 9)
self.speedx = random.randrange(-3, 3)
self.image.set_colorkey(WHITE)
self.image.set_colorkey(YELLOW)
def update(self):
self.rect.x += self.speedx
self.rect.y += self.speedy
if self.rect.top > HEIGHT + 10 or self.rect.left < -25 or self.rect.right > WIDTH + 20:
self.rect.x = random.randrange(WIDTH - self.rect.width)
self.rect.y = random.randrange( -100, -40)
self.speedy = random.randrange(1, 8)
class Bullet(pygame.sprite.Sprite):
def __init__(self, x, y):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface((10, 20))
self.image.fill(YELLOW)
self.rect = self.image.get_rect()
self.rect.bottom = y
self.rect.centerx = x
self.speedy = 200
all_sprites = pygame.sprite.Group()
mobs = pygame.sprite.Group()
player = Player()
all_sprites.add(player)
background = pygame.image.load(path.join(img_dir, "back_road.bmp")).convert()
background_rect = background.get_rect()
bullets = pygame.sprite.Group()
allspriteslist = pygame.sprite.Group()
#showstartscreen()
for i in range(8):
m = Mob()
all_sprites.add(m)
mobs.add(m)
def game_intro():
display = pygame.display.set_mode((800,600))
intro = True
while intro:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
display.fill(BLACK)
largeText = pygame.font.match_font('Arial',10)
textSurf, textRect = text_objects("this is a game", largeText)
textRect.centre = ((display_width/2), (display_height/2))
display.blit(textSurf, textRect)
pygame.display.update()
clock.tick(15)
pygame.display.update()
score = 000
# Game loop
game_intro()
running = True
while running:
# keep loop running at the right speed
clock.tick(FPS)
# Process input (events)
for event in pygame.event.get():
# check for closing window
if event.type == pygame.QUIT:
running = False
#for i in range(5):
#m = Mob()
#all_sprites.add(m)
#mobs.add(m)
elif event.type == pygame.KEYDOWN:
if event.type == pygame.K_9:
running = False
if event.key == pygame.K_SPACE:
player.shoot()
if event.key == pygame.K_EQUALS:
for i in range(100):
m = Mob()
all_sprites.add(m)
mobs.add(m)
#if event.key == pygame.K_SPACE:
if clock == 0:
for i in range(100):
m = Mob()
all_sprites.add(m)
mobs.add(m)
if event.key == pygame.K_1:
for i in range(2):
p = Priv()
all_sprites.add(p)
Priv.add(p)
if event.key == pygame.K_2:
for i in range(10):
m = Mob()
all_sprites.add(m)
mobs.add(m)
# Update
all_sprites.update()
hits = pygame.sprite.groupcollide(mobs, bullets, True, True)
for hit in hits:
score += 1
m = Mob()
all_sprites.add(m)
mobs.add(m)
p = Priv()
all_sprites.add(m)
Priv.add(p)
hits = pygame.sprite.spritecollide(player, mobs, False)
#if hits:
#running = False
try:
for i in bullets:
i.rect.bottom += -5
except:
None
# Draw / render
screen.fill(BLACK)
screen.blit(background, background_rect)
draw_text(screen, str(score), 50, WIDTH / 10, 10)
#draw_text(screen, str(scores), 50, WIDTH / 10, 10)
all_sprites.draw(screen)
# *after* drawing everything, flip the display
pygame.display.flip()
pygame.QUIT
the code where the problem is:
def game_intro():
display = pygame.display.set_mode((800,600))
intro = True
while intro:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
display.fill(BLACK)
largeText = pygame.font.match_font('Arial',10)
textSurf, textRect = text_objects("this is a game", largeText)
textRect.centre = ((display_width/2), (display_height/2))
display.blit(textSurf, textRect)
pygame.display.update()
clock.tick(15)
pygame.display.update()
score = 000
# Game loop
game_intro()
The error:
File "/Users/harrisonj11/NetBeansProjects/game_test_jakob/src/game_test_jakob.py", line 167, in
game_intro()
File
"/Users/harrisonj11/NetBeansProjects/game_test_jakob/src/game_test_jakob.py", line 159, in game_intro
textSurf, textRect = text_objects("this is a game", largeText)
NameError: name 'text_objects' is not defined
You haven't defined a text_objects function. It looks like you meant the draw_text function that you declared above, but it doesn't quite do what you want either.
I'm guessing that what you meant to do was something like:
Create a text surface and a rectangle that represents the bounds of that surface
Move the rectangle to the middle of the screen (the width / 2 code)
Draw the text surface using that rectangle
You can modify the draw_text function you already have to return that stuff, since it seems to already calculate a bounding rectangle for the text and make a surface for that text as well.

Categories