【发布时间】:2020-12-27 12:21:01
【问题描述】:
我正在重新启动一些用于 covid 模拟的代码,因为我无法在当前代码中使用碰撞功能。我已经能够绘制基本背景,并绘制一个单元格。但是,当我尝试在屏幕上的不同位置创建单元格时,由于某种原因它没有出现。
我的代码如下:
import random
import pygame
# import numpy
import time
pygame.init()
GREEN1 = (0, 255, 0) # Healthy cells
RED = (255, 0, 0) # Infected cells
GREEN2 = (0, 100, 0) # Healthy cells not susecptible
BLACK = (0, 0, 0) # Dead cells
WHITE = (255, 255, 255)
Bgcolor = (225, 198, 153)
ScreenSize = (800, 800)
Screen = pygame.display.set_mode(ScreenSize)
pygame.display.set_caption("Covid-19 Simualtion")
clock = pygame.time.Clock()
speed = [0.5, -0.5]
class Cells(pygame.sprite.Sprite):
def __init__(self, color, speed, width, height):
super().__init__()
self.color = color
self.x_cord = random.randint(0, 400)
self.y_cord = random.randint(50, 700)
self.radius = 5
self.speed = speed
self.image = pygame.Surface([width, height])
self.image.fill(WHITE)
self.image.set_colorkey(WHITE)
pygame.draw.circle(self.image, self.color, [30, 70], self.radius, width = 0)
self.rect = self.image.get_rect()
self.radius = 5
#x_number = random.randint(0, 1)
#self.xSpeed = speed[x_number]
#y_number = random.randint(0, 1)
#self.ySpeed = speed[y_number]
allCellsList = pygame.sprite.Group()
Cell1 = Cells(GREEN1, 5, 50, 50)
allCellsList.add(Cell1)
End = False
while not End:
for event in pygame.event.get():
if event.type == pygame.QUIT:
End = True
Screen.fill(Bgcolor)
pygame.draw.rect(Screen, BLACK, (0, 50, 400, 700), 3)
allCellsList.update()
allCellsList.draw(Screen)
pygame.display.flip()
clock.tick(60)
提前感谢您的帮助
【问题讨论】:
-
我看不到您在不同位置创建单元格的位置。也许在 Cell 中你应该创建方法
update()来改变self.rect -
要移动 Sprite,您必须使用(和更改)
self.rect.xself.rect.y,但您保持在self.x_cord、self.y_cord的位置 -
您的单元格大小为
(50,50),而您尝试在(20,70)位置上绘制,所以它在矩形(50, 50)之外绘制,您看不到它。您必须在矩形(50, 50)内绘制 - 例如在中心(25,25)。稍后您应该使用self.rect将其移动到屏幕上。
标签: python pygame drawing simulation