Deleting/Duplicating an instance of a class when there are many - python

I am trying to delete the dots outside of the safe zone but so far the only solution I have found is to not draw them, which is not what I want since using this method they still exist. Is there anyway to delete the specific dots outside of this region? Is there also a way to create a duplicate of an instance?
import pygame
import sys
import random
pygame.init()
win = pygame.display.set_mode((800,600))
pygame.display.set_caption("Simulation")
class Dot:
def __init__(self):
self.spawnX = random.randrange(0, 800)
self.spawnY = random.randrange(0, 600)
self.r = random.randrange(0, 256)
self.g = random.randrange(0, 256)
self.b = random.randrange(0, 256)
self.vel = [None] * 0
self.spd = random.random()
self.vel.append(self.spd)
self.vel.append(self.spd * -1)
self.fertility = random.randrange(0, 3)
def safeZone():
#Draws a top rectangle
pygame.draw.rect(win, (50,205,50), (0, 0, 800, 100))
def drawdot(dot):
width = 10
height = 10
pygame.draw.rect(win, (dot.r, dot.g, dot.b), (dot.spawnX, dot.spawnY, width, height))
def population(dots):
for dot in dots:
dot.spawnX += random.choice(dot.vel)
dot.spawnY += random.choice(dot.vel)
if dot.spawnX >= 800:
dot.spawnX -= 5
if dot.spawnY >= 600:
dot.spawnY -= 5
if dot.spawnX <= 0:
dot.spawnX += 5
if dot.spawnY <= 0:
dot.spawnY += 5
if dot.spawnX >= 0 and dot.spawnY >= 100:
pass #Here I want to delete the objects outside of this region
drawdot(dot)
alldots = [Dot() for _ in range(1000)]
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
win.fill((255, 255, 255))
safeZone() # Always draw dots after safe zone
population(alldots)
pygame.display.update()

"not draw them" just means removing them from the container they are in. Use pygame.Rect.colliderect or pygame.Rect.contains to test whether a dot object is in the safe zone. Remove the dots form the list alldots that are not in the safe zone (see How to remove items from a list while iterating?):
def population(dots):
safe_zone_rect = pygame.Rect(0, 0, 800, 100)
for dot in dots:
dot.spawnX += random.choice(dot.vel)
dot.spawnY += random.choice(dot.vel)
if dot.spawnX >= 800:
dot.spawnX -= 5
if dot.spawnY >= 600:
dot.spawnY -= 5
if dot.spawnX <= 0:
dot.spawnX += 5
if dot.spawnY <= 0:
dot.spawnY += 5
if dot.spawnX >= 0 and dot.spawnY >= 100:
pass #Here I want to delete the objects outside of this region
dot_rect = pygame.Rect(dot.spawnX, dot.spawnY, 10, 10)
# if not safe_zone_rect.colliderect(dot_rect):
if not safe_zone_rect.contains(dot_rect):
dots.remove(dot)
drawdot(dot)
pygame.Rect.colliderect tests whether 2 rectangles intersect. pygame.Rect.contains
tests whether a rectangle lies completely within another rectangle.

Related

Python treating all instances of an object as the same

