Why isn't my pygame display displaying anythin

2019-09-11 00:37发布

问题:

I am working on a program that evolves creatures over time using a genetic algorithm. However, for some reason, my pygame display stopped working and I have absolutely no idea why. When I run the program, the window opens but then it just sits on a black screen. I have tested to see where the program gets to and about 38 creatures die then nothing happens. However, these creatures should be displaying before their deaths also, but they aren't.Any help would be wonderful! Thank you for all your time!

Here's my code:

import numpy as np
import pygame
import random

#Initializes Pygame & Creates Window
pygame.init()

backgroundColor = (255, 255, 255)
screenSize = (800, 600)
screen = pygame.display.set_mode(screenSize)
pygame.display.set_caption("Genetic Algorithm")
screen.fill(backgroundColor)
clock = pygame.time.Clock()

#Loads Images & Rectangles
creaturePNG = pygame.image.load("Creature.png").convert_alpha()
foodPNG = pygame.image.load("Food.png").convert_alpha()

#Establishes Size Of Population
creatureCount = 40

deadCreatures = []

numGenerations = 10

#Generates Random 12 Digit DNA For First Generation
def initialDNA():
    while True:
        randomDNA = ""
        total = 0
        for i in range(12):
            digit = random.randint(1, 9)
            total += digit
            digit = str(digit)
            randomDNA = randomDNA + digit
        if total <= 60:
            break
    return randomDNA

def reproduce(deadCreatureList, creatureCount):
    reproducingCreatures = deadCreatureList[0.5*creatureCount:creatureCount]
    for i in range(0.25*creatureCount):
        creature1 = reproducingCreatures[0]
        del reproducingCreatures[0]
        creature2 = reproducingCreatures[0]
        del reproducingCreatures[0]
        DNA1 = str(creature1.DNA)
        DNA2 = str(creature2.DNA)
        crosspoint = random.randint(0, 12)
        newDNA1 = int(DNA1[0:crosspoint] + DNA2[crosspoint:])
        newDNA2 = int(DNA2[0:crosspoint] + DNA1[crosspoint:])
    return newDNA1,  newDNA2


#Creates Creatures From DNA
class Creature:
    def __init__(self, DNA,  image):
        self.DNA = DNA
        self.speed = (int(self.DNA[0:2])/100) + 1
        self.strength = int(DNA[2:4])/10
        self.foodCap = int(DNA[4:6])
        self.maxHealth = int(DNA[6:8])
        self.health = self.maxHealth
        self.regeneration = int(DNA[8:10])/10
        self.turnProbability = int(DNA[10:12])
        self.currentFood = self.foodCap
        self.image = image
        self.rect = self.image.get_rect()
        self.directions = [-1, 1]
        self.directionX = random.choice(self.directions)
        self.directionY = random.choice(self.directions)
        self.isAlive = True

    def spawn(self):
        self.x = random.randint(25, 775)
        self.y = random.randint(25, 575)
        self.loc = (self.x, self.y)
        self.rect = pygame.Rect(0, 0, 25, 25)
        self.rect.center = self.loc

    def move(self):
        changeDirection = random.randint(0, 100)
        if changeDirection < self.turnProbability:
            self.directionX = random.choice(self.directions)
            self.directionY = random.choice(self.directions)
        self.x += self.directionX * self.speed
        self.y += self.directionY * self.speed
        if self.x > 775:
            self.x = 775
        elif self.x < 25:
            self.x = 25
        elif self.y > 575:
            self.y = 575
        elif self.y < 25:
            self.y = 25
        self.loc = (self.x, self.y)
        self.rect.center = self.loc

    def foodCollision(self, foodList):
        foodRects = []
        for i in range(25):
            food = foodList[i]
            foodRect = food.rect
            foodRects.append(foodRect)
        collision = self.rect.collidelist(foodRects)
        if collision > 0:
            self.currentFood += 20
            if self.currentFood > self.foodCap:
                self.currentFood = self.foodCap

    def creatureCollision(self, creatureList, creatureCount, creatureNumber):
            creatureRects = []
            for i in range(creatureCount):
                creature = creatures[i]
                creatureRect = creature.rect
                creatureRects.append(creatureRect)
            collision = self.rect.collidelist(creatureRects)
            creature = creatures[collision]
            if collision >= 0:
                if collision != creatureNumber:
                    if creature.health > 0:
                        self.health -= creature.strength
                        if self.health < 0:
                            self.health = 0

    def starve(self):
        if self.currentFood == 0:
            self.health -= 1

    def display(self):
        screen.blit(self.image, self.loc)

#Creates Food Objects For Creatures To Eat
class Food:
    def __init__(self, image):
        self.image = image
        self.rect = self.image.get_rect()

    def spawn(self):
        self.x = random.randint(25, 775)
        self.y = random.randint(25, 575)
        self.loc = (self.x, self.y)
        self.rect = pygame.Rect(0, 0, 25, 25)
        self.rect.center = self.loc

    def creatureCollision(self, creatureList, creatureCount):
        creatureRects = []
        for i in range(creatureCount):
            creature = creatures[i]
            creatureRects.append(creature.rect)
        collision = self.rect.collidelist(creatureRects)
        creature = creatures[collision]
        if collision >= 0:
            if creature.health > 0:
                self.spawn()

    def display(self):
        screen.blit(self.image,  self.loc)


running = True 
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    screen.fill(backgroundColor)

    for i in range(numGenerations):
        if i == 0:
            #Spawns Creatures Into World
            creatures = []
            for i in range(creatureCount):
                DNA = initialDNA()
                print (DNA)
                creature = Creature(DNA, creaturePNG)
                creature.spawn()
                creatures.append(creature)

        elif i > 0:
            creatures = []
            for i in range(0.5*creatureCount):
                DNA1, DNA2 = reproduce(deadCreatures, creatureCount)
                print (DNA1, DNA2)
                creature1, creature2 = Creature(DNA1, creaturePNG), Creature(DNA2, creaturePNG)
                creature.spawn()
                creatures.append(creature)

        #Spawns Food Into World
        foodList = []
        for i in range(25):
            food = Food(foodPNG)
            food.spawn()
            foodList.append(food)

        livingCreatures = True

        while livingCreatures:
            for i in range(25):
                food = foodList[i]
                food.creatureCollision(creatures, creatureCount)
                food.display()

            for i in range(creatureCount):
                creature = creatures[i]
                if creature.health > 0:
                    creature.move()
                    creature.foodCollision(foodList)
                    creature.creatureCollision(creatures, creatureCount, i)
                    creature.currentFood -= 0.5
                    if creature.currentFood < 0:
                        creature.currentFood = 0
                    if creature.currentFood > 0:
                        creature.health += creature.regeneration
                        if creature.health > creature.maxHealth:
                            creature.health = creature.maxHealth
                    creature.starve()
                    creature.display()

                    if creature.isAlive == True:
                        if creature.health == 0:
                            print ("DEATH")
                            deadCreatures.append(i)
                            creature.isAlive = False

            if len(deadCreatures) == creatureCount:
                livingCreatures = False

        pygame.display.flip()
        clock.tick(10)

回答1:

I suspect the livingCreatures variable is never set to False, so the pygame.display.flip() never gets called--and you won't see anything on the screen at all until you flip the buffers. The fact that you're filling the screen with a color, but then still seeing black, is a dead giveaway for this sort of problem.

In the future, you should also try to reproduce the problem in a simpler example without domain-specific, irrelevant code.