How do I get a random number to stay fixed with slick? - random

I'm a beginner in Java as well as with the slick tools. I want to make a game that has different coloured cubes randomly placed within a certain area of the window.
I use two for-loops and call for a random number in render. I get the cubes placed exactly as I want, but the problems is that they flicker in all colours. I guess it has to do with how I call for a random number and that it gets updated with FPS?!
Please help me!!
public void render(GameContainer gc, StateBasedGame sdg, Graphics g) throws SlickException {
//set background
Image background = (new Image("res/background.png")).getScaledCopy(800, 500);
g.drawImage(background, 0, 0);
//set gamescape
blue = (new Image("res/blue.png")).getScaledCopy(20,20);
green = (new Image("res/green.png")).getScaledCopy(20,20);
red = (new Image("res/red.png")).getScaledCopy(20,20);
int xvalue = 300;
int yvalue = 400;
for (int a = 1; a < 20; a++) {
for (int i = 1; i < 10; i++) {
r = rand.nextInt(3);
if(r==0){g.drawImage(blue,xvalue,yvalue);}
else if(r==1){g.drawImage(red, xvalue, yvalue);}
else{g.drawImage(green, xvalue, yvalue);}
xvalue = xvalue+20;
}
yvalue = yvalue - 20;
xvalue = xvalue -180;
}
}

Your problem is that you generate a new random number each time you redraw the scene.
To resolve this, you may have to create an array in which you store the generated color of each cube. And each time you redraw your images, you just read each color value in the array.

Related

P5.js : manually calculate additive blendmode with pixels[]

I’m currently coding a P5.js program in which I draw some random generated patterns like this :
function setup() {
colorMode(RGB, 255, 255, 255, 255);
blendMode(ADD);
}
function draw() {
for(var i = 0; i < 20000; i++)
{
x = generateCoordinatesX();
y = generateCoordinateY();
var pointColor = generateColor(); //rgba
stroke(pointColor);
point(x, y);
}
}
When two ore more points get supperposed, they are displayed with additive BlendMode.
As the number of point is quite big, it slows down the simulation a lot. I tried to adapt this code with the pixels method like bellow to speed up things :
function draw() {
loadPixels();
for(var i = 0; i < 20000; i++)
{
x = generateCoordinatesX();
y = generateCoordinateY();
var index = (x + y * width)*4;
pixels[index+0] += ???;
pixels[index+1] += ???;
pixels[index+2] += ???;
pixels[index+3] += ???;
}
updatePixels();
}
The issue is that i dont know how to generate the R,G,B,A value so that it behave with additive Blending like my first version.
Is there a way to manually calculate this ? I tried with formulas i found but after some tests, the results are different.
Thanks in advance
There's a bunch of very helpful methods that will fill in this information for you. They are respectively named red, green, blue and alpha, and you can use them to extract the relevant information from a known color.
Here's a code snippet to demonstrate:
function setup() {
createCanvas(400, 400);
background(color(0, 255, 0));
}
function draw() {
}
function mouseClicked() {
let blendColor = color(128,0,0);
let density = pixelDensity();
loadPixels();
for (var i=0; i<width*height*density*4; i+=4)
{
pixels[i] += red(blendColor);
pixels[i+1] += green(blendColor);
pixels[i+2] += blue(blendColor);
pixels[i+3] += alpha(blendColor);
}
updatePixels();
}
Once you click on the canvas, it'll update the background color by adding the blendColor to the pixel array. I deliberately choose a color that you can blend more than once to demonstrate that there won't be any stack overflow if you try to blend two colors which should go over 8-bit (255) in intensity, so you can click more than once without fearing a crash.
Hope it helps. Have fun!

Wrong color when using loadPixels to copy image

I am trying to duplicate the ellipse such that its center point of the copy is the inverse of the original position in both axes using the pixels[] array to copy pixel data to new locations. However, the copy does not have the same color (rather than black, it is pink) as the original; the colors are not copying as I intended. Why is this?
This is the code:
function setup() {
createCanvas(600, 600);
smooth(8);
rectMode(CENTER);
fill(250);
stroke(32);
strokeWeight(10);
}
function draw() {
draw_();
}
function draw_() {
background(250);
ellipse(100, 100, 100, 100)
loadPixels();
for(var i=0; i<pixels.length/2; i++)
pixels[pixels.length-i-1] = pixels[i];
updatePixels();
}
This is the result:
According to the reference, the pixels array contains information in red, green, blue, and alpha components depending on index, like this:
pixels[0] = red(myColor);
pixels[1] = green(myColor);
pixels[2] = blue(myColor);
pixels[3] = alpha(myColor);
pixels[4] = red(myColor);
pixels[5] = green(myColor);
pixels[6] = blue(myColor);
pixels[7] = alpha(myColor);
//...
So if you simply reverse the array, you aren't going to just reverse the image. You're also going to mess up the colors: you'll swap red and alpha, and green and blue.
You might be better off using the get() function, which takes an x and y argument and returns a full color. Again, more info can be found in the reference.
Thanks a lot for Kevin's help, it's worked.
for(var i=0; i<pixels.length/2; i+=4) {
pixels[pixels.length-i-4] = pixels[i];
pixels[pixels.length-i-3] = pixels[i+1];
pixels[pixels.length-i-2] = pixels[i+2];
pixels[pixels.length-i-1] = pixels[i+3];
}