I'm making a game with pygame and pymunk as a physics engine. I'm trying to kill a bullet whenever it hits a player or goes past its lifetime.
When I tried to space.remove(self.shape) and the second bullet hits the player, it gives me an "AssertionError: shape not in space, already removed. I simply changed it to teleport the bullets away, and then learned of the real error.
When I have more than one bullet in the space and a bullet hits the enemy player, all the current bullets teleport away, which means that when I tried to remove one bullet, it called the remove on all the bullets and thats why I had the initial error.
However the problem still remains that one bullet is being treated as every bullet.
Why is something that should be a non-static variable being called as a static variable?
I even tried to use deepcopy to see if that fixed it, but to no avail
This is my chunk of code, apologies since I don't know what is needed to understand it.
The key parts are most likely the Bullet class, the shoot() function in the Player class, and the drawBulletCollision() function
# PyGame template.
# Import modules.
import sys, random, math, time, copy
from typing import List
import pygame
from pygame.locals import *
from pygame import mixer
import pymunk
import pymunk.pygame_util
from pymunk.shapes import Segment
from pymunk.vec2d import Vec2d
pygame.mixer.pre_init(44110, -16, 2, 512)
mixer.init()
# Set up the window.
width, height = 1440, 640
screen = pygame.display.set_mode((width, height))
bg = pygame.image.load("space.png")
def draw_bg():
screen.blit(bg, (0, 0))
#load sounds
#death_fx = pygame.mixer.Sound("")
#death_fx.set_volume(0.25)
shoot_fx = mixer.Sound("shot.wav")
shoot_fx.set_volume(0.25)
#mixer.music.load("video.mp3")
#mixer.music.play()
#time.sleep(2)
#mixer.music.stop()
#gun_mode_fx = pygame.mixer.Sound("")
#gun_mode_fx.set_volume(0.25)
#thrust_mode_fx = pygame.mixer.Sound("")
#thrust_mode_fx.set_volume(0.25)
collision_fx = mixer.Sound("thump.wav")
collision_fx.set_volume(0.25)
ship_group = pygame.sprite.Group()
space = pymunk.Space()
space.gravity = 0, 0
space.damping = 0.6
draw_options = pymunk.pygame_util.DrawOptions(screen)
bulletList = []
playerList = []
environmentList = []
arbiterList = []
b0 = space.static_body
segmentBot = pymunk.Segment(b0, (0,height), (width, height), 4)
segmentTop = pymunk.Segment(b0, (0,0), (width, 0), 4)
segmentLef = pymunk.Segment(b0, (width,0), (width, height), 4)
segmentRit = pymunk.Segment(b0, (0,0), (0, height), 4)
walls = [segmentBot,segmentLef,segmentRit,segmentTop]
for i in walls:
i.elasticity = 1
i.friction = 0.5
i.color = (255,255,255,255)
environmentList.append(i)
class Player(object):
radius = 30
def __init__(self, position, space, color):
self.body = pymunk.Body(mass=5,moment=10)
self.mode = 0 # 0 is gun, 1 is thrust, ? 2 is shield
self.body.position = position
self.shape = pymunk.Circle(self.body, radius = self.radius)
#self.image
#self.shape.friction = 0.9
self.shape.elasticity= 0.2
space.add(self.body,self.shape)
self.angleGun = 0
self.angleThrust = 0
self.health = 100
self.speed = 500
self.gearAngle = 0
self.turningSpeed = 5
self.shape.body.damping = 1000
self.cooldown = 0
self.fireRate = 30
self.shape.collision_type = 1
self.shape.color = color
playerList.append(self)
def force(self,force):
self.shape.body.apply_force_at_local_point(force,(0,0))
def rocketForce(self):
radians = self.angleThrust * math.pi/180
self.shape.body.apply_force_at_local_point((-self.speed * math.cos(radians),-self.speed * math.sin(radians)),(0,0))
def draw(self):
gear = pygame.image.load("gear.png")
gearBox = gear.get_rect(center=self.shape.body.position)
gearRotated = pygame.transform.rotate(gear, self.gearAngle)
#gearRotated.rect.center=self.shape.body.position
x,y = self.shape.body.position
radianGun = self.angleGun * math.pi/180
radianThrust = self.angleThrust * math.pi/180
radiyus = 30 *(100-self.health)/100
screen.blit(gearRotated,gearBox)
self.gearAngle += 1
if radiyus == 30:
radiyus = 32
pygame.draw.circle(screen,self.shape.color,self.shape.body.position,radiyus,0)
pygame.draw.circle(screen,(0,0,0),self.shape.body.position,radiyus,0)
pygame.draw.line(
screen,(0,255,0),
(self.radius * math.cos(radianGun) * 1.5 + x,self.radius * math.sin(radianGun) * 1.5 + y),
(x,y), 5
)
pygame.draw.line(
screen,(200,200,0),
(self.radius * math.cos(radianThrust) * 1.5 + x,self.radius * math.sin(radianThrust) * 1.5 + y),
(x,y), 5
)
#more
def targetAngleGun(self,tAngle):
tempTAngle = tAngle - self.angleGun
tempTAngle = tempTAngle % 360
if(tempTAngle < 180 and not tempTAngle == 0):
self.angleGun -= self.turningSpeed
elif(tempTAngle >= 180 and not tempTAngle == 0):
self.angleGun += self.turningSpeed
self.angleGun = self.angleGun % 360
#print(tAngle, "target Angle")
#print(self.angleGun, "selfangleGun")
#print(tempTAngle, "tempTAngle")
def targetAngleThrust(self,tAngle):
tempTAngle = tAngle - self.angleThrust
tempTAngle = tempTAngle % 360
if(tempTAngle < 180 and not tempTAngle == 0):
self.angleThrust -= self.turningSpeed
elif(tempTAngle >= 180 and not tempTAngle == 0):
self.angleThrust += self.turningSpeed
self.angleThrust = self.angleThrust % 360
#print(tAngle, "target Angle")
#print(self.angleThrust, "selfangleGun")
#print(tempTAngle, "tempTAngle")
def targetAngle(self,tAngle):
if(self.mode == 0):
self.targetAngleGun(tAngle)
elif(self.mode == 1):
self.targetAngleThrust(tAngle)
def shoot(self):
if(self.cooldown == self.fireRate):
x,y = self.shape.body.position
radianGun = self.angleGun * math.pi/180
spawnSpot = (self.radius * math.cos(radianGun) * 1.5 + x,self.radius * math.sin(radianGun)*1.5+y)
self.shape.body.apply_impulse_at_local_point((-20 * math.cos(radianGun),-20 * math.sin(radianGun)),(0,0))
print(spawnSpot)
bT = Bullet(spawnSpot, 5, 50,self.shape.color)
b = copy.deepcopy(bT)
bulletList.append(b)
space.add(b.shape,b.shape.body)
b.getShot(self.angleGun)
self.cooldown = 0
print('pew')
shoot_fx.play()
# HEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEREEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE
def tick(self):
self.draw()
if(self.cooldown < self.fireRate):
self.cooldown += 1
#for o in playerList:
# c = self.shape.shapes_collide(o.shape)
# if(len(c.points)>0):
# self.damage(c.points[0].distance/10)
for o in bulletList:
c = self.shape.shapes_collide(o.shape)
#print(c)
for o in walls:
c = self.shape.shapes_collide(o)
if(len(c.points)>0):
self.damage(c.points[0].distance * 3)
def damage(self, damage):
self.health -= abs(damage)
if self.health < 0:
self.health = 0
#maybe make it part of the player class
def drawWallCollision(arbiter, space, data):
for c in arbiter.contact_point_set.points:
r = max(3, abs(c.distance * 5))
r = int(r)
p = tuple(map(int, c.point_a))
pygame.draw.circle(data["surface"], pygame.Color("red"), p, r, 0)
print('magnitude', math.sqrt(arbiter.total_impulse[0]**2 + arbiter.total_impulse[1]**2))
#print('position', p)
#print(data)
print("its all arbitrary")
s1, s2 = arbiter.shapes
collision_fx.play()
def drawBulletCollision(arbiter, space, data):
s1, s2 = arbiter.shapes
for c in arbiter.contact_point_set.points:
magnitude = math.sqrt(arbiter.total_impulse[0]**2 + arbiter.total_impulse[1]**2)
for p in playerList:
avr = ((c.point_a[0] + c.point_b[0])/2, (c.point_a[1] + c.point_b[1])/2)
distance = (math.sqrt((avr[0] - p.shape.body.position[0]) **2 + (avr[1] - p.shape.body.position[1]) **2 ))
if(distance < Bullet.explosionRadius + Player.radius):
if not(s1.color == s2.color):
p.damage(magnitude)
for b in bulletList:
avr = ((c.point_a[0] + c.point_b[0])/2, (c.point_a[1] + c.point_b[1])/2)
distance = (math.sqrt((avr[0] - p.shape.body.position[0]) **2 + (avr[1] - p.shape.body.position[1]) **2 ))
if(distance < Bullet.explosionRadius + Player.radius):
if not(s1.color == s2.color):
b.damage(magnitude)
pygame.draw.circle(data["surface"], pygame.Color("red"), tuple(map(int, c.point_a)), 10, 0)
print('magnitude', magnitude)
#print('position', p)
#print(data)
print("its all arbitrary")
def drawArbitraryCollision(arbiter, space, data):
collision_fx.play()
class Ship(pygame.sprite.Sprite):
def __init__(self, x, y):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load("gear.png")
self.rect = self.image.get_rect()
self.rect.center = [x, y]
def rotate(self):
self.image = pygame.transform.rotate(self.image,1)
class Bullet(object):
damage = 2
explosionRadius = 5
def __init__(self, position, size, speed,color):
pts = [(-size, -size), (size, -size), (size, size), (-size, size)]
self.body = copy.deepcopy(pymunk.Body(mass=0.1,moment=1))
self.shape = copy.deepcopy(pymunk.Poly(self.body, pts))
self.shape.body.position = position
self.shape.friction = 0.5
self.shape.elasticity = 1
self.shape.color = color
self.speed = speed
self.size = size
self.shape.collision_type = 2
#space.add(self.body,self.shape)
#bulletList.append(self)
self.lifetime = 0
def getShot(self,angle):
radians = angle * math.pi/180
self.shape.body.apply_impulse_at_local_point((self.speed * math.cos(radians),self.speed * math.sin(radians)),(0,0))
def tick(self):
self.lifetime += 1
if(self.lifetime > 300):
self.shape.body.position = (10000,30)
def damage(self, damage):
self.lifetime = 300
#VELOCITY OF BULLET STARTS WITH VELOCITY OF PLAYER
#MAKE VOLUME OF SOUND DEPEND ON THE IMPULSE FOR THE IMPACTS
#error on purpose so you notice this
#INSTANCES NOT WORKING????
def runPyGame():
# Initialise PyGame.
pygame.init()
# Set up the clock. This will tick every frame and thus maintain a relatively constant framerate. Hopefully.
fps = 60.0
fpsClock = pygame.time.Clock()
running = True
font = pygame.font.SysFont("Arial", 16)
p1 = Player((240,240),space,(132, 66, 245,255))
p2 = Player((1200,400),space,(47, 247, 184,255))
space.add(segmentBot,segmentTop,segmentLef,segmentRit)
# Main game loop.
ch = space.add_collision_handler(1, 0)
ch.data["surface"] = screen
ch.post_solve = drawWallCollision
ch = space.add_collision_handler(1, 2)
ch.data["surface"] = screen
ch.post_solve = drawBulletCollision
ch = space.add_collision_handler(0, 2)
ch.data["surface"] = screen
ch.post_solve = drawArbitraryCollision
dt = 1/fps # dt is the time since last frame.
while True: # Loop forever!
keys = pygame.key.get_pressed()
for event in pygame.event.get():
# We need to handle these events. Initially the only one you'll want to care
# about is the QUIT event, because if you don't handle it, your game will crash
# whenever someone tries to exit.
if event.type == QUIT:
pygame.quit() # Opposite of pygame.init
sys.exit() # Not including this line crashes the script on Windows.
if event.type == KEYDOWN:
if event.key == pygame.K_s:
p1.mode = -(p1.mode - 0.5) + 0.5
print(p1.mode)
if (event.key == pygame.K_k and p1.mode == 0):
p1.shoot()
if event.key == pygame.K_KP_5:
p2.mode = -(p2.mode - 0.5) + 0.5
print(p2.mode)
if (event.key == pygame.K_m and p2.mode == 0):
p2.shoot()
#b = Bullet((200,200),51,51)
if(keys[K_w]):
p1.targetAngle(90)
if(keys[K_q]):
p1.targetAngle(45)
if(keys[K_a]):
p1.targetAngle(0)
if(keys[K_z]):
p1.targetAngle(315)
if(keys[K_x]):
p1.targetAngle(270)
if(keys[K_c]):
p1.targetAngle(225)
if(keys[K_d]):
p1.targetAngle(180)
if(keys[K_e]):
p1.targetAngle(135)
if(keys[K_k] and p1.mode == 1):
p1.rocketForce()
if(keys[K_KP_8]):
p2.targetAngle(90)
if(keys[K_KP_7]):
p2.targetAngle(45)
if(keys[K_KP_4]):
p2.targetAngle(0)
if(keys[K_KP_1]):
p2.targetAngle(315)
if(keys[K_KP_2]):
p2.targetAngle(270)
if(keys[K_KP_3]):
p2.targetAngle(225)
if(keys[K_KP_6]):
p2.targetAngle(180)
if(keys[K_KP_9]):
p2.targetAngle(135)
if(keys[K_m] and p2.mode == 1):
p2.rocketForce()
# Handle other events as you wish.
screen.fill((250, 250, 250)) # Fill the screen with black.
# Redraw screen here.
### Draw stuff
draw_bg()
space.debug_draw(draw_options)
for i in playerList:
i.tick()
screen.blit(
font.render("P1 Health: " + str(p1.health), True, pygame.Color("white")),
(50, 10),
)
screen.blit(
font.render("P2 Health: " + str(p2.health), True, pygame.Color("white")),
(50, 30),
)
for i in bulletList:
i.tick()
ship_group.draw(screen)
# Flip the display so that the things we drew actually show up.
pygame.display.update()
dt = fpsClock.tick(fps)
space.step(0.01)
pygame.display.update()
runPyGame()
I cant point to the exact error since the code is quite long and depends on files I dont have. But here is a general advice for troubleshooting:
Try to give a name to each shape when you create them, and then print it out. Also print out the name of each shape that you add or remove from the space. This should show which shape you are actually removing and will probably make it easy to understand whats wrong.
For example:
...
self.shape = pymunk.Circle(self.body, radius = self.radius)
self.shape.name = "circle 1"
print("Created", self.shape.name)
...
print("Adding", self.shape.name)
space.add(self.body,self.shape)
...
(Note that you need to reset the name of shapes you copy, since otherwise the copy will have the same name.)

