理解彩色python上的操作时遇到的问题
我开始学习pygame我买了一本书,在这本书中我有以下脚本:理解彩色python上的操作时遇到的问题,python,colors,pygame,pixel,Python,Colors,Pygame,Pixel,我开始学习pygame我买了一本书,在这本书中我有以下脚本: import pygame pygame.init() screen = pygame.display.set_mode((640,480)) all_colors = pygame.Surface((4096,4096),depth=24) for r in xrange(256): x = (r & 15) * 256 y = (r >> 4) * 256 print x, &q
import pygame
pygame.init()
screen = pygame.display.set_mode((640,480))
all_colors = pygame.Surface((4096,4096),depth=24)
for r in xrange(256):
x = (r & 15) * 256
y = (r >> 4) * 256
print x, " " , y
for g in xrange(256):
for b in xrange(256):
all_colors.set_at((x+g,y+b),(r,g,b))
screen.blit(all_colors,(0,0))
pygame.image.save(all_colors,"allcolors.bmp")
在这个脚本中,我们生成了一个包含计算机可以生成的所有颜色的图像,我不理解的唯一说明是:
有人可以解释他为什么做这个手术。我知道这是位运算符,但我不明白他为什么这么做,谢谢:D。
&
是位运算符。15是00001111二进制。因此(r&15)
屏蔽r
的低4位。结果在[0,15]范围内。>
是右移操作员<代码>(r>>4)将r
向右移位4位。如果r
是一个字节(8位)值,则结果再次在[0,15]范围内。(r&15)
是r
的低4位,(r>>4)
是r
的高4位(如果r
在[0255]范围内)
用于循环的
xrange(256)中r的:
x=(r&15)*256
y=(r>>4)*256
可以用以下嵌套的代替循环:
xrange(16)中的i的:
对于X范围内的j(16):
r=i*16+j
x=j*256
y=i*256
曲面的大小为4096x4096。4096 = 16*256. x
和y
都在[04096]范围内。这在我看来写得很混乱。发生的是x
和y
(它们定义了屏幕上网格中的位置)通过取每个可能的r
值的上下4位,从r
派生而来,但这并不是很明显,你不应该为初学者不了解它而感到难过;作者应该为编写复杂的代码而感到难过,也不应该对它进行注释。:)
在我看来,如果你在做按位运算,最好用十六进制来表示数字,因为这样更容易直观地显示移位(例如,如果你用十六进制乘以某物,那么更明显的是,目标是将两个十六进制数字向左移位,而不是用十进制乘以256).我还认为最好让外循环通过x
和y
并从这些值生成r
,而不是反过来,因为这样做的数学更简单
下面是我如何编写该循环(使用十六进制数字和注释)。我也将其编写为与Python 3兼容,但我认为它也应该与Python 2向后兼容:
for x in range(0x10):
for y in range(0x10):
# x and y define a 0x10 by 0x10 grid on the screen.
print(x, " " , y)
# Each cell in the grid has a unique 8-bit red value (r) based on its x, y.
r = x * 0x10 + y
# Each cell is itself 0x100 pixels square with each pixel having a unique g, b.
for g in range(0x100):
for b in range(0x100):
# g and b serve as both color values and cell-relative coordinates.
# To get the screen-relative coords we add the x/y values for the cell,
# multiplied by the dimensions of the cell in pixels (0x100).
all_colors.set_at((x * 0x100 + g, y * 0x100 + b), (r, g, b))
screen.blit(all_colors, (0, 0))
试着在纸上手动执行,看看结果与r
的值有什么关系。