Showing posts with label code. Show all posts
Showing posts with label code. Show all posts

7/15/2009

BOOL in an Array, casting class type


BOOL aBool;
NSMutableArray *aMutableArray = [[NSMutableArray alloc] initWithObjects:[NSNumber numberWithBool:NO], nil];
aBool = [(NSNumber *)[aMutableArray objectAtIndex:0] boolValue];

6/21/2009

#pragma mark



This little tip will help you organize your code. It creates sections with bold fonts in your method pop ups like in the screenshot.

コードを整理するのに役に立つティップです。スクリーンショット参照。


#pragma mark Whatever you want to say

6/17/2009

if([myObject isKindOfClass:[UIView class]])

This gets pretty handy, the isKindOfClass: method. It's self explanatory, it gives you a boolean of whether if it is a certain class or not. I usually use it when I have random classes in an array and wants to do something with a specific class.

けっこうよく使うメソッドがこれ、isKindOfClass。配列にいろんなクラスをいれていて例えばUIViewのクラスならば、というふうな命令が下せる。


NSMutableArray *anArray = [[NSMutableArray alloc] init];
UIView *aView = [[UIView alloc] initWithFrame:CGRectMake(20, 20, 100, 100)];
[anArray addObject: [NSNumber numberWithInt:284]];
[anArray addObject: aView];
[anArray addObject: [NSString stringWithFormat:@"a string"]];

for (id aObject in anArray){
if([aObject isKindOfClass:[UIView class]]){
NSLog(@"aObject is a UIView: %@", aObject);
}
}

6/13/2009

NSSelectorFromString

I can pass in some strings as a parameter and then have it perform the selector method in the passed in method.

メソッドの名前をNSStringのパラメーターでうけとってそれを後でselectorとして扱う方法を発見。


- (void)performThis:(NSString *)aString {
SEL aSelector = NSSelectorFromString(aString);
[self performSelector:aSelector withObject:nil afterDelay:2];
}

6/12/2009

performSelectorOnMainThread

For some reason, I had the code below when I can just do [self addToBattleTextView:aString].
This was causing the thread to redraw the battle text in an arbitrary order. I don't need multiple threads for my game, bad idea for me to use it! It might have been ok if I had the waitUntilDone:YES, but I'm still novice to use multiple threads. Plus there's no good reason for me to use multiple threads at this point.

下記のコードを使っていたため戦闘メッセージがぐちゃぐちゃになってた。複数のスレッド使わなくていいのになんでこんなことになってたのか。。2時間ぐらい悩んでたyo、うぉにぃちゃん。大体スレッドの使い方把握してないし。

[self performSelectorOnMainThread:@selector(addToBattleTextView:) withObject:aString waitUntilDone:NO];

6/06/2009

Level up, player death

Player actually gains level, and they now die. I had a hard time adjusting the size of the xp bar as they are collected. Be careful of the UIIView's clipsToBounds, they should be set to YES if you want to resize its bounds and frame. Wasted about 1 hour why my view wasn't changing its size.

レベルアップ設置とプレイヤーのHPが0になったときに死んで店に0階へ飛ばされるようにした。経験値バーの幅を設定するときにUIViewのプロパティであるclipsToBoundsがNOになってたため幅がどうしても100%のままだった。1時間無駄にしてもうた。みなさん気をつけてください。

6/05/2009

Xcode keyboard shortcut tips

Here are three simple Xcode keyboard short cut tips.
Xcodeの便利なショートカットを連載。

1) The Escape key for bringing up suggestion commands for specific class.
ESCキーでクラスのメソッドやプロパティのリストを表示。


2) Command + Shift + D lets you quickly view the header file of highlighted class.
コマンド+シフト+Dで選択したヘダーファイルを表示。


3) Command + Option + Shift + ? opens up the Documentation. This Documentation gets very very handy.
コマンド+オプション+シフト+?でドキュメンテーションを開く。

6/03/2009

MVC, Singleton, Delegate, NSNotificationCenter

It's hard to come up with a correct design pattern for you program. One of the useful one is NSNotificationCenter where you can access a selector from anywhere in your code.

プログラミングのデザインパターンをうまく構成するのはなかなか難しい。そこで一つ使えるのがNSNotificationCenter。使い過ぎは要注意。

Create a notification:


[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(myMethod) name:@"myNotification" object:nil];


Call it from anywhere in your code:


[[NSNotificationCenter defaultCenter] postNotificationName:@"myNotification" object:nil userInfo:nil];

6/01/2009

Sell items

I finally implemented selling items at the shop. Added in info button for the items so that will will display detailed view of each items. It's an little property called accessoryView in UITableViewCell.

ショップでアイテムが売れるようになった。自分のアイテムのinfoも見れるようなった。UITableViewCellでaccessoryViewというのにボタンを指定するだけ。


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

....

