IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Composants graphiques Android Discussion :

[Persistance] Sauvegarder état d'une Activity lors rotation


Sujet :

Composants graphiques Android

Vue hybride

Message précédent Message précédent   Message suivant Message suivant
  1. #1
    Membre émérite
    Avatar de tails
    Homme Profil pro
    Inscrit en
    Novembre 2003
    Messages
    799
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 45
    Localisation : France, Pyrénées Atlantiques (Aquitaine)

    Informations forums :
    Inscription : Novembre 2003
    Messages : 799
    Billets dans le blog
    15
    Par défaut [Persistance] Sauvegarder état d'une Activity lors rotation
    Bonjour, j'ai un petit soucis. J'ai développé la base d'une application TicTacToe pour Android API >= 3 (Android 1.5). Elle est fonctionnelle ... mais une sensation utilisateur risque encore de le "faire fuire" : à la rotation de mon application, tout est perdu !!!

    En effet, j'utilise "une sorte" de Canvas dont je définis moi-même le remplissage (je n'ai pas actuellement la source avec moi), et je garde un tableau de 3*3 int, mais je n'ai pas encore géré la persistance/restauration du tableau.

    Ce qui me dérange, c'est de savoir où, dans quelles méthodes (onStart, onCreate, onResume, onPause ...) ai-je intérêt à gérer la persistance (pour information j'opte pour le système de fichier -> openFile{Output/Input}() ). Sachant que je voudrais que, quelle que soit la raison pour laquelle je perds à priori le dernier état du Canvas, l'utilisateur ne puisse pas le remarquer.

    En clair :
    ApplicationTicTacToe -> appel, appui sur return, mise à mort de l'application,... -> retour demandé par utilisateur ou système -> le dernier état est conservé.

    Désolé si ma question n'est pas très bien posée.

  2. #2
    Expert confirmé

    Avatar de Feanorin
    Profil pro
    Inscrit en
    Avril 2004
    Messages
    4 589
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Avril 2004
    Messages : 4 589
    Par défaut
    En clair :
    ApplicationTicTacToe -> appel, appui sur return, mise à mort de l'application,... -> retour demandé par utilisateur ou système -> le dernier état est conservé.
    Ben alors ca n'a rien avoir avec la rotation ????
    Si c'est la cas tu peux essayer de sauvegarder ton état dans les Préférences

    PreferenceManager

    http://developer.android.com/referen...ceManager.html

  3. #3
    Membre émérite
    Avatar de tails
    Homme Profil pro
    Inscrit en
    Novembre 2003
    Messages
    799
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 45
    Localisation : France, Pyrénées Atlantiques (Aquitaine)

    Informations forums :
    Inscription : Novembre 2003
    Messages : 799
    Billets dans le blog
    15
    Par défaut Si si : la rotation fait redessiner le Canvas
    Si si j'insiste, avec la manière que j'ai codé l'appli (cet après-midi je pourrais poster quelques sources), le Canvas est redessiné lors de la rotation (peut être parce que j'ai mal géré le cycle de vie de l'Acitivity et ai mis le code de création du Canvas dans le mauvais onXXXX)

    En ce qui concerne les préférences, je ne préfère pas opter pour cette solution : car il s'agit de sauvegarde automatique et l'utilisateur n'aura pas eu à le demander (SQLite ? Trop lourd pour sauvegarde 9 petits Integer !)

  4. #4
    Rédacteur
    Avatar de MrDuChnok
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Juin 2002
    Messages
    2 112
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 41
    Localisation : France

    Informations professionnelles :
    Activité : Ingénieur développement logiciels
    Secteur : High Tech - Produits et services télécom et Internet

    Informations forums :
    Inscription : Juin 2002
    Messages : 2 112
    Par défaut
    Salut,

    Je pense cerné un peu ton problème.
    Je te conseille la lecture de ce paragraphe :
    http://d.android.com/guide/topics/fu...s.html#actlife
    Et plus particulièrement :
    Saving activity state

    When the system, rather than the user, shuts down an activity to conserve memory, the user may expect to return to the activity and find it in its previous state.

    To capture that state before the activity is killed, you can implement an onSaveInstanceState() method for the activity. Android calls this method before making the activity vulnerable to being destroyed — that is, before onPause() is called. It passes the method a Bundle object where you can record the dynamic state of the activity as name-value pairs. When the activity is again started, the Bundle is passed both to onCreate() and to a method that's called after onStart(), onRestoreInstanceState(), so that either or both of them can recreate the captured state.

    Unlike onPause() and the other methods discussed earlier, onSaveInstanceState() and onRestoreInstanceState() are not lifecycle methods. They are not always called. For example, Android calls onSaveInstanceState() before the activity becomes vulnerable to being destroyed by the system, but does not bother calling it when the instance is actually being destroyed by a user action (such as pressing the BACK key). In that case, the user won't expect to return to the activity, so there's no reason to save its state.

    Because onSaveInstanceState() is not always called, you should use it only to record the transient state of the activity, not to store persistent data. Use onPause() for that purpose instead.

  5. #5
    Membre émérite
    Avatar de tails
    Homme Profil pro
    Inscrit en
    Novembre 2003
    Messages
    799
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 45
    Localisation : France, Pyrénées Atlantiques (Aquitaine)

    Informations forums :
    Inscription : Novembre 2003
    Messages : 799
    Billets dans le blog
    15
    Par défaut Merci beaucoup : je vais tester le codage dans le onPause
    Citation Envoyé par MrDuChnok Voir le message
    Salut,

    Je pense cerné un peu ton problème.
    Je te conseille la lecture de ce paragraphe :
    http://d.android.com/guide/topics/fu...s.html#actlife
    Et plus particulièrement :
    Merci beaucoup, c'est exactement l'information dont j'avais besoin
    Je vais tester et mettre résolu si j'y suis parvenu.

    ----------------------------------------------------

    Par ailleurs, j'ai récupéré les sources de mon projet, et semble-t-il j'avais bien mal géré la chose
    -> une Activity TicTacToe, qui dispose que de la méthode onCreate, notamment :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
     
    @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(new BoardView(this));
        }
    -> une BoardView héritant tout simplement de la classe View (où sont notamment redéfinies les méthodes onDraw, onSizeChanged de View)
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
    337
    338
    339
    340
    341
    342
    343
    344
    345
    346
    347
    348
    349
    350
    351
    352
    353
    354
    355
    356
    357
    358
    359
    360
    361
    362
    363
    364
    365
    366
    367
    368
    369
    370
    371
    372
    373
    374
    375
    376
    377
    378
    379
    380
    381
    382
    383
    384
    385
    386
    387
    388
    389
    390
    391
    392
    393
    394
    395
    396
    397
    398
    399
    400
    401
    402
    403
    404
    405
    406
    407
    408
    409
    410
    411
    412
    413
    414
    415
    416
    417
    418
    419
    420
    421
    422
    423
    424
    425
    426
    427
    428
    429
    430
    431
    432
    433
    434
    435
    436
    437
    438
    439
    440
    441
    442
    443
    444
    445
    446
    447
    448
    449
    450
    451
    452
    453
    454
    455
    456
    457
    458
    459
    460
    461
    462
    463
    464
    465
    466
    467
    468
    469
    470
    471
    472
    473
    474
    475
    476
    477
    478
    479
    480
     
    public class BoardView extends View {
     
    	private final int LINES_WEIGHT;
    	private final int PIECES_WEIGHT;
    	private final byte CELLS_PER_DIM;
    	private final byte BORDER_LINES_PER_DIM;
     
    	private float cell_dim;
    	private float pieces_dim;
    	private boolean min_dim_is_width = true;
    	private int total_board_dim;
     
    	private byte [][] players_ids;
     
    	private int cursor_grid_matrix_x;
    	private int cursor_grid_matrix_y;
    	/*
    	 * 0 for none player
    	 * > 0 for player 1
    	 * < 0 for player 2
    	 */
    	private byte current_player;
    	private boolean end_game;
     
    	private final TicTacToeActivity context;
     
    	public BoardView(Context context) {
    		super(context);
     
    		this.context = (TicTacToeActivity) context;
     
    		LINES_WEIGHT = getResources().getInteger(R.id.board_lines_weight);
    		PIECES_WEIGHT = getResources().getInteger(R.id.board_pieces_weight);
    		CELLS_PER_DIM = (byte) getResources().getInteger(R.id.board_cells_per_dim);
    		BORDER_LINES_PER_DIM = (byte) getResources().getInteger(R.id.board_border_lines_per_dim);
     
    		players_ids = new byte[CELLS_PER_DIM][CELLS_PER_DIM];
    		end_game = false;
     
    		setFocusable(true);
    		setFocusableInTouchMode(true);
    		newGame();
    	}
     
    	public void newGame(){
     
    		current_player = 1; // set to player 1
    		cursor_grid_matrix_x = 0;
    		cursor_grid_matrix_y = 0;
    		for (byte cellMatrixLine = 0; cellMatrixLine < CELLS_PER_DIM; cellMatrixLine++){
    			for (byte cellMatrixColumn = 0; cellMatrixColumn < CELLS_PER_DIM; cellMatrixColumn++){
    				players_ids[cellMatrixColumn][cellMatrixLine] = 0; // set to none player
    			}
    		}
    	}
     
    	public void tryToPlayIn(int gridMatrixX, int gridMatrixY){
    		if (players_ids[gridMatrixX][gridMatrixY] == 0){
    			players_ids[gridMatrixX][gridMatrixY] = current_player;
    			invalidate(getCursorRect());
    			byte winner_id = winner();
    			if (winner_id != 0){
    				String winner_text = "";
    				String key_input_asking = getResources().getString(R.string.endgame_key_input_asking);
    				if (winner_id > 0){
    					winner_text = getResources().getString(R.string.circles_win);
    				}
    				else {
    					winner_text = getResources().getString(R.string.crosses_win);
    				}
    				Toast.makeText(
    						context,
    						winner_text+"\n"+key_input_asking,
    						Toast.LENGTH_LONG
    				).show();
    				end_game = true;
    				return;
    			}
    			if (board_filled()){
    				String no_winner_text = getResources().getString(R.string.no_winner_text);
    				String key_input_asking = getResources().getString(R.string.endgame_key_input_asking);
    				Toast.makeText(
    						context,
    						no_winner_text+"\n"+key_input_asking,
    						Toast.LENGTH_LONG
    				).show();
    				end_game = true;
    				return;
    			}
    			current_player *= -1; // change player
    		}
    	}
     
    	public void onSizeChanged(int width, int height, int oldWidth, int oldHeight){
    		int min_dim = -1;
    		if (width < height){
    			min_dim = width;
    			min_dim_is_width = true;
    		}
    		else {
    			min_dim = height;
    			min_dim_is_width = false;
    		}
    		cell_dim = (min_dim - LINES_WEIGHT * BORDER_LINES_PER_DIM) / CELLS_PER_DIM;
    		pieces_dim = .8f * cell_dim;
    		total_board_dim = (int) (BORDER_LINES_PER_DIM * LINES_WEIGHT + CELLS_PER_DIM * cell_dim);
    		super.onSizeChanged(width, height, oldWidth, oldHeight);
    	}
     
    	public void onDraw(Canvas canvas){
     
    		paintBackground(canvas);
    		drawGridBorders(canvas);
    		paintDroppingZone(canvas);
    		drawPieces(canvas);	
    		drawCursor(canvas);
     
    	}
     
    	private void drawPieces(Canvas canvas) {
    		for (byte cellMatrixLine = 0; cellMatrixLine < CELLS_PER_DIM; cellMatrixLine++){
    			for (byte cellMatrixColumn = 0; cellMatrixColumn < CELLS_PER_DIM; cellMatrixColumn++){
    				byte currentPlayerId = players_ids[cellMatrixColumn][cellMatrixLine];
    				if (currentPlayerId > 0){
    					drawCirclePiece(canvas, cellMatrixColumn, cellMatrixLine);
    				}
    				else if(currentPlayerId < 0){
    					drawCrossPiece(canvas, cellMatrixColumn, cellMatrixLine);
    				}
    			}
    		}
    	}
     
    	private void drawCursor(Canvas canvas){
    		Paint cursorColor = new Paint();
    		cursorColor.setStyle(Style.FILL);
    		cursorColor.setColor(getResources().getColor(R.color.board_cursor_color));
     
    		Rect cellRect = getCursorRect();
     
    		canvas.drawRect(cellRect, cursorColor);
    	}
     
    	private Rect getCursorRect(){
    		return new Rect(
    				(int) (LINES_WEIGHT + cursor_grid_matrix_x * (cell_dim + LINES_WEIGHT)),
    				(int) (LINES_WEIGHT + cursor_grid_matrix_y * (cell_dim + LINES_WEIGHT)),
    				(int) (LINES_WEIGHT + cursor_grid_matrix_x * (cell_dim + LINES_WEIGHT) + cell_dim -1),
    				(int) (LINES_WEIGHT + cursor_grid_matrix_y * (cell_dim + LINES_WEIGHT) + cell_dim -1)
    		);
    	}
     
    	private void paintDroppingZone(Canvas canvas) {
    		Paint bottom_zone_color = new Paint();
    		bottom_zone_color.setColor(getResources().getColor(R.color.board_dropping_zone_color));
    		bottom_zone_color.setStyle(Style.FILL);
    		Rect dropping_zone_rect;
    		if (min_dim_is_width){
    			dropping_zone_rect = new Rect(
    				0,
    				total_board_dim,
    				getWidth(),
    				getHeight()
    			);
    		}
    		else {
    			dropping_zone_rect = new Rect(
    				total_board_dim,
    				0,
    				getWidth(),
    				getHeight()
    			);
    		}
    		canvas.drawRect(
    				dropping_zone_rect,
    				bottom_zone_color
    		);
    	}
     
    	private void drawGridBorders(Canvas canvas) {
    		Paint line_color = new Paint();
    		line_color.setColor(getResources().getColor(R.color.board_lines_color));
    		// Drawing lines
    		for(int line = 0; line < BORDER_LINES_PER_DIM; line++){
    			for (int lineNumber = 0; lineNumber < LINES_WEIGHT; lineNumber++) {
    				canvas.drawLine(
    						0,
    						line * (cell_dim + LINES_WEIGHT)+lineNumber,
    						total_board_dim,
    						line * (cell_dim + LINES_WEIGHT)+lineNumber,
    						line_color
    				);
    			}
    		}
    		// Drawing columns
    		for(int column = 0; column < BORDER_LINES_PER_DIM; column++){
    			for (int lineNumber = 0; lineNumber < LINES_WEIGHT; lineNumber++) {
    				canvas.drawLine(
    						column * (cell_dim + LINES_WEIGHT)+lineNumber,
    						0,
    						column * (cell_dim + LINES_WEIGHT)+lineNumber,
    						total_board_dim,
    						line_color
    				);
    			}
    		}
    	}
     
    	private void paintBackground(Canvas canvas) {
    		Paint background_color = new Paint();
    		background_color.setColor(getResources().getColor(R.color.board_background));
    		background_color.setStyle(Style.FILL);
    		canvas.drawRect(0,0,getWidth(),getHeight(), background_color);
    	}
     
    	private void drawCrossPiece(Canvas canvas, int gridMatrixX, int gridMatrixY){
     
    		Paint crossColor = new Paint();
    		crossColor.setStyle(Style.STROKE);
    		crossColor.setColor(getResources().getColor(R.color.board_crosses_color));
     
    		final float CELL_X = LINES_WEIGHT + gridMatrixX * (cell_dim + LINES_WEIGHT);
    		final float CELL_Y = LINES_WEIGHT + gridMatrixY * (cell_dim + LINES_WEIGHT);
    		final float CELL_PADING = (cell_dim - pieces_dim) / 2;
     
    		for (int lineIndex = 0; lineIndex < PIECES_WEIGHT; lineIndex++){
    			float lineStart_X = CELL_X + CELL_PADING + lineIndex;
    			float lineEnd_X = lineStart_X + pieces_dim - PIECES_WEIGHT;
    			float lineStart_Y = CELL_Y + CELL_PADING;
    			float lineEnd_Y = CELL_Y + cell_dim - CELL_PADING - 1;
     
    			canvas.drawLine(lineStart_X, lineStart_Y, lineEnd_X, lineEnd_Y, crossColor);
     
    			lineStart_X = CELL_X + cell_dim -1 - CELL_PADING - lineIndex;
    			lineEnd_X = lineStart_X - pieces_dim + PIECES_WEIGHT;
     
    			canvas.drawLine(lineStart_X, lineStart_Y, lineEnd_X, lineEnd_Y, crossColor);
    		}
    	}
     
    	private void drawCirclePiece(Canvas canvas, int gridMatrixX, int gridMatrixY){
    		Paint circleColor = new Paint();
    		circleColor.setStyle(Style.STROKE);
    		circleColor.setColor(getResources().getColor(R.color.board_circles_color));
     
    		final float CELL_X = LINES_WEIGHT + gridMatrixX * (cell_dim + LINES_WEIGHT);
    		final float CELL_Y = LINES_WEIGHT + gridMatrixY * (cell_dim + LINES_WEIGHT);
    		final float CELL_PADING = (cell_dim - pieces_dim) / 2;
    		final float CELL_CENTER_X = CELL_X + cell_dim / 2;
    		final float CELL_CENTER_Y = CELL_Y + cell_dim / 2; 
     
    		for (int lineIndex = 0; lineIndex < PIECES_WEIGHT; lineIndex++){
    			float radius = cell_dim/2 - CELL_PADING - lineIndex;
    			canvas.drawCircle(CELL_CENTER_X, CELL_CENTER_Y, radius, circleColor);
    		}
    	}
     
    	public boolean onKeyDown(int keyCode, KeyEvent event){
    		if ( ! end_game ) {
    			switch (keyCode) {
    			case KeyEvent.KEYCODE_BACK:
    				context.finish();
    				break;
    			case KeyEvent.KEYCODE_DPAD_UP:
    				invalidate(getCursorRect());
    				cursorTopOrToColumnEnd();
    				invalidate(getCursorRect());
    				break;
    			case KeyEvent.KEYCODE_DPAD_DOWN:
    				invalidate(getCursorRect());
    				cursorDownOrToColumnStart();
    				invalidate(getCursorRect());
    				break;
    			case KeyEvent.KEYCODE_DPAD_LEFT:
    				invalidate(getCursorRect());
    				cursorLeftOrToRowEnd();
    				invalidate(getCursorRect());
    				break;
    			case KeyEvent.KEYCODE_DPAD_RIGHT:
    				invalidate(getCursorRect());
    				cursorRightOrToRowStart();
    				invalidate(getCursorRect());
    				break;
    			case KeyEvent.KEYCODE_ENTER:
    			case KeyEvent.KEYCODE_DPAD_CENTER:
    				tryToPlayIn(cursor_grid_matrix_x, cursor_grid_matrix_y);
    				break;
    			default:
    				return super.onKeyDown(keyCode, event);
    			}
    		}
    		else {
    			context.finish();
    		}
    		return true;
    	}
     
    	private void cursorLeftOrToRowEnd(){
    		cursor_grid_matrix_x -= 1;
    		if (cursor_grid_matrix_x < 0){
    			cursor_grid_matrix_x = CELLS_PER_DIM - 1;
    		}
    	}
     
    	private void cursorRightOrToRowStart(){
    		cursor_grid_matrix_x += 1;
    		if (cursor_grid_matrix_x >= CELLS_PER_DIM){
    			cursor_grid_matrix_x = 0;
    		}
    	}
     
    	private void cursorTopOrToColumnEnd(){
    		cursor_grid_matrix_y -= 1;
    		if (cursor_grid_matrix_y < 0){
    			cursor_grid_matrix_y = CELLS_PER_DIM - 1;
    		}
    	}
     
    	private void cursorDownOrToColumnStart(){
    		cursor_grid_matrix_y += 1;
    		if (cursor_grid_matrix_y >= CELLS_PER_DIM){
    			cursor_grid_matrix_y = 0;
    		}
    	}
     
    	public boolean onTouchEvent(MotionEvent event){
    		if (event.getAction() == MotionEvent.ACTION_DOWN){
    			if ( ! end_game ) {
    				float x = event.getX();
    				float y = event.getY();
    				float nearest_left_border_start = x - x
    						% (LINES_WEIGHT + cell_dim);
    				float nearest_left_border_end = nearest_left_border_start
    						+ LINES_WEIGHT - 1;
    				float nearest_top_border_start = y - y
    						% (LINES_WEIGHT + cell_dim);
    				float nearest_top_border_end = nearest_top_border_start
    						+ LINES_WEIGHT - 1;
    				// is pointed area in the board ?
    				if (x >= 0 && x < total_board_dim && y >= 0
    						&& y < total_board_dim) {
    					// is pointed area NOT in a border line ?
    					if (x > nearest_left_border_end
    							&& y > nearest_top_border_end) {
    						int matrixX = (int) (nearest_left_border_start / (LINES_WEIGHT + cell_dim));
    						int matrixY = (int) (nearest_top_border_start / (LINES_WEIGHT + cell_dim));
     
    						// set cursor to pointed cell
    						cursor_grid_matrix_x = matrixX;
    						cursor_grid_matrix_y = matrixY;
     
    						tryToPlayIn(matrixX, matrixY);
    					} else {
    						Toast.makeText(
    								context,
    								getResources().getString(
    										R.string.on_border_line_click),
    								Toast.LENGTH_SHORT).show();
    					}
    				} else {
    					Toast.makeText(
    							context,
    							getResources().getString(
    									R.string.out_of_board_click),
    							Toast.LENGTH_SHORT).show();
    				}
    			}
    			else {
    				context.finish();
    			}
    		}
    		return true;
    	}
     
    	private byte winner(){
    		byte the_winner;
     
    		the_winner = lineWinner();
    		if (the_winner != 0){
    			return the_winner;
    		}
     
    		the_winner = columnWinner();
    		if (the_winner != 0){
    			return the_winner;
    		}
     
    		return diagonals_winner();
    	}
     
    	private byte lineWinner(){
    		byte the_winner = 0; // set to none
    		byte winner_combos = 1;
    		for (int line = 0; line < CELLS_PER_DIM; line++){
    			if ( players_ids[0][line] == 0 ){
    				continue;
    			}
    			winner_combos = 1;
    			the_winner = players_ids[0][line];
    			for(int column = 1; column < CELLS_PER_DIM; column++){
    				if (players_ids[column][line] * the_winner <= 0){ // different player or none player ?
    					break;
    				}
    				winner_combos++;
    			}
    			if (winner_combos == CELLS_PER_DIM){
    				return the_winner;
    			}
    		}
    		return 0;
    	}
     
    	private byte columnWinner(){
    		byte the_winner = 0; // set to none
    		byte winner_combos = 1;
    		for (int column = 0; column < CELLS_PER_DIM; column++){
    			if ( players_ids[column][0] == 0 ){
    				continue;
    			}
    			winner_combos = 1;
    			the_winner = players_ids[column][0];
    			for(int line = 1; line < CELLS_PER_DIM; line++){
    				if (players_ids[column][line] * the_winner <= 0){ // different player or none player ?
    					break;
    				}
    				winner_combos++;
    			}
    			if (winner_combos == CELLS_PER_DIM){
    				return the_winner;
    			}
    		}
    		return 0;
    	}
     
    	private byte diagonals_winner(){
    		byte the_winner;
     
    		the_winner = players_ids[0][0];
    		if (the_winner != 0){
    			int winner_combos = 1;
    			for (int progression = 1; progression < CELLS_PER_DIM; progression++){
    				if (players_ids[progression][progression] * the_winner <= 0){
    					break;
    				}
    				winner_combos++;
    			}
    			if (winner_combos == CELLS_PER_DIM){
    				return the_winner;
    			}
    		}
     
    		the_winner = players_ids[CELLS_PER_DIM - 1][0];
    		if (the_winner != 0){
    			int winner_combos = 1;
    			for (int progression = 1; progression < CELLS_PER_DIM; progression++){
    				if (players_ids[CELLS_PER_DIM - 1 - progression][progression] * the_winner <= 0){
    					break;
    				}
    				winner_combos++;
    			}
    			if (winner_combos == CELLS_PER_DIM){
    				return the_winner;
    			}
    		}
     
    		return 0;
    	}
     
    	private boolean board_filled(){
    		for (int line_id = 0; line_id < CELLS_PER_DIM; line_id++){
    			for (int column_id = 0; column_id < CELLS_PER_DIM; column_id++){
    				if (players_ids[column_id][line_id] == 0){
    					return false;
    				}
    			}
    		}
    		return true;
    	}
    }

  6. #6
    Membre émérite
    Avatar de tails
    Homme Profil pro
    Inscrit en
    Novembre 2003
    Messages
    799
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 45
    Localisation : France, Pyrénées Atlantiques (Aquitaine)

    Informations forums :
    Inscription : Novembre 2003
    Messages : 799
    Billets dans le blog
    15
    Par défaut Réussi !!! Merci à vous :)
    Ca y est j'ai réussi

    Merci beaucoup : il s'agissait bien des méthodes onPause et onResume.
    J'ai fait appel à openFileOutput/openFileInput pour obtenir les streams afin de stocker les fichiers.

    Merci

    ------------------------------------------------------------------------

    Pour ceux que cela intéresse, voici les deux fichiers mis à jour
    -> ajout des méthodes onPause et onResume dans TicTacToeActivity
    -> ajout des méthodes getSerialisationBytes et setValuesFromUnSerialisarion dans la classe BoardView
    C'est là que toute la sauvagarde est implémentée

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
     
    public class TicTacToeActivity extends Activity {
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            boardView = new BoardView(this);
            setContentView(boardView);
        }
     
    	@Override
    	protected void onPause() {
    		super.onPause();
    		FileOutputStream output = null;
    		try {
    			output = openFileOutput(currentBoardSavingFile, MODE_PRIVATE);
    			output.write(boardView.getSerialisationBytes());
    		} catch (FileNotFoundException exception) {
    			exception.printStackTrace();
    		} catch (IOException exception) {
    			exception.printStackTrace();
    		} finally {
    			try {
    				output.close();
    			} catch (IOException exceptionIO) {
    				exceptionIO.printStackTrace();
    			} catch (NullPointerException exceptionNullPointer){
    				exceptionNullPointer.printStackTrace();
    			}
    		}
    	}
     
    	@Override
    	protected void onResume() {
    		super.onResume();
    		FileInputStream input = null;
    		try {
    			byte [] unserialisationBytesValues = new byte[10];
    			input = openFileInput(currentBoardSavingFile);
    			input.read(unserialisationBytesValues);
    			boardView.setValuesFromUnSerialisarion(unserialisationBytesValues);
    		} catch (FileNotFoundException exception) {
    			exception.printStackTrace();
    		} catch (IOException exception) {
    			exception.printStackTrace();
    		} finally {
    			try {
    				input.close();
    			} catch (IOException exceptionIO) {
    				exceptionIO.printStackTrace();
    			} catch (NullPointerException exceptionNullPointer){
    				exceptionNullPointer.printStackTrace();
    			}
    		}
    	}
     
    	private String currentBoardSavingFile = "TicTacToe_currentBoard";
    	private BoardView boardView;
    }
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
    337
    338
    339
    340
    341
    342
    343
    344
    345
    346
    347
    348
    349
    350
    351
    352
    353
    354
    355
    356
    357
    358
    359
    360
    361
    362
    363
    364
    365
    366
    367
    368
    369
    370
    371
    372
    373
    374
    375
    376
    377
    378
    379
    380
    381
    382
    383
    384
    385
    386
    387
    388
    389
    390
    391
    392
    393
    394
    395
    396
    397
    398
    399
    400
    401
    402
    403
    404
    405
    406
    407
    408
    409
    410
    411
    412
    413
    414
    415
    416
    417
    418
    419
    420
    421
    422
    423
    424
    425
    426
    427
    428
    429
    430
    431
    432
    433
    434
    435
    436
    437
    438
    439
    440
    441
    442
    443
    444
    445
    446
    447
    448
    449
    450
    451
    452
    453
    454
    455
    456
    457
    458
    459
    460
    461
    462
    463
    464
    465
    466
    467
    468
    469
    470
    471
    472
    473
    474
    475
    476
    477
    478
    479
    480
    481
    482
    483
    484
    485
    486
    487
    488
    489
    490
    491
    492
    493
    494
    495
    496
    497
    498
    499
    500
    501
    502
    503
    504
    505
    506
    507
     
    public class BoardView extends View {
     
    	private final int LINES_WEIGHT;
    	private final int PIECES_WEIGHT;
    	private final byte CELLS_PER_DIM;
    	private final byte BORDER_LINES_PER_DIM;
     
    	private float cell_dim;
    	private float pieces_dim;
    	private boolean min_dim_is_width = true;
    	private int total_board_dim;
     
    	// x as first dim
    	private byte [][] players_ids;
     
    	private int cursor_grid_matrix_x;
    	private int cursor_grid_matrix_y;
    	/*
    	 * 0 for none player
    	 * > 0 for player 1
    	 * < 0 for player 2
    	 */
    	private byte current_player;
    	private boolean end_game;
     
    	private final TicTacToeActivity context;
     
    	public BoardView(Context context) {
    		super(context);
     
    		this.context = (TicTacToeActivity) context;
     
    		LINES_WEIGHT = getResources().getInteger(R.id.board_lines_weight);
    		PIECES_WEIGHT = getResources().getInteger(R.id.board_pieces_weight);
    		CELLS_PER_DIM = (byte) getResources().getInteger(R.id.board_cells_per_dim);
    		BORDER_LINES_PER_DIM = (byte) getResources().getInteger(R.id.board_border_lines_per_dim);
     
    		players_ids = new byte[CELLS_PER_DIM][CELLS_PER_DIM];
    		end_game = false;
     
    		setFocusable(true);
    		setFocusableInTouchMode(true);
    		newGame();
    	}
     
    	public byte[] getSerialisationBytes() {
    		byte serialisationValues [] = new byte[10];
     
    		for (int x = 0; x < 3; x++){
    			for (int y = 0; y < 3; y++){
    				serialisationValues[3*x + y] = players_ids[x][y];
    			}
    		}
    		serialisationValues[9] = current_player;
     
    		return serialisationValues;
    	}
     
    	public void setValuesFromUnSerialisarion(byte [] unserialisationValues){
    		for (int x = 0; x < 3; x++){
    			for (int y = 0; y < 3; y++){
    				players_ids[x][y] = unserialisationValues[3*x + y];
    			}
    		}
    		current_player = unserialisationValues[9];
    	}
     
    	public void setBoardValueAtXY(int x, int y, byte value){
    		players_ids[x][y] = value;
    	}
     
    	public void newGame(){
     
    		current_player = 1; // set to player 1
    		cursor_grid_matrix_x = 0;
    		cursor_grid_matrix_y = 0;
    		for (byte cellMatrixLine = 0; cellMatrixLine < CELLS_PER_DIM; cellMatrixLine++){
    			for (byte cellMatrixColumn = 0; cellMatrixColumn < CELLS_PER_DIM; cellMatrixColumn++){
    				players_ids[cellMatrixColumn][cellMatrixLine] = 0; // set to none player
    			}
    		}
    	}
     
    	public void tryToPlayIn(int gridMatrixX, int gridMatrixY){
    		if (players_ids[gridMatrixX][gridMatrixY] == 0){
    			players_ids[gridMatrixX][gridMatrixY] = current_player;
    			invalidate(getCursorRect());
    			byte winner_id = winner();
    			if (winner_id != 0){
    				String winner_text = "";
    				String key_input_asking = getResources().getString(R.string.endgame_key_input_asking);
    				if (winner_id > 0){
    					winner_text = getResources().getString(R.string.circles_win);
    				}
    				else {
    					winner_text = getResources().getString(R.string.crosses_win);
    				}
    				Toast.makeText(
    						context,
    						winner_text+"\n"+key_input_asking,
    						Toast.LENGTH_LONG
    				).show();
    				end_game = true;
    				return;
    			}
    			if (board_filled()){
    				String no_winner_text = getResources().getString(R.string.no_winner_text);
    				String key_input_asking = getResources().getString(R.string.endgame_key_input_asking);
    				Toast.makeText(
    						context,
    						no_winner_text+"\n"+key_input_asking,
    						Toast.LENGTH_LONG
    				).show();
    				end_game = true;
    				return;
    			}
    			current_player *= -1; // change player
    		}
    	}
     
    	public void onSizeChanged(int width, int height, int oldWidth, int oldHeight){
    		int min_dim = -1;
    		if (width < height){
    			min_dim = width;
    			min_dim_is_width = true;
    		}
    		else {
    			min_dim = height;
    			min_dim_is_width = false;
    		}
    		cell_dim = (min_dim - LINES_WEIGHT * BORDER_LINES_PER_DIM) / CELLS_PER_DIM;
    		pieces_dim = .8f * cell_dim;
    		total_board_dim = (int) (BORDER_LINES_PER_DIM * LINES_WEIGHT + CELLS_PER_DIM * cell_dim);
    		super.onSizeChanged(width, height, oldWidth, oldHeight);
    	}
     
    	public void onDraw(Canvas canvas){
     
    		paintBackground(canvas);
    		drawGridBorders(canvas);
    		paintDroppingZone(canvas);
    		drawPieces(canvas);	
    		drawCursor(canvas);
     
    	}
     
    	private void drawPieces(Canvas canvas) {
    		for (byte cellMatrixLine = 0; cellMatrixLine < CELLS_PER_DIM; cellMatrixLine++){
    			for (byte cellMatrixColumn = 0; cellMatrixColumn < CELLS_PER_DIM; cellMatrixColumn++){
    				byte currentPlayerId = players_ids[cellMatrixColumn][cellMatrixLine];
    				if (currentPlayerId > 0){
    					drawCirclePiece(canvas, cellMatrixColumn, cellMatrixLine);
    				}
    				else if(currentPlayerId < 0){
    					drawCrossPiece(canvas, cellMatrixColumn, cellMatrixLine);
    				}
    			}
    		}
    	}
     
    	private void drawCursor(Canvas canvas){
    		Paint cursorColor = new Paint();
    		cursorColor.setStyle(Style.FILL);
    		cursorColor.setColor(getResources().getColor(R.color.board_cursor_color));
     
    		Rect cellRect = getCursorRect();
     
    		canvas.drawRect(cellRect, cursorColor);
    	}
     
    	private Rect getCursorRect(){
    		return new Rect(
    				(int) (LINES_WEIGHT + cursor_grid_matrix_x * (cell_dim + LINES_WEIGHT)),
    				(int) (LINES_WEIGHT + cursor_grid_matrix_y * (cell_dim + LINES_WEIGHT)),
    				(int) (LINES_WEIGHT + cursor_grid_matrix_x * (cell_dim + LINES_WEIGHT) + cell_dim -1),
    				(int) (LINES_WEIGHT + cursor_grid_matrix_y * (cell_dim + LINES_WEIGHT) + cell_dim -1)
    		);
    	}
     
    	private void paintDroppingZone(Canvas canvas) {
    		Paint bottom_zone_color = new Paint();
    		bottom_zone_color.setColor(getResources().getColor(R.color.board_dropping_zone_color));
    		bottom_zone_color.setStyle(Style.FILL);
    		Rect dropping_zone_rect;
    		if (min_dim_is_width){
    			dropping_zone_rect = new Rect(
    				0,
    				total_board_dim,
    				getWidth(),
    				getHeight()
    			);
    		}
    		else {
    			dropping_zone_rect = new Rect(
    				total_board_dim,
    				0,
    				getWidth(),
    				getHeight()
    			);
    		}
    		canvas.drawRect(
    				dropping_zone_rect,
    				bottom_zone_color
    		);
    	}
     
    	private void drawGridBorders(Canvas canvas) {
    		Paint line_color = new Paint();
    		line_color.setColor(getResources().getColor(R.color.board_lines_color));
    		// Drawing lines
    		for(int line = 0; line < BORDER_LINES_PER_DIM; line++){
    			for (int lineNumber = 0; lineNumber < LINES_WEIGHT; lineNumber++) {
    				canvas.drawLine(
    						0,
    						line * (cell_dim + LINES_WEIGHT)+lineNumber,
    						total_board_dim,
    						line * (cell_dim + LINES_WEIGHT)+lineNumber,
    						line_color
    				);
    			}
    		}
    		// Drawing columns
    		for(int column = 0; column < BORDER_LINES_PER_DIM; column++){
    			for (int lineNumber = 0; lineNumber < LINES_WEIGHT; lineNumber++) {
    				canvas.drawLine(
    						column * (cell_dim + LINES_WEIGHT)+lineNumber,
    						0,
    						column * (cell_dim + LINES_WEIGHT)+lineNumber,
    						total_board_dim,
    						line_color
    				);
    			}
    		}
    	}
     
    	private void paintBackground(Canvas canvas) {
    		Paint background_color = new Paint();
    		background_color.setColor(getResources().getColor(R.color.board_background));
    		background_color.setStyle(Style.FILL);
    		canvas.drawRect(0,0,getWidth(),getHeight(), background_color);
    	}
     
    	private void drawCrossPiece(Canvas canvas, int gridMatrixX, int gridMatrixY){
     
    		Paint crossColor = new Paint();
    		crossColor.setStyle(Style.STROKE);
    		crossColor.setColor(getResources().getColor(R.color.board_crosses_color));
     
    		final float CELL_X = LINES_WEIGHT + gridMatrixX * (cell_dim + LINES_WEIGHT);
    		final float CELL_Y = LINES_WEIGHT + gridMatrixY * (cell_dim + LINES_WEIGHT);
    		final float CELL_PADING = (cell_dim - pieces_dim) / 2;
     
    		for (int lineIndex = 0; lineIndex < PIECES_WEIGHT; lineIndex++){
    			float lineStart_X = CELL_X + CELL_PADING + lineIndex;
    			float lineEnd_X = lineStart_X + pieces_dim - PIECES_WEIGHT;
    			float lineStart_Y = CELL_Y + CELL_PADING;
    			float lineEnd_Y = CELL_Y + cell_dim - CELL_PADING - 1;
     
    			canvas.drawLine(lineStart_X, lineStart_Y, lineEnd_X, lineEnd_Y, crossColor);
     
    			lineStart_X = CELL_X + cell_dim -1 - CELL_PADING - lineIndex;
    			lineEnd_X = lineStart_X - pieces_dim + PIECES_WEIGHT;
     
    			canvas.drawLine(lineStart_X, lineStart_Y, lineEnd_X, lineEnd_Y, crossColor);
    		}
    	}
     
    	private void drawCirclePiece(Canvas canvas, int gridMatrixX, int gridMatrixY){
    		Paint circleColor = new Paint();
    		circleColor.setStyle(Style.STROKE);
    		circleColor.setColor(getResources().getColor(R.color.board_circles_color));
     
    		final float CELL_X = LINES_WEIGHT + gridMatrixX * (cell_dim + LINES_WEIGHT);
    		final float CELL_Y = LINES_WEIGHT + gridMatrixY * (cell_dim + LINES_WEIGHT);
    		final float CELL_PADING = (cell_dim - pieces_dim) / 2;
    		final float CELL_CENTER_X = CELL_X + cell_dim / 2;
    		final float CELL_CENTER_Y = CELL_Y + cell_dim / 2; 
     
    		for (int lineIndex = 0; lineIndex < PIECES_WEIGHT; lineIndex++){
    			float radius = cell_dim/2 - CELL_PADING - lineIndex;
    			canvas.drawCircle(CELL_CENTER_X, CELL_CENTER_Y, radius, circleColor);
    		}
    	}
     
    	public boolean onKeyDown(int keyCode, KeyEvent event){
    		if ( ! end_game ) {
    			switch (keyCode) {
    			case KeyEvent.KEYCODE_BACK:
    				context.finish();
    				break;
    			case KeyEvent.KEYCODE_DPAD_UP:
    				invalidate(getCursorRect());
    				cursorTopOrToColumnEnd();
    				invalidate(getCursorRect());
    				break;
    			case KeyEvent.KEYCODE_DPAD_DOWN:
    				invalidate(getCursorRect());
    				cursorDownOrToColumnStart();
    				invalidate(getCursorRect());
    				break;
    			case KeyEvent.KEYCODE_DPAD_LEFT:
    				invalidate(getCursorRect());
    				cursorLeftOrToRowEnd();
    				invalidate(getCursorRect());
    				break;
    			case KeyEvent.KEYCODE_DPAD_RIGHT:
    				invalidate(getCursorRect());
    				cursorRightOrToRowStart();
    				invalidate(getCursorRect());
    				break;
    			case KeyEvent.KEYCODE_ENTER:
    			case KeyEvent.KEYCODE_DPAD_CENTER:
    				tryToPlayIn(cursor_grid_matrix_x, cursor_grid_matrix_y);
    				break;
    			default:
    				return super.onKeyDown(keyCode, event);
    			}
    		}
    		else {
    			context.finish();
    		}
    		return true;
    	}
     
    	private void cursorLeftOrToRowEnd(){
    		cursor_grid_matrix_x -= 1;
    		if (cursor_grid_matrix_x < 0){
    			cursor_grid_matrix_x = CELLS_PER_DIM - 1;
    		}
    	}
     
    	private void cursorRightOrToRowStart(){
    		cursor_grid_matrix_x += 1;
    		if (cursor_grid_matrix_x >= CELLS_PER_DIM){
    			cursor_grid_matrix_x = 0;
    		}
    	}
     
    	private void cursorTopOrToColumnEnd(){
    		cursor_grid_matrix_y -= 1;
    		if (cursor_grid_matrix_y < 0){
    			cursor_grid_matrix_y = CELLS_PER_DIM - 1;
    		}
    	}
     
    	private void cursorDownOrToColumnStart(){
    		cursor_grid_matrix_y += 1;
    		if (cursor_grid_matrix_y >= CELLS_PER_DIM){
    			cursor_grid_matrix_y = 0;
    		}
    	}
     
    	public boolean onTouchEvent(MotionEvent event){
    		if (event.getAction() == MotionEvent.ACTION_DOWN){
    			if ( ! end_game ) {
    				float x = event.getX();
    				float y = event.getY();
    				float nearest_left_border_start = x - x
    						% (LINES_WEIGHT + cell_dim);
    				float nearest_left_border_end = nearest_left_border_start
    						+ LINES_WEIGHT - 1;
    				float nearest_top_border_start = y - y
    						% (LINES_WEIGHT + cell_dim);
    				float nearest_top_border_end = nearest_top_border_start
    						+ LINES_WEIGHT - 1;
    				// is pointed area in the board ?
    				if (x >= 0 && x < total_board_dim && y >= 0
    						&& y < total_board_dim) {
    					// is pointed area NOT in a border line ?
    					if (x > nearest_left_border_end
    							&& y > nearest_top_border_end) {
    						int matrixX = (int) (nearest_left_border_start / (LINES_WEIGHT + cell_dim));
    						int matrixY = (int) (nearest_top_border_start / (LINES_WEIGHT + cell_dim));
     
    						// set cursor to pointed cell
    						cursor_grid_matrix_x = matrixX;
    						cursor_grid_matrix_y = matrixY;
     
    						tryToPlayIn(matrixX, matrixY);
    					} else {
    						Toast.makeText(
    								context,
    								getResources().getString(
    										R.string.on_border_line_click),
    								Toast.LENGTH_SHORT).show();
    					}
    				} else {
    					Toast.makeText(
    							context,
    							getResources().getString(
    									R.string.out_of_board_click),
    							Toast.LENGTH_SHORT).show();
    				}
    			}
    			else {
    				context.finish();
    			}
    		}
    		return true;
    	}
     
    	private byte winner(){
    		byte the_winner;
     
    		the_winner = lineWinner();
    		if (the_winner != 0){
    			return the_winner;
    		}
     
    		the_winner = columnWinner();
    		if (the_winner != 0){
    			return the_winner;
    		}
     
    		return diagonals_winner();
    	}
     
    	private byte lineWinner(){
    		byte the_winner = 0; // set to none
    		byte winner_combos = 1;
    		for (int line = 0; line < CELLS_PER_DIM; line++){
    			if ( players_ids[0][line] == 0 ){
    				continue;
    			}
    			winner_combos = 1;
    			the_winner = players_ids[0][line];
    			for(int column = 1; column < CELLS_PER_DIM; column++){
    				if (players_ids[column][line] * the_winner <= 0){ // different player or none player ?
    					break;
    				}
    				winner_combos++;
    			}
    			if (winner_combos == CELLS_PER_DIM){
    				return the_winner;
    			}
    		}
    		return 0;
    	}
     
    	private byte columnWinner(){
    		byte the_winner = 0; // set to none
    		byte winner_combos = 1;
    		for (int column = 0; column < CELLS_PER_DIM; column++){
    			if ( players_ids[column][0] == 0 ){
    				continue;
    			}
    			winner_combos = 1;
    			the_winner = players_ids[column][0];
    			for(int line = 1; line < CELLS_PER_DIM; line++){
    				if (players_ids[column][line] * the_winner <= 0){ // different player or none player ?
    					break;
    				}
    				winner_combos++;
    			}
    			if (winner_combos == CELLS_PER_DIM){
    				return the_winner;
    			}
    		}
    		return 0;
    	}
     
    	private byte diagonals_winner(){
    		byte the_winner;
     
    		the_winner = players_ids[0][0];
    		if (the_winner != 0){
    			int winner_combos = 1;
    			for (int progression = 1; progression < CELLS_PER_DIM; progression++){
    				if (players_ids[progression][progression] * the_winner <= 0){
    					break;
    				}
    				winner_combos++;
    			}
    			if (winner_combos == CELLS_PER_DIM){
    				return the_winner;
    			}
    		}
     
    		the_winner = players_ids[CELLS_PER_DIM - 1][0];
    		if (the_winner != 0){
    			int winner_combos = 1;
    			for (int progression = 1; progression < CELLS_PER_DIM; progression++){
    				if (players_ids[CELLS_PER_DIM - 1 - progression][progression] * the_winner <= 0){
    					break;
    				}
    				winner_combos++;
    			}
    			if (winner_combos == CELLS_PER_DIM){
    				return the_winner;
    			}
    		}
     
    		return 0;
    	}
     
    	private boolean board_filled(){
    		for (int line_id = 0; line_id < CELLS_PER_DIM; line_id++){
    			for (int column_id = 0; column_id < CELLS_PER_DIM; column_id++){
    				if (players_ids[column_id][line_id] == 0){
    					return false;
    				}
    			}
    		}
    		return true;
    	}
    }

  7. #7
    Expert confirmé

    Avatar de Feanorin
    Profil pro
    Inscrit en
    Avril 2004
    Messages
    4 589
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Avril 2004
    Messages : 4 589
    Par défaut
    Si si j'insiste, avec la manière que j'ai codé l'appli (cet après-midi je pourrais poster quelques sources), le Canvas est redessiné lors de la rotation (peut être parce que j'ai mal géré le cycle de vie de l'Acitivity et ai mis le code de création du Canvas dans le mauvais onXXXX)
    Non c'est normal que le Canvas ce redessine a chaque rotation . Pour l'en empêcher il faut bloquer la rotattion de l'activity dans le manifest.

    En clair :
    ApplicationTicTacToe -> appel, appui sur return, mise à mort de l'application,... -> retour demandé par utilisateur ou système -> le dernier état est conservé.
    Maintenant ta question signifiait bien une sauvegarde automatique , maintenant si tu voulais garder en mémoire les données que lorsque l'utilisateur va sur le home puis revient (ce qui n'est pas une mise a mort de l'application mais un idle ). La tu peux soit passer par un service , ou alors sauvegarder tes données dans le savedInstanceState.

    Regarde tu coté de
    http://stackoverflow.com/questions/1...ications-state

  8. #8
    Membre émérite
    Avatar de tails
    Homme Profil pro
    Inscrit en
    Novembre 2003
    Messages
    799
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 45
    Localisation : France, Pyrénées Atlantiques (Aquitaine)

    Informations forums :
    Inscription : Novembre 2003
    Messages : 799
    Billets dans le blog
    15
    Par défaut Merci pour ces infos :)
    Citation Envoyé par Feanorin Voir le message
    Non c'est normal que le Canvas ce redessine a chaque rotation . Pour l'en empêcher il faut bloquer la rotattion de l'activity dans le manifest.
    En fait, je ne crois pas qu'au niveau expérience utilisateur, bloquer la rotation soit la meilleure des solutions : si dois je dois persévérer dans une voie, alors autant résoudre le problème des rotations en les permettant.

    Citation Envoyé par Feanorin Voir le message
    Maintenant ta question signifiait bien une sauvegarde automatique , maintenant si tu voulais garder en mémoire les données que lorsque l'utilisateur va sur le home puis revient (ce qui n'est pas une mise a mort de l'application mais un idle ). La tu peux soit passer par un service , ou alors sauvegarder tes données dans le savedInstanceState.

    Regarde tu coté de
    http://stackoverflow.com/questions/1...ications-state
    Ah oui, mais d'après la citation de MrDuChnok et le livre "Développer des Applications professionnelles pour Android 2", il faut ne programme le onSaveInstance et onRestoreInstance que pour prévenir les coupures dues au système. Donc j'opterais plutôt par la gestion dans le onPause, comme il me l'a recommandé.

    Mais de toutes façons, la page de StackOverflow que tu m'as passée en parle de ce onPause et onResume
    Merci beaucoup

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. Réponses: 3
    Dernier message: 13/08/2010, 07h10
  2. [RCP/JFace/Swt] Sauvegarder l'état d'une application RCP
    Par papaetoo dans le forum SWT/JFace
    Réponses: 1
    Dernier message: 23/09/2009, 16h33
  3. Réponses: 4
    Dernier message: 02/07/2009, 10h42
  4. Réponses: 3
    Dernier message: 16/01/2009, 14h30
  5. Rendre une macro Active lors de la réception de nouveau(x) mail(s)
    Par thomas.sculfort dans le forum VBA Outlook
    Réponses: 6
    Dernier message: 09/06/2007, 12h45

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo