I've been trying to develop a small shooting game and i'd like the window to shake eveytime the hero gets hit or looses a life, i was thinkingto maybe reposition the window 3 times in a very shot time but im not sure how to implement this and still keep the game running.
Here is my code for my main game loop:
def game():
#set screen
width = 800
height = 600
pygame.init()
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption('UoN Invaders: Game')
background = pygame.Surface(screen.get_size())
background = background.convert()
background.fill((000, 000, 000))
screen.blit(background, (0, 0))
pygame.display.flip()
#load music with help of helpers.py
music = pygame.mixer.music.load ("data/spacequest.mp3")
pygame.mixer.music.play(-1)
global clock, player, playerSprite, enemySprites, enemiestocreat
global enemiesset, lvl2, laserSprites, enemyExplosion, playerExplosion, explosionSprites
clock = pygame.time.Clock()
i = 0 #setting i that define if the game is just starting of in the middle of the game
space1 = Space1(i)
space2 = Space2()
player = Player()
space1 = pygame.sprite.RenderPlain((space1))
space2 = pygame.sprite.RenderPlain((space2))
playerSprite = pygame.sprite.RenderPlain((player))
enemySprites = pygame.sprite.RenderPlain(())
if lvl2 == False:
enemiestocreat = int(float(enemiesset))
while enemiestocreat != 0:
enemySprites.add(Enemy(enemiestocreat*50))
enemiestocreat -= 1
elif lvl2 == True:
enemiesset = int(float(enemiesset)) * 2
enemiestocreat = enemiesset
while enemiestocreat != 0:
enemySprites.add(Enemy(enemiestocreat*50))
enemiestocreat -= 1
laserSprites = pygame.sprite.RenderPlain(())
enemyExplosion = pygame.sprite.RenderPlain(())
playerExplosion = pygame.sprite.RenderPlain(())
explosionSprites = pygame.sprite.RenderPlain(())
# Main Loop
global gameover, enemydead
while gameover == False:
clock.tick(60)
global lives
font = pygame.font.Font(None,36)
text1 = font.render("Lives:" + str(lives + 1), 1, (250,250,250))
textpos1 = text1.get_rect()
textpos1.centerx = 750
textpos1.centery = 590
global enemieskilled
text2 = font.render("Score: " + str(enemieskilled), 1, (250,250,250))
textpos2 = text2.get_rect()
textpos2.centerx = 55
textpos2.centery = 590
if int(float(enemiesset)) == enemydead:
lvl2 = True
enemydead = 0
lvl2src()
for event in pygame.event.get():
if event.type == KEYDOWN and event.key == K_ESCAPE:
main()
# Update
i += 1
space1.update(i)
space2.update()
player.update()
enemySprites.update()
laserSprites.update()
enemyExplosion.update()
playerExplosion.update()
explosionSprites.update()
screen.blit(background, (0, 0))
# Draw
space1.draw(screen)
space2.draw(screen)
playerSprite.draw(screen)
enemySprites.draw(screen)
laserSprites.draw(screen)
enemyExplosion.draw(screen)
playerExplosion.draw(screen)
explosionSprites.draw(screen)
screen.blit(text1, textpos1)
screen.blit(text2, textpos2)
pygame.display.flip()
while gameover == True:
gameoversrc()
And here is my function where i detect if the hero gets hit:
class Enemy(pygame.sprite.Sprite):
def __init__(self, centerx):
global level
if level%2: #choosing which lecturer depending on the modulus of the level
pygame.sprite.Sprite.__init__(self)
self.image, self.rect = load_image("fse.png", -1)
self.rect = self.image.get_rect()
self.dy = 8
self.reset()
elif level%3:
pygame.sprite.Sprite.__init__(self)
self.image, self.rect = load_image("aps.png", -1)
self.rect = self.image.get_rect()
self.dy = 8
self.reset()
else:
pygame.sprite.Sprite.__init__(self)
self.image, self.rect = load_image("ust.png", -1)
self.rect = self.image.get_rect()
self.dy = 8
self.reset()
def update(self):
self.rect.centerx += self.dx
self.rect.centery += self.dy
#checking if enemies are outside scrren
if self.rect.top > 600:
self.reset()
# Laser Collisions
if pygame.sprite.groupcollide(enemySprites, laserSprites, 1, 1):
explosionSprites.add(EnemyExplosion(self.rect.center))
# Ship Collisions
if pygame.sprite.groupcollide(playerSprite, enemySprites, 0, 1):
global lives
if lives == 0:
explosionSprites.add(PlayerExplosion(self.rect.center))
elif lives != 0:
explosionSprites.add(EnemyExplosion(self.rect.center))
lives -= 1
#randome movement of enemies
def reset(self):
self.rect.bottom = 0
self.rect.centerx = random.randrange(0, 800)
self.dy = random.randrange(5, 10)
self.dx = random.randrange(-2, 2)
A simple solution is to not draw to the screen Surface directly, but to a temporary Surface. Then blit that temporary Surface to the screen Surface.
If you want to shake the screen, simply apply an offset to the position of the temporary Surface while blitting.
To generate that offset, you can make use of a generator function.
Here's a complete example. Note how the screen shakes if the player is hit by a falling rock.
import pygame
from random import randint
from itertools import repeat
pygame.init()
org_screen = pygame.display.set_mode((400, 400))
screen = org_screen.copy()
screen_rect = screen.get_rect()
player = pygame.Rect(180, 180, 20, 20)
def get_rock():
return pygame.Rect(randint(0, 340), 0, 60, 60)
falling = get_rock()
clock = pygame.time.Clock()
# 'offset' will be our generator that produces the offset
# in the beginning, we start with a generator that
# yields (0, 0) forever
offset = repeat((0, 0))
# this function creates our shake-generator
# it "moves" the screen to the left and right
# three times by yielding (-5, 0), (-10, 0),
# ... (-20, 0), (-15, 0) ... (20, 0) three times,
# then keeps yieling (0, 0)
def shake():
s = -1
for _ in xrange(0, 3):
for x in range(0, 20, 5):
yield (x*s, 0)
for x in range(20, 0, 5):
yield (x*s, 0)
s *= -1
while True:
yield (0, 0)
while True:
if pygame.event.get(pygame.QUIT): break
pygame.event.pump()
keys = pygame.key.get_pressed()
if keys[pygame.K_w]: player.move_ip(0, -2)
if keys[pygame.K_a]: player.move_ip(-2, 0)
if keys[pygame.K_s]: player.move_ip(0, 2)
if keys[pygame.K_d]: player.move_ip(2, 0)
player.clamp_ip(screen_rect)
falling.move_ip(0, 4)
org_screen.fill((0, 0, 0))
screen.fill((255,255,255))
pygame.draw.rect(screen, (0,0,0), player)
pygame.draw.rect(screen, (255,0,0), falling)
if player.colliderect(falling):
# if the player is hit by the rock,
# we create a new shake-generator
offset = shake()
falling = get_rock()
if not screen_rect.contains(falling):
falling = get_rock()
clock.tick(100)
# here we draw our temporary surface to the
# screen using the offsets created by the
# generators.
org_screen.blit(screen, next(offset))
pygame.display.flip()
For anyone that is using the Pyscroll library (which enables scrolling maps and a few other things) you can achieve this by calling scroll on the BufferedRenderer with an offset of your choice.
Example:
map_layer.scroll(
(
random.randint(0, your_offset),
random.randint(0, your_offset)
)
)
Related
I want to know how to Display a "You Win" and a picture at the end of the game when my player reaches 2000 score in the game. I also want to randomly display a hint when the player collides with the class Reseta. Below is my current code. Please be patient with me. Thank you!
import pygame
import os
import random
pygame.init()
pygame.display.set_caption("Chimera")
SCREEN_HEIGHT = 576
SCREEN_WIDTH = 936
SCREEN = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
RUNNING = [pygame.transform.scale(pygame.image.load("images/Main1_side_right.png"), (64,64)),
pygame.transform.scale(pygame.image.load("images/Main1_side_right_1.png"), (64,64)),
pygame.transform.scale(pygame.image.load("images/Main1_side_right_2.png"), (64,64)),
pygame.transform.scale(pygame.image.load("images/Main1_side_right_3.png"), (64,64)),
pygame.transform.scale(pygame.image.load("images/Main1_side_right_4.png"), (64,64)),
pygame.transform.scale(pygame.image.load("images/Main1_side_right_5.png"), (64,64)),
pygame.transform.scale(pygame.image.load("images/Main1_side_right_6.png"), (64,64)),
pygame.transform.scale(pygame.image.load("images/Main1_side_right_7.png"), (64,64))]
JUMPING = pygame.transform.scale(pygame.image.load("images/Main1_jump_right.png"), (64,64))
DUCKING = [pygame.transform.scale(pygame.image.load("images/slide3.png"), (64, 64)),
pygame.transform.scale(pygame.image.load("images/slide3.png"), (64,64))]
TREE = [pygame.transform.scale(pygame.image.load("images/Tree_1.png"), (64,140)),
pygame.transform.scale(pygame.image.load("images/Tree_1.png"), (64,140)),
pygame.transform.scale(pygame.image.load("images/Tree_2.png"), (64,140))]
BOX = [pygame.transform.scale(pygame.image.load("images/box1.png"), (110,90)),
pygame.transform.scale(pygame.image.load("images/box2.png"), (110,90)),
pygame.transform.scale(pygame.image.load("images/box3.png"), (110,90))]
SHADOW = [pygame.transform.scale(pygame.image.load("images/Enemy_1.png"), (64,64)),
pygame.transform.scale(pygame.image.load("images/Enemy_2.png"), (64,64)),]
PORTAL = [pygame.transform.scale(pygame.image.load("images/portal_real.png"), (64,128)),
pygame.transform.scale(pygame.image.load("images/portal_real.png"), (64,128)),
pygame.transform.scale(pygame.image.load("images/portal_real.png"), (64,128))]
RESETA = [pygame.transform.scale(pygame.image.load("images/reseta_real.png"), (45,120)),
pygame.transform.scale(pygame.image.load("images/reseta_real.png"), (45,120)),
pygame.transform.scale(pygame.image.load("images/reseta_real.png"), (45,120))]
DRUG = [pygame.transform.scale(pygame.image.load("images/Drug.png"), (45,90)),
pygame.transform.scale(pygame.image.load("images/Drug.png"), (45,90)),
pygame.transform.scale(pygame.image.load("images/Drug.png"), (45,90))]
STANDING = pygame.transform.scale(pygame.image.load("images/Main1_front.png"), (64,64))
BG = pygame.image.load(os.path.join("images", "Background_2.jpg"))
class Boy:
X_POS = 80
Y_POS = 390
Y_POS_DUCK = 430
JUMP_VEL = 8.5
def __init__(self):
self.duck_img = DUCKING
self.run_img = RUNNING
self.jump_img = JUMPING
self.boy_duck = False
self.boy_run = True
self.boy_jump = False
self.step_index = 0
self.jump_vel = self.JUMP_VEL
self.image = self.run_img[0]
self.boy_rect = self.image.get_rect()
self.boy_rect.x = self.X_POS
self.boy_rect.y = self.Y_POS
def update(self, userInput):
if self.boy_duck:
self.duck()
if self.boy_run:
self.run()
if self.boy_jump:
self.jump()
if self.step_index >= 10:
self.step_index = 0
if userInput[pygame.K_UP] and not self.boy_jump:
self.boy_duck = False
self.boy_run = False
self.boy_jump = True
elif userInput[pygame.K_DOWN] and not self.boy_jump:
self.boy_duck = True
self.boy_run = False
self.boy_jump = False
elif not (self.boy_jump or userInput[pygame.K_DOWN]):
self.boy_duck = False
self.boy_run = True
self.boy_jump = False
def duck(self):
self.image = self.duck_img[self.step_index // 5]
self.boy_rect = self.image.get_rect()
self.boy_rect.x = self.X_POS
self.boy_rect.y = self.Y_POS_DUCK
self.step_index += 1
def run(self):
self.image = self.run_img[self.step_index // 5]
self.boy_rect = self.image.get_rect()
self.boy_rect.x = self.X_POS
self.boy_rect.y = self.Y_POS
self.step_index += 1
def jump(self):
self.image = self.jump_img
if self.boy_jump:
self.boy_rect.y -= self.jump_vel * 4
self.jump_vel -= 0.8
if self.jump_vel < - self.JUMP_VEL:
self.boy_jump = False
self.jump_vel = self.JUMP_VEL
def draw(self, SCREEN):
SCREEN.blit(self.image, (self.boy_rect.x, self.boy_rect.y))
class Obstacle:
def __init__(self, image, type):
self.image = image
self.type = type
self.rect = self.image[self.type].get_rect()
self.rect.x = SCREEN_WIDTH
def update(self):
self.rect.x -= game_speed
if self.rect.x < -self.rect.width:
obstacles.pop()
def draw(self, SCREEN):
SCREEN.blit(self.image[self.type], self.rect)
class Box(Obstacle):
def __init__(self, image):
self.type = random.randint(0, 2)
super().__init__(image, self.type)
self.rect.y = 380
class Tree(Obstacle):
def __init__(self, image):
self.type = random.randint(0, 2)
super().__init__(image, self.type)
self.rect.y = 325
class Shadow(Obstacle):
def __init__(self, image):
self.type = 0
super().__init__(image, self.type)
self.rect.y = 390
self.index = 0
def draw(self, SCREEN):
if self.index >= 9:
self.index = 0
SCREEN.blit(self.image[self.index//5], self.rect)
self.index += 1
class Drug(Obstacle):
def __init__(self, image):
self.type = random.randint(0, 2)
super().__init__(image, self.type)
self.rect.y = 325
class Portal(Obstacle):
def __init__(self, image):
self.type = random.randint(0, 2)
super().__init__(image, self.type)
self.rect.y = 300
class Reseta(Obstacle):
def __init__(self, image):
self.type = random.randint(0, 2)
super().__init__(image, self.type)
self.rect.y = 350
def main():
global game_speed, x_pos_bg, y_pos_bg, points, obstacles
run = True
clock = pygame.time.Clock()
player = Boy()
# cloud = Cloud()
game_speed = 10
x_pos_bg = 0
y_pos_bg = 0
points = 0
font = pygame.font.Font('freesansbold.ttf', 20)
obstacles = []
death_count = 0
def score():
global points, game_speed
points += 1
if points % 500 == 0:
game_speed += 1
text = font.render("Points: " + str(points), True, (0, 0, 0))
textRect = text.get_rect()
textRect.center = (850, 30)
SCREEN.blit(text, textRect)
def background():
global x_pos_bg, y_pos_bg
image_width = BG.get_width()
SCREEN.blit(BG, (x_pos_bg, y_pos_bg))
SCREEN.blit(BG, (image_width + x_pos_bg, y_pos_bg))
if x_pos_bg <= -image_width:
SCREEN.blit(BG, (image_width + x_pos_bg, y_pos_bg))
x_pos_bg = 0
x_pos_bg -= game_speed
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
SCREEN.fill((255, 255, 255))
userInput = pygame.key.get_pressed()
background()
player.draw(SCREEN)
player.update(userInput)
if len(obstacles) == 0:
if random.randint(0, 2) == 0:
obstacles.append(Box(BOX))
elif random.randint(0, 2) == 1:
obstacles.append(Tree(TREE))
elif random.randint(0, 2) == 2:
obstacles.append(Shadow(SHADOW))
elif random.randint(0, 2) == 0:
obstacles.append(Portal(PORTAL))
elif random.randint(0, 2) == 0:
obstacles.append(Reseta(RESETA))
elif random.randint(0, 2) == 0:
obstacles.append(Drug(DRUG))
for obstacle in obstacles:
obstacle.draw(SCREEN)
obstacle.update()
if player.boy_rect.colliderect(obstacle.rect):
pygame.time.delay(2000)
death_count += 1
menu(death_count)
score()
clock.tick(30)
pygame.display.update()
def menu(death_count):
global points
run = True
while run:
# SCREEN.fill((255, 255, 255))
SCREEN.blit(BG, (0,0))
font = pygame.font.Font('freesansbold.ttf', 30)
if death_count == 0:
text = font.render("Press any Key to Start", True, (250, 245, 225))
save = font.render("Score 1000 to save the Girl", True, (250, 245, 225))
saveRect = save.get_rect()
saveRect.center = (SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2 + 50)
SCREEN.blit(save, saveRect)
elif death_count > 0:
text = font.render("Press any Key to Restart", True, (250, 245, 225))
score = font.render("Your Score: " + str(points), True, (250, 245, 225))
scoreRect = score.get_rect()
scoreRect.center = (SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2 + 50)
SCREEN.blit(score, scoreRect)
textRect = text.get_rect()
textRect.center = (SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2)
SCREEN.blit(text, textRect)
SCREEN.blit(STANDING, (SCREEN_WIDTH // 2 - 20, SCREEN_HEIGHT // 2 - 140))
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
pygame.quit()
if event.type == pygame.KEYDOWN:
main()
menu(death_count=0)
below is the file for the folder of images used in my game.
https://drive.google.com/file/d/1t_kDNw3G1Q6X4KKZ9IfsCmYKpEecz9Ci/view?usp=sharing
There is a very simple way that you can have a "You Win" show up in your game when the score reaches 200. You would need a variable for the score that increases every time something happens. First, you would have to load an image for the "You Win" by doing pygame.image.load(file name.png) then you would have to assign variables for the x-axis and y-axis of the image (I used You_WinX and You_WinY for the example) then you can simply do this:
if score == 2000:
You_WinX = (location on x-axis)
You_WinY = (location in y-axis)
What this would do is when the score reaches the value of 2000, the image of "You Win" will appear where you want it to be on the screen (x,y)
I created a little exemple for you. The only thing you have to remember is the purpose of the method main_loop() contained in my class Game (comments will help you to understand it). Just remember that you add several while loops that depends on a variable you will change in order to change state of the game. Each loop print out different things according to what is its goal.
For the point to reach, just create an invisible rect and check if your player rect collide with the invisible one. If it does, switch your variables in order to get into another loop that will print out something else than your game (in this case you could print out "You won".
For the score, you could add score every time the player does something and check every frame if the score exceed the score you have set to win. In this case, just switch variables in order to change state of the game.
import pygame
# creating screen
screen = pygame.display.set_mode((1000, 500))
class Player(pygame.sprite.Sprite):
"""Defining a little class just to show the player on the screen"""
def __init__(self):
# initialize super class (pygame.sprite.Sprite)
super().__init__()
# defining rect of the player
self.rect = pygame.Rect((100, 100), (100, 100))
self.color = (255, 0, 0)
def move_right(self):
self.rect.x += 20
def show_player(self):
pygame.draw.rect(screen, self.color, self.rect)
class Game:
"""Defining the game class that contains the main loop and main variables"""
def __init__(self):
# defining variables for game loops
self.running = True
self.end_menu = False
self.game = True
# initialising player class
self.pl = Player()
# creating an invisible rect that the player has to reach
self.reach_point = pygame.Rect((500, 100), (100, 100))
def main_loop(self):
"""The goal here is to create several loops. One will be for the main game loop that will contains
the two other loops (as many as you want), when an event you chose will happens, the variable that makes
the loop run will turn on false and the variable that makes the loop of the other stage you want to reach
will turn on true. So you will constantly run a loop because your main loop will end up only if you quit the
game."""
while self.running:
while self.game:
for event in pygame.event.get():
if event.type == pygame.QUIT:
self.running = False
self.game = False
if event.type == pygame.KEYDOWN:
# defining just a key for the example
if event.key == pygame.K_d:
self.pl.move_right()
# detecting if the player reach the invisible rect
if self.pl.rect.colliderect(self.reach_point):
self.game = False
self.end_menu = True
# fill the screen in white
screen.fill((255, 255, 255))
# shows the player
self.pl.show_player()
# update the screen
pygame.display.flip()
while self.end_menu:
for event in pygame.event.get():
if event.type == pygame.QUIT:
self.running = False
self.end_menu = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_p:
self.game = True
self.end_menu = False
# fills the screen in order to see the different states of the game
screen.fill((255, 255, 0))
# update the screen
pygame.display.flip()
# initializing the class game
game = Game()
pygame.init()
# calling function `main_loop()` contained in the class Game (initialised as game)
game.main_loop()
pygame.quit()
I am making a game with Pygame. For this game I need to be able to detect not only that two rectangles have collided, but also the point of collision between them. I looked at the documentation but couldn't seem to find any answers.
Is something like this possible?
You can use Rect.clip:
crops a rectangle inside another
clip(Rect) -> Rect
Returns a new rectangle that is cropped to be completely inside the argument Rect. If the two rectangles do not overlap to begin with, a Rect with 0 size is returned.
Here's an example:
import pygame
import random
class Stuff(pygame.sprite.Sprite):
def __init__(self, pos, color, *args):
super().__init__(*args)
self.image = pygame.Surface((30, 30))
self.image.fill(color)
self.rect = self.image.get_rect(center=pos)
self.pos = pygame.Vector2(pos)
def update(self):
self.rect.center = self.pos
def main():
pygame.init()
screen = pygame.display.set_mode((500, 500))
screen_rect = screen.get_rect()
font = pygame.font.SysFont(None, 26)
clock = pygame.time.Clock()
sprites = pygame.sprite.Group()
blocks = pygame.sprite.Group()
movement = {
pygame.K_UP: ( 0, -1),
pygame.K_DOWN: ( 0, 1),
pygame.K_LEFT: (-1, 0),
pygame.K_RIGHT: ( 1, 0)
}
for _ in range(15):
x, y = random.randint(0, 500), random.randint(0, 500)
color = random.choice(['green', 'yellow'])
Stuff((x, y), pygame.Color(color), sprites, blocks)
player = Stuff(screen_rect.center, pygame.Color('dodgerblue'))
sprites.add(player)
dt = 0
while True:
events = pygame.event.get()
for e in events:
if e.type == pygame.QUIT:
return
pressed = pygame.key.get_pressed()
move = pygame.Vector2()
for dir in (movement[key] for key in movement if pressed[key]):
move += dir
if move.length() > 0: move.normalize_ip()
player.pos += move * dt/5
sprites.update()
screen.fill(pygame.Color('black'))
sprites.draw(screen)
for block in pygame.sprite.spritecollide(player, blocks, False):
clip = player.rect.clip(block.rect)
pygame.draw.rect(screen, pygame.Color('red'), clip)
hits = [edge for edge in ['bottom', 'top', 'left', 'right'] if getattr(clip, edge) == getattr(player.rect, edge)]
text = font.render(f'Collision at {", ".join(hits)}', True, pygame.Color('white'))
screen.blit(text, (20, 20))
pygame.display.flip()
dt = clock.tick(60)
if __name__ == '__main__':
main()
First post here. So I am trying to implement a Civilization type of movement game. At the moment, I have one sprite in a cell. I can click it and then if I click another grid, the sprite moves there. What I now want is to spawn 5-6 such sprites, and then do the same thing. Click on a sprite and then click another grid, and that specific sprite moves there without affecting the other sprites. I cannot seem to do that. I can spawn 5-6 random sprites at different grids, but when I click on one of them and then click another grid, all the other sprites are gone. The code is below (not the best as I am learning Pygame). I understand that I have to somehow only update the sprite that was clicked, but I am not sure how to do that.
import pygame
import random
WIDTH = 900
HEIGHT = 700
FPS = 2
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
TURN = "TeamOne"
def main():
# Pygame sprite Example
global x_lines
global y_lines
x_lines = [WIDTH-i*WIDTH/20 for i in range(20,0, -1)]
y_lines = [HEIGHT-j*HEIGHT/20 for j in range(20,0, -1)]
class TeamOne(pygame.sprite.Sprite):
# sprite for the Player
def __init__(self):
# this line is required to properly create the sprite
pygame.sprite.Sprite.__init__(self)
# create a plain rectangle for the sprite image
self.image = pygame.Surface((WIDTH / 20, HEIGHT / 20))
self.image.fill(GREEN)
# find the rectangle that encloses the image
self.rect = self.image.get_rect()
# center the sprite on the screen
self.rect.center = ((random.randint(1,19)*2+1)* WIDTH/ 40, (random.randint(1,19)*2+1)*HEIGHT/40)
def update(self, position):
# any code here will happen every time the game loop updates
(a, b) = position
for index, i in enumerate(x_lines):
if i > a:
self.rect.x = x_lines[index-1]
break
for index, j in enumerate(y_lines):
if j > b:
self.rect.y = y_lines[index-1]
break
# initialize pygame and create window
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("A Game")
clock = pygame.time.Clock()
clicked_sprites = pygame.sprite.Group()
teamone_sprites = pygame.sprite.Group()
for i in range(5):
mob1 = TeamOne()
teamone_sprites.add(mob1)
# Game loop
running = True
j=0
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
elif event.type == pygame.MOUSEBUTTONDOWN and j == 0:
pos = pygame.mouse.get_pos()
for s in teamone_sprites:
if s.rect.collidepoint(pos):
#teamone_sprites.add(s)
clicked_sprites.add(s)
print (clicked_sprites)
j = 1
elif event.type == pygame.MOUSEBUTTONDOWN and j == 1:
new_pos = pygame.mouse.get_pos()
#teamone_sprites.update(new_pos)
clicked_sprites.update(new_pos)
j = 0
# Update
# Draw / render
## screen.fill(BLACK)
## draw_grid(screen)
##
## teamone_sprites.draw(screen)
##
##
##
## # *after* drawing everything, flip the display
## pygame.display.flip()
# Draw / render
screen.fill(BLACK)
draw_grid(screen)
teamone_sprites.draw(screen)
pygame.display.flip()
pygame.quit()
def draw_grid(screen):
for i in range(1, HEIGHT, int(HEIGHT/20)):
pygame.draw.line(screen, GREEN, (1,i) ,(WIDTH,i), 2)
for j in range(1, WIDTH, int(WIDTH/20)):
pygame.draw.line(screen, GREEN, (j,1) ,(j,HEIGHT), 2)
if __name__ == '__main__':
main()
Some tips for you:
Keep your main loop clean
Put logic where it belongs
Only call pygame.display.flip()/pygame.display.update() once
Don't use variable names like j
Since your game is grid based, you should have a way to translate between grid coordinates and screen coordinates
Here's a simple runnable example I hacked together (see the comments for some explanations):
import pygame
import random
WIDTH = 900
HEIGHT = 700
ROWS = 20
COLUMNS = 20
TILE_SIZE = WIDTH / COLUMNS, HEIGHT / ROWS
TILE_W, TILE_H = TILE_SIZE
FPS = 60
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
TURN = "TeamOne"
# some functions to translate grid <-> screen coordinates
def posToScreen(pos):
column, row = pos
return column * TILE_W, row * TILE_H
def screenToPos(pos):
column, row = pos
return column / TILE_W, row / TILE_H
def draw_grid(screen):
for i in range(1, HEIGHT, TILE_H):
pygame.draw.line(screen, GREEN, (1,i) ,(WIDTH,i), 2)
for j in range(1, WIDTH, TILE_W):
pygame.draw.line(screen, GREEN, (j,1) ,(j,HEIGHT), 2)
# a class that handles selecting units
class Cursor(pygame.sprite.Sprite):
def __init__(self, units, *groups):
pygame.sprite.Sprite.__init__(self, *groups)
# group of the units that can be controlled
self.units = units
# we create two images
# to indicate if we are selecting or moving
self.image = pygame.Surface(TILE_SIZE)
self.image.set_colorkey((43,43,43))
self.image.fill((43,43,43))
self.rect = self.image.get_rect()
self.selected_image = self.image.copy()
pygame.draw.rect(self.image, pygame.Color('red'), self.image.get_rect(), 4)
pygame.draw.rect(self.selected_image, pygame.Color('purple'), self.image.get_rect(), 4)
self.base_image = self.image
self.selected = None
def update(self):
# let's draw the rect on the grid, based on the mouse position
pos = pygame.mouse.get_pos()
self.rect.topleft = posToScreen(screenToPos(pos))
def handle_click(self, pos):
if not self.selected:
# if we have not selected a unit, do it now
for s in pygame.sprite.spritecollide(self, self.units, False):
self.selected = s
self.image = self.selected_image
else:
# if we have a unit selected, just set its target attribute, so it will move on its own
self.selected.target = posToScreen(screenToPos(pos))
self.image = self.base_image
self.selected = None
class TeamOne(pygame.sprite.Sprite):
def __init__(self, *groups):
pygame.sprite.Sprite.__init__(self, *groups)
self.image = pygame.Surface(TILE_SIZE)
self.image.fill(GREEN)
self.pos = random.randint(0, COLUMNS), random.randint(0, ROWS)
self.rect = self.image.get_rect(topleft = posToScreen(self.pos))
self.target = None
def update(self):
# do nothing until target is set
# (maybe unset it if we reached our target)
if self.target:
if self.rect.x < self.target[0]:
self.rect.move_ip(1, 0)
elif self.rect.x > self.target[0]:
self.rect.move_ip(-1, 0)
elif self.rect.y < self.target[1]:
self.rect.move_ip(0, 1)
elif self.rect.y > self.target[1]:
self.rect.move_ip(0, -1)
self.pos = screenToPos(self.rect.topleft)
def main():
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("A Game")
clock = pygame.time.Clock()
all_sprites = pygame.sprite.LayeredUpdates()
team_ones = pygame.sprite.Group()
for i in range(5):
TeamOne(all_sprites, team_ones)
cursor = Cursor(team_ones, all_sprites)
# a nice, simple, clean main loop
running = True
while running:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# we could also pass all events to all sprites
# so we would not need this special clause for the cursor...
if event.type == pygame.MOUSEBUTTONDOWN:
cursor.handle_click(event.pos)
all_sprites.update()
screen.fill(BLACK)
draw_grid(screen)
all_sprites.draw(screen)
pygame.display.flip()
if __name__ == '__main__':
main()
I have pretty much the same Problem i have a healthbar for my enemie but i want all enemys to have one so its a spritegroup now if i want to change an attribute of one object out of my spritegroup i dont know how to properly access it. The Problem lays in the Healthbaranimation function. I tried self.healthbar.sprites() self.healthbar.sprites and spritedict nothing really semms to work. Is there an easy way to fix this? P.s sorry for my bad code It is my first real attempt making a small game
from os import path
import pygame
from elements.ammo import AMMO
from elements.bigenemy import BIGENEMY
from elements.enemy import ENEMY
from elements.player import PLAYER
from .base import BaseState
from elements.healthbar import HEALTHBAR
class Gameplay(BaseState):
def __init__(self):
super(Gameplay, self).__init__()
self.next_state = "GAME_OVER"
self.x, self.y = 100, 1030
self.playersprite = PLAYER((self.x, self.y))
self.bigenemy = pygame.sprite.GroupSingle(BIGENEMY())
self.bottomrect = pygame.Rect((0, 1030), (1920, 50))
self.enemysprite = ENEMY()
self.ammosprite = AMMO()
self.healthbar = pygame.sprite.Group(HEALTHBAR())
self.displayedimage = self.playersprite.image
self.displayedrect = self.playersprite.rect
self.highscore = self.load_data()
self.points = 0
self.scoretext = f"SCORE: {self.points}"
self.scoresurf = self.font.render(self.scoretext, True, "red")
self.nhstext = "NEW HIGHSCORE!"
self.nhssurf = self.font.render(self.nhstext, True, "red")
self.ammotext = f"AMMO:{self.playersprite.ammunition}"
self.ammosurf = self.font.render(self.ammotext, True, "red")
self.bulletgroup = pygame.sprite.Group()
self.time_active = 0
self.bigenemyexisting = True
def get_event(self, event):
if event.type == pygame.QUIT:
self.quit = True
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LCTRL:
self.playersprite.crouching = True
elif event.key == pygame.K_SPACE:
self.playersprite.jumping = True
elif event.key == pygame.K_q and self.playersprite.ammunition != 0:
self.playersprite.shooting = True
elif event.type == pygame.KEYUP:
if event.key == pygame.K_ESCAPE:
self.done = True
elif event.key == pygame.K_LCTRL:
self.playersprite.crouching = False
elif event.key == pygame.K_q:
self.playersprite.shooting = False
def draw(self, surface):
surface.fill(pygame.Color("black"))
pygame.draw.rect(surface, "red", self.bottomrect)
surface.blit(self.displayedimage, (self.displayedrect))
surface.blit(self.enemysprite.image, (self.enemysprite.rect))
surface.blit(self.ammosprite.image, (self.ammosprite.rect))
self.healthbar.draw(surface)
self.bigenemy.draw(surface)
self.bulletgroup.draw(surface)
surface.blit(self.scoresurf, (0, 0))
surface.blit(self.ammosurf, (0, 1000))
if self.points > self.highscore: surface.blit(self.nhssurf, (1920 / 2 - 100, 1080 / 2))
def lost(self):
self.enemysprite.startposx = 1920
self.enemysprite.startposy = self.enemysprite.gettypeenemy()
self.enemysprite.speed = 10
self.highscorefunc()
self.points = 0
self.playersprite.ammunition = 30
def collidecheck(self):
self.playermask = pygame.mask.from_surface(self.displayedimage)
self.enemymask = pygame.mask.from_surface(self.enemysprite.image)
offsetx = self.enemysprite.rect.left - self.displayedrect.left
offsety = self.enemysprite.rect.top - self.displayedrect.top
if self.displayedrect.colliderect(self.enemysprite.rect):
if self.playermask.overlap(self.enemymask, (offsetx, offsety)):
self.lost()
self.done = True
elif self.enemysprite.rect.x < 0 and self.enemysprite.speed < 25:
self.points += 1
self.enemysprite.speed += 1
elif self.enemysprite.speed > 25:
self.enemysprite.speed += .5
elif self.displayedrect.colliderect(self.ammosprite.rect):
self.ammosprite.startposx = 2300
self.playersprite.ammunition += 30
elif pygame.sprite.groupcollide(self.bigenemy,self.bulletgroup,False,True):
self.bigenemy.sprite.health -= 10
def shooting(self, dt):
if self.playersprite.ammunition != 0:
if self.playersprite.shooting and not self.playersprite.jumping and not self.playersprite.crouching:
self.time_active += dt
if self.time_active >= 100:
self.bulletgroup.add(self.playersprite.createbullet())
self.time_active = 0
self.playersprite.ammunition -= 1
else:
self.playersprite.shooting = False
def highscorefunc(self):
if self.points > self.highscore:
self.highscore = self.points
with open(path.join(self.dir, self.HS_FILE), 'w') as f:
f.write(str(self.highscore))
def animation(self):
if not self.playersprite.shooting and not self.playersprite.jumping and not self.playersprite.crouching:
if self.playersprite.index >= len(self.playersprite.basicanimation):
self.playersprite.index = 0
self.displayedimage = self.playersprite.basicanimation[int(self.playersprite.index)]
self.playersprite.index += .1
elif self.playersprite.shooting and not self.playersprite.jumping:
if self.playersprite.index >= len(self.playersprite.shootanimation):
self.playersprite.index = 0
self.displayedimage = self.playersprite.shootanimation[int(self.playersprite.index)]
self.playersprite.index += .1
elif self.playersprite.jumping:
self.displayedimage = self.playersprite.imagejump
elif self.playersprite.crouching:
self.displayedimage = self.playersprite.slidingimage
def healthbaranimation(self):
if self.bigenemy.sprite.health < 90:
self.healthbar.spritedict.index = 1
if self.bigenemy.sprite.health < 80:
self.healthbar.sprite.index = 2
if self.bigenemy.sprite.health < 70:
self.healthbar.sprite.index = 3
if self.bigenemy.sprite.health < 60:
self.healthbar.sprite.index = 4
if self.bigenemy.sprite.health < 50:
self.healthbar.sprite.index = 5
if self.bigenemy.sprite.health < 40:
self.healthbar.sprite.index = 6
if self.bigenemy.sprite.health < 30:
self.healthbar.sprite.index = 7
if self.bigenemy.sprite.health < 20:
self.healthbar.sprite.index = 8
if self.bigenemy.sprite.health < 10:
self.healthbar.sprite.index = 9
def spawnbigenemies(self):
if self.bigenemyexisting:
if self.bigenemy.sprite.health < 3:
self.bigenemy.add(BIGENEMY())
self.bigenemyexisting = True
def update(self, dt):
try:
self.bigenemy.sprite.update()
except:
pass
self.healthbaranimation()
self.healthbar.update()
self.playersprite.jump()
self.animation()
self.shooting(dt)
self.bulletgroup.update()
self.enemysprite.update()
self.ammosprite.update()
self.collidecheck()
self.spawnbigenemies()
self.scoretext = f"SCORE: {self.points}"
self.scoresurf = self.font.render(self.scoretext, True, "black")
self.ammotext = f"AMMO:{self.playersprite.ammunition}"
self.ammosurf = self.font.render(self.ammotext, True, "red")
I am trying to find a certain sprite in a collision group. In this case, My code checks every platform to see if the player is touching it. If the player is touching the platform, I want the player's bottom y to become the platform's (that the player is touching) top y. I do not know how to grab a certain platform, and edit the attributes of that one. How would I edit my code to make this work?
import pygame
import random
WIDTH = 500
HEIGHT = 400
FPS = 30
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
playerImage = "blockBandit/BlockBandit.png"
class Player(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface((50, 50))
self.image = pygame.image.load(playerImage).convert()
self.rect = self.image.get_rect()
self.rect.center = (WIDTH / 2, HEIGHT / 2)
self.vx = 0
self.vy = 0
class Platform(pygame.sprite.Sprite):
def __init__(self, x, y, w, h):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface((w, h))
self.image.fill(GREEN)
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
pygame.init()
pygame.mixer.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Block Bandit")
clock = pygame.time.Clock()
allPlatforms = pygame.sprite.Group()
all_sprites = pygame.sprite.Group()
player = Player()
p1 = Platform(0, HEIGHT - 40, WIDTH, 40)
all_sprites.add(p1)
allPlatforms.add(p1)
all_sprites.add(player)
def moveCharacter(object):
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
object.vx += -2
if keys[pygame.K_RIGHT]:
object.vx += 2
if keys[pygame.K_UP]:
object.vy -= 12
pygame.quit()
object.vx = object.vx * 0.9
if abs(object.vx) < 1:
object.vx = 0
if abs(object.vx) > 10:
if object.vx < 0:
object.vx = -10
else:
object.vx = 10
object.vy = object.vy + 1
object.rect.x += object.vx
object.rect.y += object.vy
hits = pygame.sprite.spritecollide(object, allPlatforms, False)
if hits:
# object.rect.y = hits[0].rect.midbottom
object.rect.y -= 1
object.vy = 0
if object.rect.bottom < allPlatforms.top:
object.rect.y = allPlatforms.top
print(object.rect.midbottom)
running = True
while running:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
moveCharacter(player)
# Update State
all_sprites.update()
# Render
screen.fill(BLACK)
all_sprites.draw(screen)
# screen.blit(player.icon, (20, 40))
pygame.display.flip()
pygame.quit()
hits is a list of the colliding platform sprites, so you can iterate over it with a for loop and set the object.rect.bottom to the platform.rect.top.
hits = pygame.sprite.spritecollide(object, allPlatforms, False)
for platform in hits:
object.vy = 0
object.rect.bottom = platform.rect.top
this is my game right now but for some reason i keep getting a
PYTHON GAME.py", line 319, in <module>
blocks_hit_list = pygame.sprite.spritecollide(player, block_list, True)
File "C:\Python33\lib\site-packages\pygame\sprite.py", line 1515, in spritecollide
if spritecollide(s.rect):
AttributeError: 'Rocket' object has no attribute 'rect'
error. I have no idea why and ive tried alot of stuff to get it to work.
This stupid thing keeps saying i have to much code so i wrote this sentance to take up room
import pygame
import random
"""
Global constants
"""
# Colors
BLACK = ( 0, 0, 0)
WHITE = ( 255, 255, 255)
BLUE = ( 0, 0, 255)
BLACK = [ 0, 0, 0]
WHITE = [255, 255, 255]
black = [ 0,0,0]
white=[255,255,255]
green = ( 0, 255, 0)
red = ( 255, 0, 0)
BLUE = ( 0, 0, 255)
lightblue= ( 0, 255, 255)
brown =( 97, 66, 12)
yellow =(232,232,74)
grey=(148,148,148)
purple=(124,102,196)
yellow2 =(252,252,0)
yellow3 =(252,252,0)
red2=(255,0,0)
brown2 =(51,32,5)
orange = (255,119,0)
a=random.randrange(0,255,1)
b=random.randrange(0,255,1)
c=random.randrange(0,255,1)
#color=(a,b,c)
score=0
x=50
#game_sound = pygame.mixer.Sound("nunu_nights.wav")
# Screen dimensions
SCREEN_WIDTH = 1000
SCREEN_HEIGHT = 700
# This class represents the bar at the bottom that the player controls
class Player(pygame.sprite.Sprite):
""" This class represents the bar at the bottom that the player controls. """
# Set speed vector
change_x = 0
change_y = 0
walls = None
# Constructor function
def __init__(self, x, y):
# Call the parent's constructor
pygame.sprite.Sprite.__init__(self)
# Set height, width
self.image = pygame.Surface([15, 15])
self.image.fill(WHITE)
# Make our top-left corner the passed-in location.
self.rect = self.image.get_rect()
self.rect.y = y
self.rect.x = x
def changespeed(self, x, y):
""" Change the speed of the player. """
self.change_x += x
self.change_y += y
def update(self):
""" Update the player position. """
# Move left/right
self.rect.x += self.change_x
# Did this update cause us to hit a wall?
block_hit_list = pygame.sprite.spritecollide(self, self.walls, False)
for block in block_hit_list:
# If we are moving right, set our right side to the left side of the item we hit
if self.change_x > 0:
self.rect.right = block.rect.left
else:
# Otherwise if we are moving left, do the opposite.
self.rect.left = block.rect.right
# Move up/down
self.rect.y += self.change_y
# Check and see if we hit anything
block_hit_list = pygame.sprite.spritecollide(self, self.walls, False)
for block in block_hit_list:
# Reset our position based on the top/bottom of the object.
if self.change_y > 0:
self.rect.bottom = block.rect.top
else:
self.rect.top = block.rect.bottom
class Wall(pygame.sprite.Sprite):
""" Wall the player can run into. """
def __init__(self, x, y, width, height):
""" Constructor for the wall that the player can run into. """
# Call the parent's constructor
pygame.sprite.Sprite.__init__(self)
# Make a black wall, of the size specified in the parameters
self.image = pygame.Surface([width, height])
self.image.fill(BLACK)
# Make our top-left corner the passed-in location.
self.rect = self.image.get_rect()
self.rect.y = y
self.rect.x = x
class Rocket(pygame.sprite.Sprite):
""" Rocket Class. """
x=0
y=0
change_x=0
change_y=0
size=10
color=[255, 0, 0]
def move(self):
self.x+=self.change_x
self.y+=self.change_y
def draw(self,screen):
pygame.draw.circle(screen,self.color,[self.x,self.y], self.size)
# Call this function so the Pygame library can initialize itself
pygame.init()
# Create an 800x600 sized screen
screen = pygame.display.set_mode([SCREEN_WIDTH, SCREEN_HEIGHT])
# Set the title of the window
pygame.display.set_caption('ROCKETS EVERYWHERE!!')
all_sprite_list = pygame.sprite.Group()
# Create an empty array
rocket_list = []
# Loop 50 times and add a rocket in a random x,y position
for i in range(100):
x = random.randrange(0, 1000)
y = random.randrange(0, 700)
rocket_list.append([x, y])
rect_x = 50
rect_y = 50
# Speed and direction of rectangle
rect_change_x = 5
rect_change_y = 5
# This is a font we use to draw text on the screen (size 36)
font = pygame.font.Font(None, 36)
# List to hold all the sprites
all_sprite_list = pygame.sprite.Group()
# Make the walls. (x_pos, y_pos, width, height)
wall_list = pygame.sprite.Group()
wall = Wall(0, 0, 10, 800)
wall_list.add(wall)
all_sprite_list.add(wall)
wall = Wall(10, 0, 1000, 10)
wall_list.add(wall)
all_sprite_list.add(wall)
wall = Wall(990, 0, 10, 800)
wall_list.add(wall)
all_sprite_list.add(wall)
wall = Wall(0, 690, 1000, 10)
wall_list.add(wall)
all_sprite_list.add(wall)
block_list = pygame.sprite.Group()
all_sprites_list = pygame.sprite.Group()
# Create the player object
player = Player(500, 600)
player.walls = wall_list
for i in range(50):
enemyRocket1 = Rocket()
enemyRocket1.change_x=2
enemyRocket1.change_y=2
enemyRocket1.color=[a,b,c]
enemyRocket1.x=random.randrange(0,1000,1)
enemyRocket1.y=random.randrange(0,700,1)
block_list.add(enemyRocket1)
all_sprites_list.add(enemyRocket1)
'''
enemyRocket2 = Rocket()
enemyRocket2.x=50
enemyRocket2.y=0
enemyRocket2.change_x=0
enemyRocket2.change_y=10
enemyRocket2.color=[a,b,c]
'''
all_sprite_list.add(player)
clock = pygame.time.Clock()
display_instructions = True
instruction_page = 1
done= False
# -------- Instruction Page Loop -----------
while done==False and display_instructions:
for event in pygame.event.get(): # User did something
if event.type == pygame.QUIT: # If user clicked close
done=True # Flag that we are done so we exit this loop
if event.type == pygame.MOUSEBUTTONDOWN:
instruction_page += 1
if instruction_page == 3:
display_instructions = False
# Set the screen background
screen.fill(black)
if instruction_page == 1:
# Draw instructions, page 1
# This could also load an image created in another program.
# That could be both easier and more flexible.
#random.play()
#screen.blit(title_intro, [0,0])
text=font.render("ROCKETS EVERYWHERE!!", True, white)
screen.blit(text, [10, 10])
text=font.render("Click mouse to see the instructions", True, white)
screen.blit(text, [10, 40])
if instruction_page == 2:
# Draw instructions, page 2
text=font.render("The objective of the game is to dodge rockets", True, white)
screen.blit(text, [10, 10])
text=font.render("Use the Arrow keys to move around the screen", True, white)
screen.blit(text, [10, 40])
# Limit to 20 frames per second
clock.tick(20)
# Go ahead and update the screen with what we've drawn.
pygame.display.flip()
#------------------------
#MAIN PROGRAM LOOP
#------------------------
done = False
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
# Set the speed based on the key pressed
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
player.changespeed(-14, 0)
elif event.key == pygame.K_RIGHT:
player.changespeed(14, 0)
elif event.key == pygame.K_UP:
player.changespeed(0, -7)
elif event.key == pygame.K_DOWN:
player.changespeed(0, 7)
# Reset speed when key goes up
elif event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT:
player.changespeed(14, 0)
elif event.key == pygame.K_RIGHT:
player.changespeed(-14, 0)
elif event.key == pygame.K_UP:
player.changespeed(0, 7)
elif event.key == pygame.K_DOWN:
player.changespeed(0, -7)
all_sprite_list.update()
player.update()
screen.fill(BLACK)
all_sprite_list.draw(screen)
#The score
text=font.render("Score="+str(score), True, white)
screen.blit(text, [10, 10])
a=random.randrange(0,255,1)
b=random.randrange(0,255,1)
c=random.randrange(0,255,1)
color=(a,b,c)
enemyRocket1.move()
enemyRocket1.draw(screen)
blocks_hit_list = pygame.sprite.spritecollide(player, block_list, True)
# Check the list of collisions.
for block in blocks_hit_list:
score+=99999999999
if score>x:
x+=100
for i in range(len(rocket_list)):
# Draw the rocket
pygame.draw.circle(screen, WHITE, rocket_list[i], 2)
# Move the rocket down one pixel
rocket_list[i][1] += 10
# If the rocket has moved off the bottom of the screen
if rocket_list[i][1] > 700:
# Reset it just above the top
y = random.randrange(-50, -10)
rocket_list[i][1] = y
# Give it a new x position
x = random.randrange(0, 1000)
rocket_list[i][0] = x
score+=1
# Go ahead and update the screen with what we've drawn.
pygame.display.flip()
clock.tick(40)
pygame.quit ()
As the error message suggests, you are trying to access the attribute rect of a Rocket.
Looking at your Rocket class, Rocket objects indeed have no such attribute.