issues with checking if my images collided in pygame [duplicate]

This question already has an answer here:
Why is my collision test always returning 'true' and why is the position of the rectangle of the image always wrong (0, 0)?
(1 answer)
Closed 1 year ago.
So I'm trying to check im my bird images are touching my could images and if they are to print print('Collided1!').
My Issue is that print('Collided1!') goes off no matter what and is not checking whether the images are touching. colliderect was the solution I found online but I don't seem to know how it works because this is not working.
Do You Know how to fix this? and check whether my images are touching or not?
from random import randint
import pygame, sys
import random
import time
pygame.init()
pygame.display.set_caption('Lokaverkefni')
DISPLAYSURF = pygame.display.set_mode((1224, 724))
fpsClock = pygame.time.Clock()
FPS = 60
a = 1
b = 1
c = 15
x = 100
y = 480
start = 0
score = 0
landX = 1205
totalScore = 0
level = 'low'
directionForBird = 'none'
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
BASICFONT = pygame.font.Font('freesansbold.ttf', 30)
background_resized = pygame.image.load('sky.jpg')
background = pygame.transform.scale(background_resized, (1224, 724))
bird1 = pygame.image.load('bird1.png')
bird1_resized = pygame.transform.scale(bird1, (170, 150))
bird1Surface = bird1_resized.get_rect()
bird2 = pygame.image.load('bird2.png')
bird2_resized = pygame.transform.scale(bird2, (170, 150))
bird2Surface = bird2_resized.get_rect()
cloudsList = ['cloud1.png', 'cloud2.png', 'cloud3.png', 'cloud4.png']
clouds = random.choice(cloudsList)
cloud = pygame.image.load(clouds)
cloud_resized = pygame.transform.scale(cloud, (352, 352))
cloudSurface = cloud_resized.get_rect()
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
elif event.type == KEYDOWN:
if level == 'low':
if (event.key == K_SPACE ):
directionForBird = 'up'
level = 'high'
FPS += 2
c += 1
if directionForBird == 'up':
y -= 10
if y == 10:
directionForBird = 'down'
if directionForBird == 'down':
y += 10
if y == 480:
directionForBird = 'none'
if a == 1:
DISPLAYSURF.blit(background, (0, 0))
DISPLAYSURF.blit(bird1_resized, (x, y))
DISPLAYSURF.blit(cloud_resized, (landX, 300))
b += 1
if b == c:
a += 1
if a == 2:
DISPLAYSURF.blit(background, (0, 0))
DISPLAYSURF.blit(bird2_resized, (x, y))
DISPLAYSURF.blit(cloud_resized, (landX, 300))
b -= 1
if b == 1:
a -= 1
start += 1
if start == 100:
start -= 1
directionForLand = 'left'
if directionForLand == 'left':
landX -= 15
if landX == -550:
landX = 1205
level = 'low'
clouds = random.choice(cloudsList)
cloud = pygame.image.load(clouds)
cloud_resized = pygame.transform.scale(cloud, (352, 352))
score += 1
if score == 30:
score = 0
totalScore += 1
scoreText = BASICFONT.render('Stig : %s' % (totalScore), True, (BLACK))
scoreRect = scoreText.get_rect()
scoreRect.topleft = (1070, 10)
DISPLAYSURF.blit(scoreText, scoreRect)
# This is Supossed to Be what checks if the bird images
# colide with the cloud images
if bird1Surface.colliderect(cloudSurface):
print('Collided1!')
if bird2Surface.colliderect(cloudSurface):
print('Collided1!')
pygame.display.update()
fpsClock.tick(FPS)
bird1Surface, bird2Surface and cloudSurface always have an upper left of (0,0), so they are always on top of each other.. You don't change the rectangles when you move the birds. You need to track the bird x,y and the cloud x,y, and construct new rectangles with the current x,y and the known width and height before you do the collision check.