Creating Grid in as3

I am trying to make to grid to squares using as3.
I am using nested for loops to create the grid.
import flash.display.Shape;
import flash.display.MovieClip;
var n=10;
var myClip = new MovieClip;
stage.addChild(myClip);
for (var i = 0; i < n * 10; i += 10) {
for (var j = 0; j < n * 10; j += 10) {
var _shape = new Shape;
myClip.addChild(_shape);
_shape.graphics.lineStyle(1);
_shape.graphics.beginFill(0xcccccc);
_shape.graphics.drawRect(i, j, 10, 10);
_shape.graphics.endFill();
}
}
I am applying Zooming and Panning Gestures on myClip. For this Grid size everything works fine. As soon as I increase the value of n, it starts lagging
My game requires a bigger grid. Please help
I'll show some ideas as code, my AS3 is a bit rusty but perhaps it helps.
You can reduce the number of Shape instances or draw the vector based grid graphic to a Bitmap. Since you are zooming and panning it you'll want to smooth it. Depending on performance and how much you zoom you also may want to draw the bitmap at a higher resolution than initially used. See comments in the below.
import flash.display.Shape;
import flash.display.MovieClip;
var n=10;
// do you actually need dynamic binding or a timeline in this?
// if not (also if you don't know what it means) do use the Sprite class instead
var myClip = new MovieClip;
stage.addChild(myClip);
// if you don't need individual shapes move this out of the for loop
// your logic with all of the shapes having the same origin suggests this might be so
var _shape = new Shape;
myClip.addChild(_shape);
for (var i = 0; i < n * 10; i += 10) {
for (var j = 0; j < n * 10; j += 10) {
_shape.graphics.lineStyle(1);
_shape.graphics.beginFill(0xcccccc);
_shape.graphics.drawRect(i, j, 10, 10);
_shape.graphics.endFill();
}
}
// then we can draw the grid to a bitmap
// since you are scaling it I'm drawing it a 300% resolution
var _bmd:BitmapData = new BitmapData(_shape.width*3, _shape.height*3, true, 0);
var _bit:Bitmap = new Bitmap(_bmd);
myClip.addChild(_bit);
_shape.width*=3;
_shape.height*=3;
_bmd.draw(stage);
_bit.smoothing = true;
_bit.width/=3;
_bit.height/=3;
// and remove the vector shape so it won't be rendered
myClip.removeChild(_shape);
// if need be it can be redrawn later

Kinect Depth Histogram in Processing

I'm trying to create a histogram displaying the distances scanned by a Kinect vs. their occurrences. I've adapted the Histogram example code to create a depth histogram, but it's currently displaying the depth at each pixel (from left to right) multiple times across the depth image width.
What I'm looking to do is reorder the depth information so that it ranges from the lowest value (that isn't 0) to the highest on the x axis, and shows their occurrences on the y. I'm using Processing, so I'm unsure if this is the right site to be posting on, but I've tried on the posting forum and not gotten any help. If anyone can show me where I'm going wrong, that'd be awesome. My current code is below, and a screenshot of my current output can be found here
import SimpleOpenNI.*;
SimpleOpenNI kinect;
void setup() {
size(1200, 580);
kinect = new SimpleOpenNI(this);
kinect.enableDepth();
}
void draw () {
kinect.update();
PImage depthImage = kinect.depthImage();
image (depthImage, 11, 0);
int[] depthValues = kinect.depthMap();
int[] hist = new int[716800];
for (int x = 11; x < depthImage.width; x++) {
for (int y = 0; y < depthImage.height; y++) {
int i = x + y * 640;
hist[i] = depthValues[i];
}
}
int histMax = max(hist);
stroke(20);
for (int i = 0; i < depthImage.width; i += 2) {
int which = int(map(i, 0, depthImage.width, 0, histMax));
int y = int(map(hist[which], 0, histMax, depthImage.height, 0));
line(i, depthImage.height, i, y);
}
}
I think you're asking two questions here.
How to get the histogram to go from 0-N:
Use Processing's sort() function to sort the array.
hist = sort(hist); // sorts your array numerically
How to get the histogram to fill the screen:
I'm not entirely sure why it's drawing twice, but I think you can clean up your code quite a bit.
// how far apart are the bars - set based on screen dimensions
int barSpacing = width / hist.length;
for (int i=0; i<hist.length; i++) {
// get value and map into usable range (note 10 not 0 for min)
int h = int(map(hist[i], 0,histMax, 10,height));
// set x position onscreen
int x = i * barSpacing;
// draw the bar
line(x,height, x,height-h);
}

