存档

2012年1月 的存档

Dynamic if-statement?

2012年1月18日 没有评论

I’m working on a Game of Life clone (can’t link wiki, as it’s down). The basic functionality is done, but I want to give the user the option to also define his own rules. The standard game of life rules are:

Cell with 2 or 3 neighbors keeps living.

Cell with 0-1 and 4-8 neighbors dies.

Dead cell with 3 neighbors becomes alive.

This is easy to do with 2 if-statements. But a user could also define something like:

Cell with 1-3 or 5-7 neighbors keeps living.

Cell with another number dies.

Dead cell with 2 or 4 neighbors becomes alive.

How can I implement this in if-statements? Can I use some sort of list to check against?

EDIT: I’m seeing some great solutions here. Will have to determine what fits my code best. For anyone still answering: I can properly handle user input, do not worry about that ;)

I will probably have a window where I ask How many neighbors to stay alive?, How many neighbours to become alive when dead?, with some textboxes. These will also check if the input is valid.

(This is C# in Unity3D)

I would only check those conditions that would make a cell dead. I would structure my function along the line:

bool CalculateIfDead(Cell c, int[] deadlyCountRules)
{       
   foreach(int n in deadlyCountRules)
   {
      if(c.NeighbourCount == n)
      {
         return true;
      }
   }
   return false;
}

I’d define an enum with values Propogate, Die, NoChange.

Then create a list/array, with an element of that type for each number of possibly neighbours (0 to 8). The user can then set this list some how (maybe a comma separated list of enums as strings, which is split then cast to the enum type).

Then all you’d do is count the neighbours and perform a lookup and act accordingly.

var UserActionList =
    "Die, Die, NoChange, NoChange, Propogate, Propogate, Die, Die, Die"
    .Split(',').Select(s => Enum.Parse(typeof(CellAction), s).ToArray();

// Count neighbours

swtich(UserActionList[NeighboursCount])
{
    case Die:
    /////

    case Propogate:
    /////
}

What you should probably have is something like a class

class DyingRule
{

   enum RuleResult{ Neutral , Death , Lives}; 

   //evaluates if according to this rule
   //death occurs.. pass parameter as needed
   RuleResult Evaluate();
}

And somewhere in your code you maintain a vector of them. Users are free to append the vector and add their own rules.

You evaluate them as

foreach ( currentRule in Rules )
   {
          RuleResult r = currentRule.Evaluate();
           if ( r ==  Death )
           {
                 ProcessDeath();
                 break;
           }
          else if ( r == Lives )
          {
                ProcessLiving();
                break;
          }
   } 

Optionally you can have priority for rules and sort them according if a rule supersedes another

Well, the primary problem is the “Cell with another number _” clause. There’s two options for that.

-Just disallow having that clause, and make the user specify exactly what numbers do what.

-Handle that clause as a special case last, and assign it any currently unassigned values.

The way I would implement it is with an array of #neighbours => IAction (IAction being one of Same, Kill or Grow). Since you only have a very finite number of possible neighbor counts, you can easily populate the map from the given data, and then you don’t even need any if statements, just a direct call to the IAction at the index if the array associated with the current number of neighbors.

Try a solution matix.

bool life[] = new bool[] {false, false, true, true, false, false, false, false, false};
bool die[] = new bool[] {true, true, false, false, true, true, true, true, true};
bool alive[] = new bool[] {false, false, false, true, false, false, false, false, false};

bool shouldLife=live[count];
bool shouldDie=die[count];
bool getAlive=alive[count];

this is more OO and design pattern question. Here you need something similar to strategy pattern.

http://www.oodesign.com/strategy-pattern.html

Well if the User is allowed to define unlimited number of rules you may need to translate, and validate User definitions and create a C# code file including a class, and run it through the CodeDom provider for C#, compile into an assembly, and execute. this file should return the resulkt of all if statetments which are generated from the User definition.

If the number of options is limited you can save a file in which you save a Vector which contains a binary array of all combinations which causes dead.

分类: stackoverflow精选, unity3d 标签:

Draw an UIImage with Core Graphics?

2012年1月9日 没有评论

I want to draw on screen an image retrieved from PhotoLibrary using CGContextRef or UIGraphicsBeginImageContext .

I tried the following code but it doesn’t draw anything on screen. I’m currently using cocos2d and box2d. What’s wrong?

-(void)imagePickerController:(UIImagePickerController *)picker
didFinishPickingMediaWithInfo:(NSDictionary *)info{

newImage = [info objectForKey:@"UIImagePickerControllerOriginalImage"];

// Dismiss UIImagePickerController and release it
[picker dismissModalViewControllerAnimated:YES];
[picker.view removeFromSuperview];
[picker release];

// Let's create a sprite now that we have an image

//CCSprite *imageFromPicker = [CCSprite spriteWithCGImage:newImage.CGImage key:@"ImageFromPicker"];
//[self addChild:imageFromPicker];


UIGraphicsBeginImageContext(CGSizeMake(320,480));

CGContextRef context = UIGraphicsGetCurrentContext();

[newImage drawAtPoint:CGPointZero];

CGContextTranslateCTM(context, 70, 370 );
CGContextScaleCTM(context, 1.0, -1.0);
//CGContextDrawImage(context, CGRectMake(0, 0, 40, 40), newImage.CGImage);
//CGImageRelease(newImage);
UIGraphicsEndImageContext();

}

You don’t tell Cocoa (touch or otherwise) to suddenly start drawing. It asks your app how it should draw certain views, and you tell it in the drawRect method of your view subclasses. At this point a graphics context is already created.

Your code is creating a graphics context and drawing to it, but this drawing is not done on screen.

To draw a specific image at a specific position, you would typically assign the image object to some view (like your sprite in the code above? I’m not familiar with cocos2d) which already knows how to draw an image. Then you’d put that view on the screen (your commented out addChild call?). You could add the necessary transform to the view object and this would be taken into account.

Briefly looking at the cocos2d documents, CCSprite inherits from CCNode, which can have a transform applied to it- you can set rotation and scale parameters. I suggest you look into that.

分类: cocos2d, stackoverflow精选 标签:

Can I use phonegap to build the same app for iOS and Android?

2012年1月1日 没有评论

I’m planning to make a tablet application using phonegap. In my presentation I want to keep five buttons.

  • First button is to load html page in phonegap application.

  • Second button is to load flash or unity3d app/apk in application.

  • Third button to load video

  • Fourth button to show video (half page) and half page for html page means at the same time I want to show html document and video on same page with the use of webview and videoview.

  • Fifth button is to load xml or sqlite generated quiz (multiple choice question)

So is it possible to load external applications using phonegap for both iOS and android? If is it possible than please tell me how to do it.

I want to make one application for iOS and android.

for using phonegap between IOS and android:

  • yes you can, but you must code the app to expand dynamically with the screen size due to the variation of screen sizes on android. This can be achieved with a fluid css layout.

for the second button on your app:

  • flash cannot be used on iphone and you cannot open an .app inside an iphone app.
  • as for android you can definitely open flash but i’m not sure you can launch an .apk

Yes, that is one of the major advantages of phonegap build. One zip file with your html/javascript/css code supports ios, android, blackberry, windows phone, and more. You do need to have an apple developer program account in order to build the ios app. This is a great tool that I have used multiple times.

Yes, this is the only purpose of PhoneGap. You need to first follow the steps to create the PhoneGap project for both the iOS and Android. For this, you can use the link :-

http://docs.phonegap.com/en/3.4.0/guide_cli_index.md.html#The%20Command-Line%20Interface

Now you can club your HTML/CSS/JS files into the common www folder, which you can use for any mobile platform which supports PhoneGap.

分类: stackoverflow精选, unity3d 标签: