jeudi 1 janvier 2015

Obj-C and SpriteKit - Changing a sprite value that is created randomly

I'm making a game using SpriteKit and Objective-C.


I have four different texture drops (Blue, Green, Orange and Red) that falls down on screen randomly.


In my ANBDropNode class I have this method:



+(instancetype)dropOfType:(ANBDropType)type {

ANBDropsNode *drop;

if (type == ANBDropTypeBlue) {
drop = [self spriteNodeWithImageNamed:@"bluedrop"];
} else if (type == ANBDropTypeGreen) {
drop = [self spriteNodeWithImageNamed:@"greendrop"];
} else if (type == ANBDropTypeOrange) {
drop = [self spriteNodeWithImageNamed:@"orangedrop"];
} else if (type == ANBDropTypeRed){
drop = [self spriteNodeWithImageNamed:@"reddrop"];
}

[drop setupPhysicsBody];
return drop;
}


And in my GamePlayScene these two:



-(void)addDrops {

NSUInteger randomDrop = [ANBUtil randomWithMin:0 max:4];

self.drop = [ANBDropsNode dropOfType:randomDrop];

float y = self.frame.size.height + self.drop.size.height;
float x = [ANBUtil randomWithMin:10 + self.drop.size.width
max:self.frame.size.width - self.drop.size.width - 10];
self.drop.position = CGPointMake(x, y);

[self addChild:self.drop];
}

-(void)update:(NSTimeInterval)currentTime {

if (self.lastUpdateTimeInterval) {
self.timeSinceDropAdded += currentTime - self.lastUpdateTimeInterval;
}

if (self.timeSinceDropAdded > 1) {
[self addDrops];
self.timeSinceDropAdded = 0;
}

self.lastUpdateTimeInterval = currentTime;

}


The question is (and it may sound a little dumber, I know): before the drop hits the ground it has already changed it value. If ANBDropNode *drop is a bluedrop, before it hits the ground the method randomly create another drop and change it value for greendrop, for example. But I don't want this behavior. I want the drop to continue with its value until it reaches the ground so I can detect its color in my didBeginContact method.





Can't generate random number

I'm trying to generate random numbers in a loop. I make an instance of the Random class before the loop starts, but it is inaccessible. The error i get is:



'System.Random.Sample()' is inaccessible due to its protection level



My code is:



Random random = new Random();
while (ready == false)
{
double h = random.Sample();
//Lots of things done here
}


What's wrong?





Why does creation of a Theano shared variable on GPU effect numpy's random streams?

I'm just starting to play with Theano, and am wondering why the first creation of a shared variable on the gpu seems to effect numpy's random number generator. At times this initial creation seems to advance the random number generator.


I've explored the following test cases in this code:



import numpy

import theano
from theano.compile.sharedvalue import shared
import theano.sandbox.cuda as tcn

def make_cpu_shared():
#Create, but don't return/use shared variable on cpu
shared(theano._asarray(numpy.asarray([.67]), dtype='float32'), 'cpu_shared')
return None

def make_gpu_shared():
#Create, but don't return/use shared variable on gpu
tcn.shared_constructor(theano._asarray(numpy.asarray([.67]), dtype='float32'), 'gpu_shared')
return None


def rand_test0():
#Match - Sanity check - Ensure numpy.random.seed creates repeatable random streams
numpy.random.seed(666) #Note: 666 seems to be seed used in Theano test suite
temp = numpy.random.rand(1)
print "temp[0]=",temp[0]

numpy.random.seed(666)
temp = numpy.random.rand(1)
print "temp[0]=",temp[0]

def rand_test1():
#Match - Show creation of shared variable on cpu has no effect on random streams
numpy.random.seed(666)
temp = numpy.random.rand(1)
print "temp[0]=",temp[0]

numpy.random.seed(666)
make_cpu_shared()
temp = numpy.random.rand(1)
print "temp[0]=",temp[0]

def rand_test2():
#No Match - Show creation of shared variable on gpu effects random streams
numpy.random.seed(666)
temp = numpy.random.rand(1)
print "temp[0]=",temp[0]

numpy.random.seed(666)
make_gpu_shared()
temp = numpy.random.rand(1)
print "temp[0]=",temp[0]

def rand_test3():
#Match - Show effect is only for initial creation of shared gpu variable
make_gpu_shared()

numpy.random.seed(666)
temp = numpy.random.rand(1)
print "temp[0]=",temp[0]

numpy.random.seed(666)
make_gpu_shared()
temp = numpy.random.rand(1)
print "temp[0]=",temp[0]

def rand_test4():
#No Match - Show initial creation of shared gpu variable effecting random streams
numpy.random.seed(666)
make_gpu_shared()
temp = numpy.random.rand(1)
print "temp[0]=",temp[0]

numpy.random.seed(666)
make_gpu_shared()
temp = numpy.random.rand(1)
print "temp[0]=",temp[0]



  1. rand_test0 - A sanity check to show I can reset a random stream using numpy.random.seed

  2. rand_test1 - Show creation of shared variable on cpu does nothing unexpected

  3. rand_test2 - Show creation of shared variable on gpu does have an unexpected effect

  4. rand_test3 - Show it is only the initial creation of the shared variable on the gpu with an unexpected effect

  5. rand_test4 - A verification of rand_test3


The results I got were as follows:



(Test 0 - Sanity Check)
me@Bedrock1:~/Projects/Theano/packageTests$ python
Python 2.7.6 (default, Mar 22 2014, 22:59:56)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from test_rand_shared import *
>>> rand_test0()
temp[0]= 0.700437121858
temp[0]= 0.700437121858
>>>