UIButton *anAccessory = [UIButton buttonWithType:UIButtonTypeCustom];
UIImage *aImage = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"icon_info" ofType:@"png"]];
[anAccessory setBackgroundImage:aImage forState:UIControlStateNormal];
anAccessory.frame = CGRectMake(0, 0, 24, 24);
anAccessory.showsTouchWhenHighlighted = YES;
[anAccessory addTarget:self action:@selector(tappedAccessory:withEvent:) forControlEvents:UIControlEventTouchUpInside];
anAccessory.userInteractionEnabled = YES;
cell.accessoryView = anAccessory;



- (void)tappedAccessory:(UIControl *)button withEvent:(UIEvent *)event{
NSIndexPath *indexPath = [self.theTableView indexPathForRowAtPoint: [[[event touchesForView: button] anyObject] locationInView: self.theTableView]];
NSLog(@"%i", indexPath.row);
}

5/28/2009

Custom icon in UITableViewCell

Added icons by the items to indicate the item category such as weapons, armors, items, etc.
API made it really easy to do this.

アイテムの左側にアイテムジャンル(武器、防具など)を表示するアイコンを設置。ものすごく簡単にできる。

Inside this method in your UITableViewController:


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {


...put this:


UIImage *aIconImage = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"some_image" ofType:@"png"]];
cell.imageView.image = aIconImage;

5/27/2009

UIImageViewController


Getting images from your photo library is as easy as about... 10 lines of code. I was pretty impressed how the API made it so easy. I'm putting in some player profile picture feature in there.

写真アルバムから写真をゲットすんのにめちゃくちゃ簡単なことにびっくり。
ステータスに自分の写真を入れれるようにした。


