我是pygame的新手,正在尝试创建类似“ splatoon”的游戏,我已经准备好了基本元素,但是我不知道如何计算屏幕百分比。我是使用get_at单独扫描每个像素还是有一种更简单的方法来计算它?
这是我的代码:
import pygame
import sys
black = (0,0,0)
white = (255, 255, 255)
silver = (192, 192, 192)
aqua = (0, 255,255)
x = 10
y =490
a = 490
b = 10
vel = 1
pygame.init()
FPS = 60
fpsClock = pygame.time.Clock()
win = pygame.display.set_mode((500,500))
time = pygame.time.get_ticks()
while True:
seconds = (pygame.time.get_ticks())/1000
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if seconds <= 10:
keys = pygame.key.get_pressed()
color = black
if keys[pygame.K_d] and x < 490:
x += vel
if keys[pygame.K_RIGHT] and a < 490:
a += vel
if keys[pygame.K_a] and x > 0:
x -= vel
if keys[pygame.K_LEFT] and a > 0:
a -= vel
if keys[pygame.K_w] and y > 0:
y -= vel
if keys[pygame.K_UP] and b > 0:
b -= vel
if keys[pygame.K_s] and y < 490:
y += vel
if keys[pygame.K_DOWN] and b < 490:
b += vel
if keys[pygame.K_e]:
pygame.draw.rect(win, aqua, (x-20,y-20,50,50))
if keys[pygame.K_SPACE]:
pygame.draw.rect(win, silver, (a-20,b-20,50,50))
if keys[pygame.K_p]:
win.fill((0,0,0))
pygame.draw.rect(win, aqua, (x,y,10,10))
pygame.draw.rect(win, silver, (a,b,10,10))
pygame.display.update()
fpsClock.tick(FPS)
else:
break
答案 0 :(得分:0)
我认为您可以使用这样的函数,使用 pygame.Surface.get_at()
:
def get_percentage(color, step=1):
width, height = screen_size
total_number_of_pixels = width * height
number_of_pixels = 0
for x in range(0, width, step):
for y in range(0, height, step):
if screen.get_at((x, y)) == color:
number_of_pixels += 1
percentage = number_of_pixels / total_number_of_pixels * 00
return percentage
但是因为它会大大减慢代码的速度,所以您可以存储百分比并仅在百分比更新时调用此函数(例如,如果玩家攻击)。
您可以更改上面代码中的 step
变量,以更粗略(更快)地获得百分比。