按下鼠标时随机化图像 - 处理

Randomize image when mouse pressed - Processing

    PImage img[];
    int nPics;
     
    int w;
    int h;
    
    
    int rand;
    
     
    void setup(){
      
      size(1500,500);
      nPics=27;
      img = new PImage[nPics];
    
      w=width/9;  
      h=height/3; 
    
    for (int i = 0; i <nPics; i++) {
        img[i] = loadImage("img_" +nf(i,3)+ ".jpg");
        imageMode(CORNERS);
      }

      //rand = int(random(0,687));
      //img[0]=loadImage("img_" + nf(rand,3)+ ".jpg");

    }
     
    void draw(){
    background(0);
      for(int i=0;i<nPics;i=i+3){  
         int col = i/3;
         for(int row=0;row<3;row++)
           image(img[i+row],col*w,row*h,(col+1)*w,(row+1)*h);
      }
      
    }

当您加载图像时,您使用的是 i 而不是 rand。为了在您单击鼠标时随机化图像,您可以使用 mousePressed() 将不同的图像重新加载到您的数组中。

这应该有效:

PImage img[];
int nPics;

int w, h;

void loadImages(){
  for (int i = 0; i < nPics; i++) {
    img[i] = loadImage("img_"+ nf(int(random(0, 687)), 3) + ".jpg");
    imageMode(CORNERS);
  }
}

void setup() {
  size(1500, 500);
  nPics=27;
  img = new PImage[nPics];

  w=width/9;  
  h=height/3; 

  loadImages();
}

void mousePressed(){
  loadImages();
}

void draw() {
  background(0);
  for (int i=0; i<nPics; i=i+3) {  
    int col = i/3;
    for (int row=0; row<3; row++)
      image(img[i+row], col*w, row*h, (col+1)*w, (row+1)*h);
  }
}