为什么我的pygame显示器没有显示任何内容?

2024-09-30 10:34:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在研究一个程序,利用遗传算法随时间进化生物。然而,由于某些原因,我的pygame显示器停止工作,我完全不知道为什么。当我运行这个程序时,窗口会打开,但它只是停留在一个黑屏上。我已经测试了程序的运行情况,大约38个生物死亡,然后什么都没有发生。然而,这些生物也应该在他们死前展示,但他们没有。任何帮助都将是美妙的!谢谢你花了这么多时间!在

我的代码是:

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)

Tags: inrectimageselfforifdefrange
1条回答
网友
1楼 · 发布于 2024-09-30 10:34:54

我怀疑livingCreatures变量从未设置为False,因此pygame.display.flip()永远不会被调用,并且在屏幕上根本看不到任何内容,除非您翻转缓冲区。事实上,你在屏幕上填充了一种颜色,但仍然看到黑色,这是对这类问题的一种彻底的放弃。在

将来,您还应该尝试在一个更简单的示例中重现该问题,而不使用特定于域的、无关的代码。在

相关问题 更多 >

    热门问题