Pygame bug, music will not play properly as it just loops the beginning part

I'm working on a basic shooter game in Pygame (I'm following a tutorial.) I decided to add background music to keep things nice.
Code (quite long!):
import pygame
from pygame import image as sprite
pygame.init()
dow = pygame.display.set_mode((1000, 700))
pygame.display.set_caption("PY.Touhou")
clock = pygame.time.Clock()
rightSprites = [sprite.load('ness-right1.png'),
pygame.image.load('ness-right2.png'),
pygame.image.load('ness-right3.png'),
pygame.image.load('ness-right4.png'),
pygame.image.load('ness-right5.png'),
pygame.image.load('ness-right6.png'),
pygame.image.load('ness-right7.png'),
pygame.image.load('ness-right8.png')
]
leftSprites = [
sprite.load('ness-left1.png'),
sprite.load('ness-left2.png'),
sprite.load('ness-left3.png'),
sprite.load('ness-left4.png'),
sprite.load('ness-left5.png'),
sprite.load('ness-left6.png'),
sprite.load('ness-left7.png'),
sprite.load('ness-left8.png')
]
scene = pygame.image.load('bg.png')
idle = pygame.image.load('ness-idle.png')
class Player(object):
def __init__(self, x_pos, y_pos, w, h):
self.x_pos = x_pos
self.y_pos = y_pos
self.w = w
self.h = h
self.velocity = 15
self.JUMPbool = False
self.atleft = False
self.atright = False
self.steps = 0
self.jumpheight = 12
self.hitbox = (self.x_pos + 50, self.y_pos, 73, 227)
self.still = True
def move(self):
if self.steps + 1 >= 24:
self.steps = 0
if not self.still:
if self.atleft:
dow.blit(leftSprites[self.steps // 4], (self.x_pos, self.y_pos))
self.steps += 1
elif self.atright:
dow.blit(rightSprites[self.steps // 4], (self.x_pos, self.y_pos))
self.steps += 1
else:
if self.atright:
dow.blit(rightSprites[1], (self.x_pos, self.y_pos))
else:
dow.blit(leftSprites[1], (self.x_pos, self.y_pos))
self.hitbox = (self.x_pos + 50, self.y_pos, 73, 227)
# pygame.draw.rect(dow, (0, 0, 255), self.hitbox, 2)
class IceBullet(object):
def __init__(self, x_pos, y_pos, radius, color, direction):
self.x_pos = x_pos
self.y_pos = y_pos
self.radius = radius
self.color = color
self.direction = direction
self.velocity = 8 * direction
def summon(self):
pygame.draw.circle(dow, self.color, (self.x_pos, self.y_pos), self.radius)
class EnemyCirno(object):
erightSprites = [sprite.load('e-right%s.png' % pic) for pic in range(1, 9)]
eleftSprites = [sprite.load('e-left%s.png' % pic) for pic in range(1, 9)]
def __init__(self, x_pos, y_pos, w, h, ending):
self.x_pos = x_pos
self.y_pos = y_pos
self.w = w
self.h = h
self.ending = ending
self.path = [self.x_pos, self.ending]
self.hitbox = (self.x_pos + 50, self.y_pos, 73, 227)
self.steps = 0
self.health = 20
self.isAlive = True
self.velocity = 4
def summon(self):
self.move()
if self.isAlive:
if self.steps + 1 >= 24:
self.steps = 0
if self.velocity > 0:
dow.blit(self.erightSprites[self.steps // 4], (self.x_pos, self.y_pos))
self.steps += 1
else:
dow.blit(self.eleftSprites[self.steps // 4], (self.x_pos, self.y_pos))
self.steps += 1
pygame.draw.rect(dow, (255, 10, 0), (100, 110, 400, 20))
pygame.draw.rect(dow, (5, 255, 10), (100, 110, 200 - (20 * (10 - self.health)), 20))
enemy_health = italicStyle.render('Enemy Health', 1, (255, 0, 0))
dow.blit(enemy_health, (100, 150))
self.hitbox = (self.x_pos + 50, self.y_pos, 73, 227)
# pygame.draw.rect(dow, (0, 0, 0), self.hitbox, 2)
def move(self):
if self.velocity > 0:
if self.x_pos + self.velocity < self.path[1]:
self.x_pos += self.velocity
else:
self.velocity = self.velocity * -1
self.steps = 0
else:
if self.x_pos - self.velocity > self.path[0]:
self.x_pos += self.velocity
else:
self.velocity = self.velocity * -1
self.steps = 0
def hit(self):
if self.health > 1:
self.health -= 0.50
hit = pygame.mixer.Sound('hit.wav')
hit.play()
else:
self.isAlive = False
dead = pygame.mixer.Sound('death_sound.wav')
dead.play()
# Main starting loop.
letterStyle = pygame.font.SysFont('Bookman Old Style', 50)
italicStyle = pygame.font.SysFont('Bookman Old Style', 30, False, True)
cirno = Player(300, 470, 160, 233)
score = 0
evilCirno = EnemyCirno(50, 470, 160, 233, 800)
maxShots = 0
bullets = []
running = True
while running is True:
clock.tick(24)
pygame.time.delay(10)
music = pygame.mixer.music.load('main_theme.wav') # And here is where the bug begins!
pygame.mixer.music.play()
for events in pygame.event.get():
if events.type == pygame.QUIT:
running = False
key = pygame.key.get_pressed()
def update_screen():
dow.blit(scene, (0, 0))
textdisplay = letterStyle.render('Score: ' + str(score), 1, (0, 255, 255))
won = italicStyle.render("Enemy defeated!", 1, (10, 255, 19))
dow.blit(textdisplay, (50, 30))
if not evilCirno.isAlive:
dow.blit(won, (100, 150))
cirno.move()
evilCirno.summon()
for shot in bullets:
shot.summon()
pygame.display.update()
if maxShots > 0:
maxShots += 1
if maxShots > 5:
maxShots = 0
for shot in bullets:
if evilCirno.isAlive:
if shot.y_pos - shot.radius < evilCirno.hitbox[1] + evilCirno.hitbox[3] and shot.y_pos + shot.radius > \
evilCirno.hitbox[1]:
if shot.x_pos + shot.radius > evilCirno.hitbox[0] and shot.x_pos - shot.radius < evilCirno.hitbox[0] + \
evilCirno.hitbox[2]:
evilCirno.hit()
score += 50
bullets.pop(bullets.index(shot))
if 1000 > shot.x_pos > 0:
shot.x_pos += shot.velocity
else:
bullets.pop(bullets.index(shot))
if key[pygame.K_z] and maxShots == 0:
shoot = pygame.mixer.Sound('bullet.wav')
shoot.play()
if cirno.atleft:
facing = -1
else:
facing = 1
if len(bullets) < 5:
bullets.append(
IceBullet(round(cirno.x_pos + cirno.w // 2), round(cirno.y_pos + cirno.h // 1.2), 20, (0, 0, 255),
facing))
maxShots = 1
if key[pygame.K_LEFT] and cirno.x_pos > cirno.velocity: # Will stop ASAP when reached
cirno.x_pos -= cirno.velocity
cirno.atleft = True
cirno.atright = False
cirno.still = False
elif key[
pygame.K_RIGHT] and cirno.x_pos < 1000 - cirno.velocity - cirno.w: # If it goes past this, it will stop ASAP, as well
cirno.x_pos += cirno.velocity
cirno.atright = True
cirno.atleft = False
cirno.still = False
else:
cirno.steps = 0
cirno.still = True
if not cirno.JUMPbool:
if key[pygame.K_UP]:
cirno.JUMPbool = True
cirno.steps = 0
else:
if cirno.jumpheight >= -12: # What to do if pygame.K_SPACE is pressed down.
cirno.y_pos -= (cirno.jumpheight * abs(cirno.jumpheight)) * 0.5
cirno.jumpheight -= 1
else:
cirno.jumpheight = 12
cirno.JUMPbool = False
update_screen()
pygame.quit()
So far, the music actually does play, as well as the sounds. Though the problem is that it just loops the beginning part of the music over and over (which is only the first few seconds), so what you get is just something that sounds like a broken MP3 player.
(for reference the music is 1:45. Even weirder is that I've seen people use it with no issues.)
Is there any way to fix this bug? Thanks for your help :)
Do you see the bug here?
while running is True:
[...]
music = pygame.mixer.music.load('main_theme.wav')
pygame.mixer.music.play()
It's re-loading and re-playing replaying the music inside your code main loop. That is every single updated frame of game-play,
Load and play music outside your main loop:
music = pygame.mixer.music.load('main_theme.wav')
pygame.mixer.music.play()
while running is True:
[...]
Your code can then call the mixer.get_busy() function too see if the music has stopped, and do something about it.
You probably also want to investigate PyGame Sound mixer channels, so your sound effects mix in with the background music properly.

popping a particular element from a list in pygame [duplicate]

This question already has answers here:
How to remove items from a list while iterating?
(25 answers)
Closed 2 years ago.
I recently started making Atari Breakout in Pygame. I encountered a problem that I don't know how to fix. Whenever I run my code, and the ball comes in contact with the block, the block that's colliding with it, doesn't disappear as it should, but the last block from the list. (I made a list of 21 pygame.Surfaces and iterate over it and blit every single one). Obviously, if the ball touches the last block from the list, the correct one disappears. Please can you help me?
This is my code:
import pygame, random, math
pygame.init()
screen = pygame.display.set_mode((800,600))
pygame.display.set_caption('Atari Breakout')
player = pygame.image.load('player copy.png')
ball = pygame.image.load('poland.png')
blocks = [pygame.image.load('block.png') for i in range(21)]
x, y = 25,25
blockx, blocky = [], []
for i in range(21):
if i % 7 == 0:
y += 52
x = 25
blockx.append(x)
blocky.append(y)
x += (50 + 64)
ballx, bally = 400, 300
balldx, balldy = 4,4
score = 0
score_font = pygame.font.Font('freesansbold.ttf', 32)
def show_score():
score_text = score_font.render('Score : {}'.format(score), True, (255,255,255))
screen.blit(score_text, (0,0))
def isCollision(x1,y1,x2,y2):
ballRect = ball.get_rect(topleft = (x1, y1))
playerRect = player.get_rect(topleft = (x2, y2))
return ballRect.colliderect(playerRect)
def isCollision2(x1,y1,x2,y2):
ballRect = ball.get_rect(topleft = (x1,y1))
blockRect = blocks[i].get_rect(topleft = (x2,y2))
return ballRect.colliderect(blockRect)
def blit_blocks():
for i in range(len(blocks)):
screen.blit(blocks[i], (blockx[i], blocky[i]))
running = True
while running:
if score >= 21:
running = False
screen.fill((0,0,0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
pos = pygame.mouse.get_pos()
for i, block in enumerate(blocks):
if isCollision2(ballx, bally, blockx[i], blocky[i]):
balldy *= -1
score += 1
blocks.pop(i)
if isCollision(ballx, bally, pos[0], 525):
balldy *= -1
if bally <= 0:
balldy *= -1
if bally >= 570:
running = False
if ballx <= 0:
balldx *= -1
if ballx >= 770:
balldx *= -1
ballx += balldx
bally += balldy
screen.blit(player, (pos[0], 525))
screen.blit(ball, (ballx,bally))
blit_blocks()
show_score()
pygame.display.update()
What you actually do ist manipulate a list (by pop) while you iterate it. I recommend to travers a copy of the list (blocks[:]) and to manipulate the original list. e.g:
i = 0
for x, y, block in zip(blockx[:], blocky[:], blocks[:]):
if isCollision2(ballx, bally, x, y):
blockx.pop(i)
blocky.pop(i)
blocks.pop(i)
balldy *= -1
score += 1
else:
i += 1
Anyway, I recommend to create a class Block:
class Block():
def __init__(self, image, x, y)
self.image = image
self.x = x
self.y = y
image = pygame.image.load('block.png')
x, y = 25,25
blocks = []
for i in range(21)
if i % 7 == 0:
y += 52
x = 25
blocks.append(Block(image, x, y))
x += (50 + 64)
i = 0
for block in block[:]:
if isCollision2(ballx, bally, block.x, block.y):
balldy *= -1
score += 1
block.pop(i)
else:
i += 1
it is a bad practice to pop from a list while you are iterating over this will cause unexpected behaviour, here:
for i, block in enumerate(blocks):
if isCollision2(ballx, bally, blockx[i], blocky[i]):
balldy *= -1
score += 1
blocks.pop(i)
you can use:
new_blocks = []
for i, block in enumerate(blocks):
if isCollision2(ballx, bally, blockx[i], blocky[i]):
balldy *= -1
score += 1
else:
new_blocks.append(block)
blocks = new_blocks

How do I add a score tracker?

So I want it to count the score every time the snake eats a candy.
I haven't tried much, but I tried to find existing codes and adding them to mine but that just broke the game. I also tried to make my own score board by watching a tutorial, but I don't know where the code should go like at the beginning or end.
import pygame
import random
score = 0
welcome = ("Welcome to our snake game")
print(welcome)
class cube:
height = 20
w = 500
def __init__(movee,start,x=1,y=0,color=(0,0,0)):
movee.pos = start
movee.x = 1
movee.y = 0
movee.color = color
def move(movee, x, y):
movee.x = x
movee.y = y
movee.pos = (movee.pos[0] + movee.x, movee.pos[1] + movee.y)
def draw(movee, surface, eyes=False):
leng = movee.w // movee.height
i = movee.pos[0]
j = movee.pos[1]
pygame.draw.rect(surface, movee.color, (i*leng+1,j*leng+1, leng-2, leng-2))
class snake:
body = []
turns = {}
def __init__(movee, color, pos):
movee.color = color
movee.head = cube(pos)
movee.body.append(movee.head)
def move(movee):
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
keys = pygame.key.get_pressed()
for key in keys:
if keys[pygame.K_LEFT]:
movee.x = -1
movee.y = 0
movee.turns[movee.head.pos[:]] = [movee.x, movee.y]
elif keys[pygame.K_RIGHT]:
movee.x = 1
movee.y = 0
movee.turns[movee.head.pos[:]] = [movee.x, movee.y]
elif keys[pygame.K_UP]:
movee.x = 0
movee.y = -1
movee.turns[movee.head.pos[:]] = [movee.x, movee.y]
elif keys[pygame.K_DOWN]:
movee.x = 0
movee.y = 1
movee.turns[movee.head.pos[:]] = [movee.x, movee.y]
for i, c in enumerate(movee.body):
p = c.pos[:]
if p in movee.turns:
turn = movee.turns[p]
c.move(turn[0],turn[1])
if i == len(movee.body)-1:
movee.turns.pop(p)
else:
if c.x == -1 and c.pos[0] <= 0: c.pos = (c.height-1, c.pos[1])
elif c.x == 1 and c.pos[0] >= c.height-1: c.pos = (0,c.pos[1])
elif c.y == 1 and c.pos[1] >= c.height-1: c.pos = (c.pos[0], 0)
elif c.y == -1 and c.pos[1] <= 0: c.pos = (c.pos[0],c.height-1)
else: c.move(c.x,c.y)
def add(movee):
tail = movee.body[-1]
dx, dy = tail.x, tail.y
if dx == 1 and dy == 0:
movee.body.append(cube((tail.pos[0]-1,tail.pos[1])))
elif dx == -1 and dy == 0:
movee.body.append(cube((tail.pos[0]+1,tail.pos[1])))
elif dx == 0 and dy == 1:
movee.body.append(cube((tail.pos[0],tail.pos[1]-1)))
elif dx == 0 and dy == -1:
movee.body.append(cube((tail.pos[0],tail.pos[1]+1)))
movee.body[-1].x = dx
movee.body[-1].y = dy
def draw(movee, surface):
for i, c in enumerate(movee.body):
if i ==0:
c.draw(surface, True)
else:
c.draw(surface)
def drawingAGrid(w, height, surface):
sizein = w // height
x = 0
y = 0
for l in range(height):
x = x + sizein
y = y + sizein
def redrawGrid(surface):
global height, width, s, snack
surface.fill((255,255,255))
s.draw(surface)
snack.draw(surface)
drawingAGrid(width, height, surface)
pygame.display.update()
def Candy(height, item):
positions = item.body
while True:
x = random.randrange(height)
y = random.randrange(height)
if len(list(filter(lambda z:z.pos == (x,y), positions))) > 0:
continue
else:
break
return (x,y)
def gameloop():
global width, height, s, snack, x_pos, y_pos, reset
width = 500
height = 20
win = pygame.display.set_mode((width, width))
s = snake((255, 0, 0), (10, 10))
snack = cube(Candy(height, s), color=(0, 0, 0))
flag = True
clock = pygame.time.Clock()
x_pos, y_pos = s.body[0].pos
while flag:
pygame.time.delay(50)
clock.tick(7)
s.move()
x, y = s.body[0].pos
if not -1 <= x - x_pos <= 1 or not -1 <= y - y_pos <= 1:
movee.reset((10,10))
x_pos, y_pos = s.body[0].pos
if s.body[0].pos == snack.pos:
s.add()
snack = cube(Candy(height, s), color=(0, 0, 0))
redrawGrid(win)
gameloop()
I just want like a scoreboard in any of the corners counting the score.
Use pygame.freetype to render text. e,g, crated a pygame.freetype.SysFont object:
import pygame.freetype
pygame.init()
font = pygame.freetype.SysFont('Times New Roman', 30)
The score is the number of body parts. Use str to convert a number to a text and .render() to render a text to a pygame.Surface object:
score = len(s.body)
text_surf, text_rect = font.render(str(score), (255, 0, 0), size=30)
Define a margin to the border of the window, calculate the text position (e.g. bottom right) and .blit the text to the window surfrace:
margin = 10
text_pos = (width - text_rect.width - margin, width - text_rect.height - margin)
surface.blit(text_surf, text_pos)
Function redrawGrid:
def redrawGrid(surface):
global height, width, s, snack
surface.fill((255,255,255))
s.draw(surface)
snack.draw(surface)
drawingAGrid(width, height, surface)
score = len(s.body)
text_surf, text_rect = font.render(str(score), (255, 0, 0), size=30)
margin = 10
text_pos = (width - text_rect.width - margin, width - text_rect.height - margin)
surface.blit(text_surf, text_pos)
pygame.display.update()

Categories

Resources