I have an integer high score. But I don't know how save the best of it and show on the screen.
This is my code, thank for your help.
-(void)aggiungiPunti
{
punteggio = punteggio +0001;
[labelPunteggio setString:[NSString stringWithFormat:#"%d", punteggio]];
}
And in the init method:
labelPunteggio = [CCLabelTTF labelWithString:#"0000" fontName:#"Marker Felt" fontSize:13];
labelPunteggio.position = ccp(30, altezzaSchermo -15);
[self addChild:labelPunteggio];
U can do this :
write this code in app delegate:
[[NSUserDefaults standardUserDefaults] setInteger:0 forKey:#"key"]
In the class where the top score is to be displayed :
if([punteggio intValue]>[[[NSUserDefaults standardUserDefaults] valueForKey:#"key"]intValue])
{
//display the score in the desired label
[labelPunteggio setString:[NSString stringWithFormat:#"%d", punteggio]];
// set the new best score in the userDefault
[[NSUserDefaults standardUserDefaults] setInteger:[punteggio intValue] forKey:#"key"];
}
Related
This question already has an answer here:
High score and current score
(1 answer)
Closed 9 years ago.
I want to show on the screen the current score of the gameplay and the storical best score. It is work, but every times i restart the game the best score change even if the current score is lower than the best score.
CCLabelTTF *punteggio;
NSString *stringa;
NSString *stringa2;
CCLabelTTF *punteggioMAX;
int score;
int scoreMAX;
There are the methods to SAVE the score, to add the score and to reset the score at the end of the game.
-(void)aum{
score++;
stringa = [NSString stringWithFormat:#"Punteggio: %d",score];
[punteggio setString:stringa];
}
-(void)res{
score=0;
stringa = [NSString stringWithFormat:#"Punteggio: %d",score];
[punteggio setString:stringa];
}
-(void)sal{
NSUserDefaults *ud=[NSUserDefaults standardUserDefaults];
[ud setInteger:score forKey:#"Punteggio"];
[ud synchronize];
}
-(void)sal2{
NSUserDefaults *ud=[NSUserDefaults standardUserDefaults];
[ud setInteger:scoreMAX forKey:#"Punteggio"];
[ud synchronize];
}
And in the init method:
NSString *fontName = #"score.fnt";
stringa = [NSString stringWithFormat:#"Punteggio: %d",score];
punteggio = [CCLabelBMFont labelWithString:stringa fntFile:fontName];
punteggio.scale = 0.4;
punteggio.position=ccp(40,altezzaSchermo - 15);
[self addChild:punteggio];
NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
score=[ud integerForKey:#"Punteggio"];
stringa2 = [NSString stringWithFormat:#"Best Score: %d",score];
punteggioMAX = [CCLabelBMFont labelWithString:stringa2 fntFile:fontName];
punteggioMAX.scale = 0.4;
punteggioMAX.position=ccp(40,altezzaSchermo - 35);
[self addChild:punteggioMAX];
scoreMAX=[ud integerForKey:#"punteggioMAX"];
if(score>scoreMAX) scoreMAX = score;
[self res];
Thank you.
you are saving max score with the wrong key. Try :
-(void)sal2{
NSUserDefaults *ud=[NSUserDefaults standardUserDefaults];
[ud setInteger:scoreMAX forKey:#"punteggioMAX"];
[ud synchronize];
}
I try to explain better the situation.
The variables are:
int punteggio;
CCLabelTTF *labelPunteggio;
Then in the init metod i print my score on the screen:
- (id)init {
if ((self = [super init])) {
// PUNTEGGIO
labelPunteggio = [CCLabelTTF labelWithString:#"0000" fontName:#"Marker Felt" fontSize:13];
[self addChild:labelPunteggio];
....
}
}
And this is the function to add score on Punteggio: for example, every time i kill a monster i add 10 point.
-(void)aggiungiPunti
{
punteggio = punteggio +0001;
[labelPunteggio setString:[NSString stringWithFormat:#"%d", punteggio]];
}
But now, i don't know how save the score when the player do game over.
I'd want save this score, and then print the high score on the screen,
i think about
-(void) setScore:(int)score
{
punteggio = highScore;
if (punteggio>highScore)
{
highScore = punteggio;
}
}
Thank you!
Use NSUserdefaults
// Snippet used to save your highscore in the prefs.
int highScore = yourGameScore;
[[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithInt:highScore] forKey:#"HighScore"];
[[NSUserDefaults standardUserDefaults] synchronize];
//In Game Over screen
// Get your highscore from the prefs.
highScore = [[[NSUserDefaults standardUserDefaults] objectForKey:#"HighScore"] intValue ];
look at this link and you can use SettingManager class to do this work for you. i have used settingManager class for storing highscore.
Hope this will help
Like the game helicopter or like Left 4 dead survival mode I want the score to stay and only change if score is surpassed. Here is the code I have so far.
./m file
_score = 0;
_oldScore = -1;
self.scoreLabel = [CCLabelTTF labelWithString:#"" dimensions:CGSizeMake(100, 50) alignment:UITextAlignmentRight fontName:#"Marker Felt" fontSize:32];
_scoreLabel.position = ccp(winSize.width - _scoreLabel.contentSize.width, _scoreLabel.contentSize.height);
_scoreLabel.color = ccc3(255,0,0);
[self addChild:_scoreLabel z:1];
if (_score != _oldScore) {
_oldScore = _score;
[_scoreLabel setString:[NSString stringWithFormat:#"score%d", _score]];
}
and the .h file
int _score;
int _oldScore;
CCLabelTTF *_scoreLabel;
I tried to put
_score = [[NSUserDefaults standardUserDefaults] integerForKey:#"score"];
[[NSUserDefaults standardUserDefaults] setInteger:_oldScore forKey:#"score"];
[[NSUserDefaults standardUserDefaults] synchronize];
but when i did that it only saved the data and keeps going up rather than starting over and only change when score is surpassed.
You need to compare if your score is more than the old score and just save it then.
For example,
if (_score > _oldscore) {
// Save out new score as it is more than the old score
// Then reset ready for next time
_oldscore = _score;
_score = 0;
}
However, if you are struggling with something like this, I would suggest you are going to be in for a whole lot of problems unless you stop and learn the basics of programming now before progressing further in your development.
Please can anyone refer me to a tutorial or help me out with this problem. I wish to display high scores and other games statistics at game Over but I don't seem to get a headway despite looking at tutorials and trying stuff out. I don't seem to understand how to use NSUserdefaults to achieve this.
My codes are as follows:
Gameplaylayer.mm
- (id)initWithHUDLayer:(HUDLayer *)hudLayer {
if ((self = [super init]))
{
score = 0;
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSDictionary *defaultArray = [NSDictionary dictionaryWithObject:[NSArray arrayWithObjects:[NSNumber numberWithInt:0],
[NSNumber numberWithInt:0],
[NSNumber numberWithInt:0],
[NSNumber numberWithInt:0],
[NSNumber numberWithInt:0],
nil]
forKey:#"Scores"];
[defaults registerDefaults:defaultArray];
[defaults synchronize];
}
return self;
}
-(void)gameOver:(id)sender{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSMutableArray *HighScores = [NSMutableArray arrayWithArray:[defaults arrayForKey:#"Scores"]];
for (unsigned int i = 0; i < [HighScores count]; i++)
{
if (dist >= [[HighScores objectAtIndex:i] intValue])
{
[HighScores insertObject:[NSNumber numberWithInt:dist] atIndex:i];
[HighScores removeLastObject];
[defaults setObject:HighScores forKey:#"Scores"];
[defaults synchronize];
NSLog(#"Saved new high score of %i", dist);
break;
}
}
}
-(void)update:(ccTime)dt {
CGSize winSize = [CCDirector sharedDirector].winSize;
score += (int)delta;
dist = score - 18;
if (!gameOver )
{
if (!lives)
{
gameOver = true;
[self gameOver];
}
}
}
my game over layer is as follows
-(id)init {
self = [super init];
if (self != nil)
{
self.isTouchEnabled = YES;
CGSize windowSize = [CCDirector sharedDirector].winSize;
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSArray *HighScores = [defaults arrayForKey:#"Scores"];
CLabelTTF *title = [CCLabelTTF labelWithString:#"high scores" fontName:#"Courier" fontSize:32.0];
[title setPosition:ccp(screenSize.width / 2, screenSize.height - title.contentSize.height)];
[self addChild:title];
NSMutableString *scoresString = [NSMutableString stringWithString:#""];
for (unsigned int i = 0; i < [HighScores count]; i++)
{
[scoresString appendFormat:#"%i. %i\n", i + 1, [[HighScores objectAtIndex:i] intValue]];
}
CCLOG(#"scores saved %i", dist);
CCLabelTTF *scoresLabel = [CCLabelTTF labelWithString:scoresString dimensions:CGSizeMake(screenSize.width, screenSize.height / 3) alignment:CCTextAlignmentCenter fontName:#"Courier" fontSize:40.0];
[scoresLabel setPosition:ccp(screenSize.width / 2, screenSize.height / 2)];
scoresLabel.color = ccc3(0, 0, 0);
[self addChild:scoresLabel z:9];
}
return self;
}
It's hard to understand your code, please look at this small example below.
Ok, that's saving new score, assuming you have GameController singleton, where scores mutable array is declared and currentScore in that singleton also displays current player's score.
-(void) saveScores {
GameController * controller = [GameController sharedController];
for(int i=0; i<5;i++)
{
if([[[controller.scores objectAtIndex:i] objectForKey:#"score"] intValue] == controller.finalscore)
{
break;
}
if([[[controller.scores objectAtIndex:i] objectForKey:#"score"] intValue] < controller.finalscore) {
for(int j=5;j>i+1;j--)
{
[controller.scores replaceObjectAtIndex:j-1 withObject:[controller.scores objectAtIndex:j-2]];
}
NSMutableDictionary *newEntry = [NSMutableDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:controller.finalscore],#"score",#"Local player",#"name", nil];
[controller.scores replaceObjectAtIndex:i withObject:newEntry];
break;
}
}
controller.currentScore=0;
[[NSUserDefaults standardUserDefaults] setObject:controller.scores forKey:#"OurScores"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
You can see, that we are saving updated scores in NSUserDefaults. So, at our game start we shoul load them. I added this code to GameController init method:
- (void) loadScores {
if([[NSUserDefaults standardUserDefaults] objectForKey:#"OurScores"] == nil)
{
NSMutableDictionary *empty = [NSMutableDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:0],#"score",#"empty",#"name", nil];
for(int i=0;i<5;i++)
[scores addObject:empty];
}
else
{
NSLog(#"Loading scores");
scores = [[NSUserDefaults standardUserDefaults] objectForKey:#"OurScores"];
}
}
And that's how we can show this scores using cocos2d:
-(void) drawScores {
for(int i=0; i<5; i++)
{
CCLabelTTF* score = [CCLabelTTF labelWithString:
[NSString stringWithFormat:#"%#",[[controller.scores objectAtIndex:i] objectForKey:#"name"]] fontName:#"Marker Felt" fontSize:30];
score.anchorPoint=ccp(0,0);
score.position = ccp(115, 180-i*35);
CCLabelTTF* score2 = [CCLabelTTF labelWithString:
[NSString stringWithFormat:#"%d",[[[controller.scores objectAtIndex:i] objectForKey:#"score"] intValue] ] fontName:#"Marker Felt" fontSize:35];
score2.anchorPoint=ccp(0,0);
score2.position = ccp(280, 180-i*35);
score.color=currentClr;
score2.color=currentClr;
[self addChild: score z:3 tag:i];
[self addChild: score2 z:3 tag:i+15];
}
}
Your code has a number of problems, some of which just break with convention but all together they make your program quite unreadable. I have not been able to make sense of it. You are not using comments, nor are you telling us, what exactly is not working.
For instance, you might consider following the convention of having instance variables start with small letters, reserving capitalized names for classes. It is generally a bad idea to give misleading names, such as calling an NSDictinoary "defaultArray". Also, try to use empty lines more sparingly to structure your code for better readability.
That being said, this is how you set a default value:
[[NSUserDefaults standardUserDefaults] setValue:scoreArray
forKey:#"Score"];
I see you know how to retrieve the score.
As for your updating routine, consider that it is normally not a good idea to modify the array your iterating through (in your particular case it could still work, but it is not guaranteed). Also, there is no need to store the whole array in the loop. Just save it once you have contructed the complete new high score array.
Otherwise your code is working, right?
I have 3 UIVIewControllers that have NSUsuerDefaults to store data. My 4th UIViewController is used to display the total data collected between the first 3 UIViewControllers. How do I collect the data and display it in a UITextfield? Here is an example of my NSUserDefault code that I'm using:
[tex setText:[[NSUserDefaults standardUserDefaults] objectForKey:#"storedTextValue1"]];
[tex setText:[[NSUserDefaults standardUserDefaults] objectForKey:#"storedTextValue22"]];
[tex setText:[[NSUserDefaults standardUserDefaults] objectForKey:#"storedTextValue43"]]; I want to add this collected data to a UITextfield on my 4th UIViewController.
Try this:
textField.text = [[NSUserDefaults standardUserDefaults] objectForKey:#"storedTextValue1"];
Or
NSString *storedValue1 = [[NSUserDefaults standardUserDefaults] objectForKey:#"storedTextValue1"];
textField.text = storedValue1;
I think you should use
tex setText:[[NSUserDefaults standardUserDefaults] valueForKey:#"storedTextValue43"];
So basically you need to use valueForKey: in place of objectForKey:
Hope this helps you.
EDIT:
[text setText:[NSString stringWithFormat:#"%# %# %#",[[NSUserDefaults standardUserDefaults] valueForKey:#"storedTextValue43"],[[NSUserDefaults standardUserDefaults] valueForKey:#"storedTextValue1"],[[NSUserDefaults standardUserDefaults] valueForKey:#"storedTextValue22"]]];
EDIT-2:
UITextField(Total) is Say txtTotal
UITextField(storetext1) is say txtStore1
UITextField(storetext2) is say txtStore2
UITextField(storetext3) is say txtStore3
Now simply do this as
int sum = [txtStore1.text intValue] + [txtStore2.text intValue] + [txtStore3.text intValue]
txtTotal.text = [NSString stringWithFormat:#%d",sum];