(Test 1 - Shared on CPU OK)
me@Bedrock1:~/Projects/Theano/packageTests$ python
Python 2.7.6 (default, Mar 22 2014, 22:59:56)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from test_rand_shared import *
>>> rand_test1()
temp[0]= 0.700437121858
temp[0]= 0.700437121858
>>>

(Test 2 - Shared on GPU effects random stream)
me@Bedrock1:~/Projects/Theano/packageTests$ python
Python 2.7.6 (default, Mar 22 2014, 22:59:56)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from test_rand_shared import *
>>> rand_test2()
temp[0]= 0.700437121858
Using gpu device 0: GeForce GTX 670MX
temp[0]= 0.859992279406
>>>

(Test 3 - Only initial creation of shared variable on GPU effects random stream)
me@Bedrock1:~/Projects/Theano/packageTests$ python
Python 2.7.6 (default, Mar 22 2014, 22:59:56)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from test_rand_shared import *
>>> rand_test3()
Using gpu device 0: GeForce GTX 670MX
temp[0]= 0.700437121858
temp[0]= 0.700437121858
>>>

(Test 4 - Variation on Test 3)
me@Bedrock1:~/Projects/Theano/packageTests$ python
Python 2.7.6 (default, Mar 22 2014, 22:59:56)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from test_rand_shared import *
>>> rand_test4()
Using gpu device 0: GeForce GTX 670MX
temp[0]= 0.859992279406
temp[0]= 0.700437121858
>>>


Does this make sense to anyone? Is it a Theano artifact? Is it a CUDA artifact, caused by my initial access to the GPU (i.e. the fact that I was playing with shared variables is only incidental to what I'm seeing). Or, am I misunderstanding something else?





Unity3D: Random Values Appear Identical?

In my breakout clone I'm trying to split the ball, at which point they assume random directions to move in. This direction is decided in the Start() of each ball instance. Upon observation is seems that the more balls I split, the more obvious it becomes that all balls move in the same direction, towards the upper-right corner of the screen. Can anyone help? Why are the values the same every time the balls split? This is my code:



// Use this for initialization
void Start ()
{
ballRB = transform.rigidbody;
direction = new Vector3(0,1,0);

//If there's only one ball in the field, being this current one, the default up motion should be used.
if (GameObject.Find("StartBall").GetComponent<StartBall>().numBalls <= 1) ballRB.AddForce(direction*1000f, ForceMode.Force);
//If not, there are more balls, which means the player split the ball. A random direction should be used in this case.
else ballRB.AddForce(GenerateRandomDirection(), ForceMode.Force);

}


Vector2 GenerateRandomDirection()
{
int randX = Random.Range(0,360);
int randY = Random.Range(0,360);
randDirection = new Vector2(randX, randY);
return randDirection;
}




Smooth transition for background-image script?

So I have a javascript that I found that finally works and changes my backgrounds. The thing is that the transition between the images is not smooth at all. Can someone help me out - I want a smooth transition, fade perhaps, between the images.



<script type="text/javascript">

var num;
var temp=0;
var speed=10000;
var preloads=[6];
preload(
'images/bg-1.jpg',
'images/bg-2.jpg',
'images/bg-3.jpg',
'images/bg-4.jpg',
'images/bg-5.jpg',
'images/bg-6.jpg',
'images/bg-7.jpg',
'images/bg-8.jpg',
'images/bg-9.jpg',
'images/bg-10.jpg',
'images/bg-11.jpg',
'images/bg-12.jpg',
'images/bg-13.jpg'
);

function preload(){

for(var c=0;c<arguments.length;c++) {
preloads[preloads.length]=new Image();
preloads[preloads.length-1].src=arguments[c];
}
}

function rotateImages() {
num=Math.floor(Math.random()*preloads.length);
if(num==temp){
rotateImages();
}
else {
document.body.style.backgroundImage='url('+preloads[num].src+')';
temp=num;

setTimeout(function(){rotateImages()},speed);
}
}

if(window.addEventListener){
window.addEventListener('load',rotateImages,false);
}
else {
if(window.attachEvent){
window.attachEvent('onload',rotateImages);
}
}
</script>




Weight selection of index from NSArray

Given an NSArray of objects eg [NSArray arrayWithObjects:A, B, C, D, E, nil], I can choose a random set of N objects from the array by using a for loop and an arc4random function e.g.



NSArray *objArray = [NSArray arrayWithObjects:A, B, C, D, E, nil];
NSMutableArray *newArray = [NSMutableArray alloc] init];
for(int i=0;i<N;i++){

id randIndex = arc4random() % N;
[newArray addObject:[objArray objectAtIndex:randIndex];
}


This works fine, but what I'd like is to be able to specify a weighting for each of the elements in objArray that defines how likely that element is to be selected by the randIndex. It seems this selection could be dependent on previous selections (or not).



NSArray *weights = [NSArray arrayWithObjects:@1, @0.5, @1, @1, @1]; would mean:

A - 1
B - 0.5 // 0.5 times as likely to appear
C - 0.3 // 0.3 times as likely to appear
D - 0.1 // 0.1x times as likely to appear
E - 0 // Will never appear


etc so the weights above would lead to having more object A's and no object E's. Thanks.





mercredi 31 décembre 2014

arc4random on Xcode for C

I want to do a multiplications quiz using random numbers from 2 variables. I tried to use this:



int answ

int rand1= (arc4random()%10)+1;

int rand2= (arc4random()%20)+1;

printf("\n¿What is %d * %d?: ", rand1, rand2);

scanf("%d", &answ);

if (answ==rand1*rand2)
printf("\nCorrect answer!");
else
printf("\Incorrect answer, the result was %d", rand1*rand2);


My problem is that both random numbers does not change when the next question is asked. I also tried adding srand(time(NULL)) and the same.. (I already have the library stdlib.h added)


What´s missing?