Pixel reordering is wrong when trying to process and display image copy with lower res

I'm currently making an application using processing intended to take an image and apply 8bit style processing to it: that is to make it look pixelated. To do this it has a method that take a style and window size as parameters (style is the shape in which the window is to be displayed - rect, ellipse, cross etc, and window size is a number between 1-10 squared) - to produce results similar to the iphone app pxl ( http://itunes.apple.com/us/app/pxl./id499620829?mt=8 ). This method then counts through the image's pixels, window by window averages the colour of the window and displays a rect(or which every shape/style chosen) at the equivalent space on the other side of the sketch window (the sketch when run is supposed to display the original image on the left mirror it with the processed version on the right).
The problem Im having is when drawing the averaged colour rects, the order in which they display becomes skewed..
Although the results are rather amusing, they are not what I want. Here the code:
//=========================================================
// GLOBAL VARIABLES
//=========================================================
PImage img;
public int avR, avG, avB;
private final int BLOCKS = 0, DOTS = 1, VERTICAL_CROSSES = 2, HORIZONTAL_CROSSES = 3;
public sRGB styleColour;
//=========================================================
// METHODS FOR AVERAGING WINDOW COLOURS, CREATING AN
// 8 BIT REPRESENTATION OF THE IMAGE AND LOADING AN
// IMAGE
//=========================================================
public sRGB averageWindowColour(color [] c){
// RGB Variables
float r = 0;
float g = 0;
float b = 0;
// Iterator
int i = 0;
int sizeOfWindow = c.length;
// Count through the window's pixels, store the
// red, green and blue values in the RGB variables
// and sum them into the average variables
for(i = 0; i < c.length; i++){
r = red (c[i]);
g = green(c[i]);
b = blue (c[i]);
avR += r;
avG += g;
avB += b;
}
// Divide the sum of the red, green and blue
// values by the number of pixels in the window
// to obtain the average
avR = avR / sizeOfWindow;
avG = avG / sizeOfWindow;
avB = avB / sizeOfWindow;
// Return the colour
return new sRGB(avR,avG,avB);
}
public void eightBitIT(int style, int windowSize){
img.loadPixels();
for(int wx = 0; wx < img.width; wx += (sqrt(windowSize))){
for(int wy = 0; wy < img.height; wy += (sqrt(windowSize))){
color [] tempCols = new color[windowSize];
int i = 0;
for(int x = 0; x < (sqrt(windowSize)); x ++){
for(int y = 0; y < (sqrt(windowSize)); y ++){
int loc = (wx+x) + (y+wy)*(img.width-windowSize);
tempCols[i] = img.pixels[loc];
// println("Window loc X: "+(wx+(img.width+5))+" Window loc Y: "+(wy+5)+" Window pix X: "+x+" Window Pix Y: "+y);
i++;
}
}
//this is ment to be in a switch test (0 = rect, 1 ellipse etc)
styleColour = new sRGB(averageWindowColour(tempCols));
//println("R: "+ red(styleColour.returnColourScaled())+" G: "+green(styleColour.returnColourScaled())+" B: "+blue(styleColour.returnColourScaled()));
rectMode(CORNER);
noStroke();
fill(styleColour.returnColourScaled());
//println("Rect Loc X: "+(wx+(img.width+5))+" Y: "+(wy+5));
ellipse(wx+(img.width+5),wy+5,sqrt(windowSize),sqrt(windowSize));
}
}
}
public PImage load(String s){
PImage temp = loadImage(s);
temp.resize(600,470);
return temp;
}
void setup(){
background(0);
// Load the image and set size of screen to its size*2 + the borders
// and display the image.
img = loadImage("oscilloscope.jpg");
size(img.width*2+15,(img.height+10));
frameRate(25);
image(img,5,5);
// Draw the borders
strokeWeight(5);
stroke(255);
rectMode(CORNERS);
noFill();
rect(2.5,2.5,img.width+3,height-3);
rect(img.width+2.5,2.5,width-3,height-3);
stroke(255,0,0);
strokeWeight(1);
rect(5,5,9,9); //window example
// process the image
eightBitIT(BLOCKS, 16);
}
void draw(){
//eightBitIT(BLOCKS, 4);
//println("X: "+mouseX+" Y: "+mouseY);
}
This has been bugging me for a while now as I can't see where in my code im offsetting the coordinates so they display like this. I know its probably something very trivial but I can seem to work it out. If anyone can spot why this skewed reordering is happening i would be much obliged as i have quite a lot of other ideas i want to implement and this is holding me back...
Thanks,

Resources