@interface StatusViewController : UIViewController <UIImagePickerControllerDelegate, UINavigationControllerDelegate> {



- (IBAction)showImagePicker:(id)sender
{
UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
imagePickerController.delegate = self;
imagePickerController.allowsImageEditing = YES;
[self presentModalViewController:imagePickerController animated:YES];
[imagePickerController release];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
[self dismissModalViewControllerAnimated:YES];
}

5/25/2009

Some math for the first time!

I've never had to use more than arithmetic in before, but today I had to use arc cosine for the first time.
I'm drawing a line that from point A to point B, and below is the equation I had to use. Awesome stuff.

今日生まれて初めてプログラミングでコサインを使った。線をかくのに必要。


- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
CGPoint currentTouchPosition = [touch locationInView:self.view];
float deltaX2 = originalPoint.x - currentTouchPosition.x;
float deltaY2 = fabsf(originalPoint.y - currentTouchPosition.y);
float c = sqrt( pow(deltaY2,2) + pow(deltaX2,2));
float radian = acos( (deltaX2 / c ) );
if(originalPoint.y < currentTouchPosition.y) radian = -radian;
CGAffineTransform transformRadian = CGAffineTransformMakeRotation(radian);
theSlash.transform = transformRadian;

...

5/22/2009

UIImage cache or not to cache

There are different ways to display images. Cached or not cached. Apple employee at the forum said NOT to use the cache way, which is the + (UIImage *)imageNamed:(NSString *)name method in UIImage.
UIImageで絵をロードする時はキャッシュするやり方、 (UIImage *)imageNamed:(NSString *)name 、よりしないやり方のほうがいいらしい。

NSString *aFilePath = [[NSBundle mainBundle] pathForResource:@"mypicture" ofType:@"png"];
UIImage *aImage = [UIImage imageWithContentsOfFile:aFilePath];
UIImageView *aImageView = [[UIImageView alloc] initWithImage:aImage];

5/19/2009

Battle: Item usage

Items can be used during battle, but you cannot change equipment. I'm having problem using up the turn when the player uses the item. It sounds like a simple thing! UIAlertView is so handy. I wish I could customize the design though.
戦闘中のアイテムの使用はできるようになったけど、ターン終了がうまくいかない。UIAlertViewは使えるがデザインをカスタマイズできないのが残念。

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"This is UIAlertView" delegate:nil cancelButtonTitle:@"OKotherButtonTitles:nil];
[alert show];
[alert release];

5/15/2009

LanguageManager class

So I ended up writing my custom class called LanguageManager, which just holds all the strings that need to be translated and returns the strings.


LanguageManagerというクラスでlocalizationをすることに決定。オプションメニューでスイッチできるようにしたいので、アップルの自動的に認知するやつは使えなかった。


[LanguageManager translate:@"Start"];



+ (NSString *)translate:(NSString *)aString {
Settings *gameSettings = [Settings getInstance];
if (gameSettings.languageSettings == 0) return aString; // if user setting is English
if (gameSettings.languageSettings == 1){ //if user setting is Japanese
if(aString == @"Start") return @"スタート";
if(aString == @"Continue") return @"コンティニュー";
...


I wonder if there's any better way...
これでいいんかいな。

5/14/2009

Localization research

I've figured out how to do localization for the game before, but I wanted it so users (or me) can switch the language on the fly instead of going to the iPhone Settings.
完璧にlocalizationをする方法をサーチ。iPhoneの設定でやるより自分のアプリ内でやりたいしね〜。ほぼ自分のため。iPhone自体は英語で使いたくて、ゲームは日本語でしたいのです。

Some helpful links:

http://www.iphonesdkarticles.com/2008/11/localizing-iphone-apps.html

http://www.bdunagan.com/2009/03/15/ibtool-localization-made-easy/

http://developer.apple.com/documentation/MacOSX/Conceptual/BPInternational/Articles/InternatAndLocaliz.html#//apple_ref/doc/uid/20000277


To get what language the user is using:
ユーザーが何語を使ってるか:


NSArray *languages = [[NSUserDefaults standardUserDefaults] objectForKey:@"AppleLanguages"];
NSString *currentLanguage = [languages objectAtIndex:0];
NSLog(@"Current Locale: %@", [[NSLocale currentLocale] localeIdentifier]);
NSLog(@"Current language: %@", currentLanguage);
NSLog(@"Welcome Text: %@", NSLocalizedString(@"TitleKey", @""));

5/13/2009

Battle coding...

I think the battle system is working OK even though the code is very ugly... The more agility you have, the more attack you do.
バトルのコードはきれいじゃないけど、うまくいってる気がする。Agilityを100を超すとアタック。1ラウンドで100を超すと何回も攻撃するorされるシステム。素早さが命になるときもある。

This code would've saved me a million times if I knew this earlier... Often times, I need to execute something after X seconds.
これをもっと早くに知ってればどんだけ助かったことか。。X秒後に何か命令させるのを今までNSTimerでやってました。はっはっは。(T▽T)

[self performSelector:@selector(battle02:) withObject:NO afterDelay:1];

5/12/2009

NSThread, NSTimer

I need a good way to display these battle messages with little delay like 1 second. NSThread and NSTimer were my options. It seems to be working.
NSThreadとか見てみるけど、「◯◯の攻撃!」「◯○のダメージ!」というふうに1秒の間を作ってみる。NSTimerでやってみた。うまくいきそう。


NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[NSThread sleepForTimeInterval:0.3];
// do stuff here
[self performSelectorOnMainThread:@selector(addToBattleTextView:) withObject:aString waitUntilDone:NO];
[pool release];

5/05/2009

NSKeyedUnarchiver

Using NSKeyedUnarchiver to save player data and item data as an alternative to NSUserDefaults. I've read that NSUserDefaults isn't the best for storing huge amounts of data. Actually, the reason I migrated to NSKeyedUnarchiver is because I couldn't save some object or an array using NSUserDefaults. Now I can save the items I've purchased from the store. Learned how to use enum.
プレイヤーデータ、アイテムデータなどはNSUserDefaultsじゃなくてArchiverでセーブ。買ったアイテムをセーブできるようになった。enumの使い方もおぼえた。



theData = [NSData dataWithContentsOfFile:dataFilePath];
decoder = [[NSKeyedUnarchiver alloc] initForReadingWithData:theData];
Player *tempPlayer = [decoder decodeObjectForKey:@"playerData"];


- (void)savePlayerStateBeforeTerminate {
Player *player = [Player getInstance];
Player *tempPlayer = [[Player alloc] init];
tempPlayer = player;
NSMutableData *theData;
NSKeyedArchiver *encoder;
theData = [NSMutableData data];
encoder = [[NSKeyedArchiver alloc] initForWritingWithMutableData:theData];
[encoder encodeObject:tempPlayer forKey:@"playerData"];
[encoder finishEncoding];
[theData writeToFile:dataFilePath atomically:YES];
[encoder release];
}


Player.m

- (id)initWithCoder:(NSCoder *)decoder
{
playerLevel = [decoder decodeIntegerForKey:@"playerLevel"];
playerFloor = [decoder decodeIntegerForKey:@"playerFloor"];
playerRoom = [decoder decodeIntegerForKey:@"playerRoom"];
...
return self;
}

- (void)encodeWithCoder:(NSCoder *)coder {
//[super encodeWithCoder:coder];
[coder encodeInt:playerLevel forKey:@"playerLevel"];
[coder encodeInt:playerFloor forKey:@"playerFloor"];
...
}

5/01/2009

UITableViewController and copy, hooray!

Managed to use UITableViewController alright. I understood the concept of the copy method. I needed to copy the object with a new pointer from the items list. Before, I was just copying the pointer. It took me 3 hours of research how to copy object properly.
UITableViewControllerうまくいった。newItem = [aItem copy]しないとだめと気づく&リサーチで3時間ぐらいかかった。


- (id)copyWithZone:(NSZone *)zone {
id aCopy = [[[self class] alloc] init];
[aCopy setItemAbundancyPercent:[self itemAbundancyPercent]];
[aCopy setItemPrice:[self itemPrice]];
[aCopy setItemCategory:[self itemCategory]];
[aCopy setItemName:[self itemName]];
[aCopy setItemWeapon:[self itemWeapon]];
[aCopy setEffectPower:[self effectPower]];
[aCopy setItemAttributeNumber:[self itemAttributeNumber]];
[aCopy setItemDescription:[self itemDescription]];
[aCopy setIsEquipped:[self isEquipped]];
return aCopy;
}