-1

Im a newbie to pygame, having trouble in rendering the "bad guys" in my game. For the first couple frames they move towards the player all fine, but after that they start flickering and hiding (i think behind the background) every couple frames

They should move towards the player continiously and smoothly, not flicker. Im thinking it may be because my code is inefficient, and im storing a lot of info inside lists and maybe that slows it down? Either way, if you think of a solution for that, greatly appreciated.

Code THE IMPORTANT PART IS IN THE MOB CLASS:

import pygame
from sys import exit
import random
import math
import threading
import time

pygame.init()
pygame.mixer.init()

# Definir dimensiones y variables globales
width = 1500
height = 800
x1, y1 = 100, 100
list_bullets = 0
bx = [100]
by = [100]
bullet = []
bullet_rect = []
bullet_angle = []
vx = []
vy = []
mob_rect = []
mob_list = []
list_mobs = 0
mx = 100
my = 100
mobanimation = 0

# Crear la pantalla y otros elementos
screen = pygame.display.set_mode((width, height))
screen2 = pygame.surface.Surface((width,height),pygame.SRCALPHA)
bg = pygame.Surface((width, height))
bg.fill((200, 200, 200))

pygame.display.set_caption("Pistolitas")
clock = pygame.time.Clock()

main_og = pygame.image.load("img/main.png")
main_og = pygame.transform.scale(main_og, (40, 40))
bullet_og = pygame.image.load("img/bullet.png")
bullet_og = pygame.transform.scale(bullet_og, (20, 20))
mob_sprite = [
    pygame.image.load("img/mob_idle1.png"),
    pygame.image.load("img/mob_idle2.png"),
    pygame.image.load("img/mob_idle3.png"),
    pygame.image.load("img/mob_idle4.png"),
]

mob = pygame.transform.scale(mob_sprite[0], (100, 100))

# Funciones para el jugador y balas
def PlayerMovement():
    global x1, y1
    keys = pygame.key.get_pressed()
    if keys[pygame.K_d]:
        x1 += 3
    if keys[pygame.K_a]:
        x1 -= 3
    if keys[pygame.K_s]:
        y1 += 3
    if keys[pygame.K_w]:
        y1 -= 3

def PlayerRotation():
    global x1, y1, main, main_rect, angle
    mouse_x, mouse_y = pygame.mouse.get_pos()
    rel_x1, rel_y1 = mouse_x - x1, mouse_y - y1
    angle = (180 / math.pi) * -math.atan2(rel_y1, rel_x1)
    main = pygame.transform.rotate(main_og, angle)
    main_rect = main.get_rect(center=(x1, y1))

class Bullets:
    def BulletShot(self, number):
        global bx, by
        bullet.append(pygame.transform.rotate(bullet_og, angle - 90))
        bx.append(x1)
        by.append(y1)
        bullet_angle.append(angle)
        trayectory = threading.Thread(target=self.BulletTrayectory, args=(number,))
        trayectory.start()

    def BulletTrayectory(self, number):
        global bullet_angle
        bx[number] = x1
        by[number] = y1
        vx.append(math.sin((bullet_angle[number] + 90) * (math.pi / 180)))
        vy.append(math.cos((bullet_angle[number] + 90) * (math.pi / 180)))
        for number in range(200):
            bx[number] += vx[number] * 8
            by[number] += vy[number] * 8
            bullet_rect.append(bullet_og.get_rect(center=(bx[number], by[number])))
            screen2.blit(bullet[number],(bx,by))
            

class Mobs:
    def Spawning(self, number):
        global mob, mob_list, mob_rect,list_mobs
        if list_mobs < 5:
            for a in range(5 - list_mobs):
                list_mobs += 1 
                mob_rect.append(mob.get_rect(center=(random.randrange(-50, 1400), random.randrange(-50, 700))))
                print(mob_rect)
        animate = threading.Thread(target=self.AnimationMob)
        animate.start()

    def AnimationMob(self):
        global mob, mob_list, mob_rect, mobanimation,list_mobs
        while True:
            mobanimation = (mobanimation + 1) % 4  # Ciclo de 0 a 3
            if list_mobs < 5:
                for a in range(5 - list_mobs):
                    list_mobs += 1 
                    mob_rect.append(mob.get_rect(center=(random.randrange(-50, 1400), random.randrange(-50, 700))))
                    print(mob_rect)
            self.UpdateMobPos()
            time.sleep(0.5)  # Añade una pausa para evitar que la animación sea muy rápida

    def UpdateMobPos(self):
        global i
        screen2.fill((200,200,200))
        for i in range(len(mob_rect)):  # Itera sobre los índices válidos de mob_rect
            if i < len(mob_sprite):  # Verifica si el índice es válido en mob_sprite
                mob_surf = pygame.transform.scale(mob_sprite[i], (100, 100))
                mob_list.append(mob_surf)
                if i < len(mob_rect):  # Verifica si el índice es válido en mob_rect
                    screen2.blit(mob_list[i], mob_rect[i])
        m.Tracking()

    def Tracking(self):
        global x1, y1, mob_rect
        for i in range(list_mobs):
            distance = [x1 - mob_rect[i].centerx, y1 - mob_rect[i].centery]
            angle = math.atan2(distance[1], distance[0])
            speed = 2  # Velocidad de los mobs
            vx = speed * math.cos(angle)
            vy = speed * math.sin(angle)
            mob_rect[i].centerx += vx/2
            mob_rect[i].centery += vy/2



# Inicializar las clases y threads
b = Bullets()
m = Mobs()

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            exit()
        if event.type == pygame.MOUSEBUTTONDOWN:
            b.BulletShot(list_bullets)
            list_bullets += 1
    PlayerMovement()
    PlayerRotation()
    screen.blit(screen2,(0,0))
    screen.blit(main, main_rect)
    m.Spawning(list_mobs)
    pygame.display.update()
    clock.tick(5)
Rabbid76
  • 202,892
  • 27
  • 131
  • 174

0 Answers0