Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@miohtama
Last active August 31, 2021 15:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save miohtama/f4e437b91a3ac21eb27a21d1a7e42b5d to your computer and use it in GitHub Desktop.
Save miohtama/f4e437b91a3ac21eb27a21d1a7e42b5d to your computer and use it in GitHub Desktop.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;
pragma abicoder v2;
contract ArrayTest {
function colourToString(uint r, uint g, uint b) private pure returns(string memory) {
bytes memory alphabet = "0123456789abcdef";
bytes memory str = new bytes(7);
str[0] = '#';
str[1] = alphabet[r >> 4];
str[2] = alphabet[r & 0x0f];
str[3] = alphabet[g >> 4];
str[4] = alphabet[g & 0x0f];
str[5] = alphabet[b >> 4];
str[6] = alphabet[b & 0x0f];
return string(str);
}
function getColourMap(uint tokenId) public view returns (string[8] memory){
uint8[100] memory array = [5,228,119,255,5,228,119,255,122,191,72,255,5,228,119,255,5,228,119,255,5,228,119,255,122,191,72,255,0,0,0,0,122,191,72,255,5,228,119,255,164,13,103,255,0,0,0,0,5,228,119,255,0,0,0,0,164,13,103,255,0,0,0,0,122,191,72,255,164,13,103,255,122,191,72,255,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];//_pixelArrays[tokenId];
// We limit to 8 colours per invader because EVM limitations of no dynamic arrays within the function scope
string[8] memory colourmap;
uint[8] memory found;
string memory colourHex;
uint existingIdx;
// convert to hex, loop through pixels, check if new colour & add to list of hex #RRGGBB
for (uint8 i=0; i<100 ; i+=4){
uint r = array[i];
uint g = array[i + 1];
uint8 b = array[i + 2];
// colour as integer
// add 0xff alpha so we distinguish 0x000000 black from unallocated memory
uint binValue = r << 24 | g << 16 | b << 8 | 0xff;
// colour as string
colourHex = colourToString(r, g, b);
// mapping() would be better, but mapping type is only supported for
// storage and not available within the functions
bool alreadyHas = false;
for(existingIdx=0; existingIdx<found.length; existingIdx++) {
if(found[existingIdx] == binValue) {
alreadyHas = true;
}
}
if(!alreadyHas) {
for(existingIdx=0; existingIdx<found.length; existingIdx++) {
// 0x0 is the default unallocated memory in EVM
if(found[existingIdx] == 0) {
found[existingIdx] = binValue;
colourmap[existingIdx] = colourHex;
break;
}
}
}
}
return colourmap;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment