Skip to content

Commit 30536d8

Browse files
committed
Moved game code from MainActivity to GameFragment
1 parent d52b7b3 commit 30536d8

File tree

10 files changed

+272
-231
lines changed

10 files changed

+272
-231
lines changed

app/src/main/java/ro/tav/pavgame/PavGameApplication.java

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@
2323
public class PavGameApplication extends Application {
2424
private static PavGameApplication pavGameApplication;
2525
private final List < Activity > activities;
26+
private static NotificationManager notificationManager = null;
2627

2728
public PavGameApplication() {
2829
super();
@@ -37,7 +38,7 @@ public void onCreate() {
3738
setupLibs();
3839

3940
if ( Build.VERSION.SDK_INT >= Build.VERSION_CODES.O ) {
40-
NotificationManager notificationManager = ( NotificationManager ) getSystemService( Context.NOTIFICATION_SERVICE );
41+
notificationManager = ( NotificationManager ) getSystemService( Context.NOTIFICATION_SERVICE );
4142
notificationManager.createNotificationChannel( PavGameNotificationChannelFactory.createProcessingWorkNotificationChannel() );
4243
}
4344
}
@@ -78,4 +79,7 @@ public static PavGameApplication getApplication() {
7879
return pavGameApplication;
7980
}
8081

82+
public static NotificationManager getNotificationManager() {
83+
return notificationManager;
84+
}
8185
}

app/src/main/java/ro/tav/pavgame/data/localDB/GameDataSource.java

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,5 +20,4 @@ public GameDataSource( GameDao gameDao ) {
2020
protected abstract List < GameEntity > getSpecificGamesbyUserNameStatic( String user );
2121

2222
protected abstract void insertGame( GameEntity game );
23-
2423
}

app/src/main/java/ro/tav/pavgame/presentation/PavGameReplacedBroadcastReceiver.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ public void onReceive( Context context, Intent intent ) {
1717
//ne initializam sistemul de notificari
1818
NotificationManager notificationManager = ( NotificationManager ) context.getSystemService( Context.NOTIFICATION_SERVICE );
1919
//afisam o notificare de bun venit
20-
notificationManager.notify( PavGameNotificationFactory.HELLO_NOTIFICATION_ID,
20+
notificationManager.notify( PavGameNotificationFactory.getHelloNotificationId(),
2121
PavGameNotificationFactory.createCustomHelloNotification( context,
2222
context.getString( R.string.broadcast_s1 ), context.getString( R.string.broadcast_s2 ) ) );
2323
}

app/src/main/java/ro/tav/pavgame/presentation/PavGameService.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ public int onStartCommand( Intent intent, int flags, int startId ) {
3131
int type = intent.getIntExtra( TYPE_KEY, TYPE_BASIC );
3232

3333
if ( type == TYPE_BASIC ) {
34-
startForeground( PavGameNotificationFactory.SERVICE_NOTIFICATION_ID, PavGameNotificationFactory.createProcessingWorkNotification( this ) );
34+
startForeground( PavGameNotificationFactory.getServiceNotificationId(), PavGameNotificationFactory.createProcessingWorkNotification( this ) );
3535

3636
Timber.i( "Basic work in progress" );
3737

app/src/main/java/ro/tav/pavgame/presentation/fragments/GameFragment.java

Lines changed: 241 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,28 +2,47 @@
22

33

44
import android.content.Context;
5+
import android.content.Intent;
56
import android.content.SharedPreferences;
67
import android.os.Bundle;
78
import android.os.SystemClock;
89
import android.view.LayoutInflater;
910
import android.view.View;
1011
import android.view.ViewGroup;
12+
import android.widget.Button;
1113
import android.widget.Chronometer;
14+
import android.widget.EditText;
15+
import android.widget.Toast;
1216

1317
import androidx.annotation.NonNull;
1418
import androidx.annotation.Nullable;
19+
import androidx.constraintlayout.widget.ConstraintLayout;
20+
import androidx.constraintlayout.widget.ConstraintSet;
1521
import androidx.fragment.app.Fragment;
1622

1723
import com.google.gson.Gson;
1824

25+
import ro.tav.pavgame.PavGameApplication;
1926
import ro.tav.pavgame.R;
27+
import ro.tav.pavgame.presentation.PavGameService;
28+
import ro.tav.pavgame.presentation.PavGameViewModel;
29+
import ro.tav.pavgame.presentation.notification.PavGameNotificationFactory;
2030
import ro.tav.pavgame.presentation.view.MainActivity;
2131
import timber.log.Timber;
2232

2333
public class GameFragment extends Fragment {
2434
private SharedPreferences sharedPreferences; ///folosim sharedPreferences pt a stoca pt fiecare utilizator timpul total de joc (de cand a instalat aplicatia)
2535
private final static String pavGameSharedPreference = "pavGameSharedPreference";
2636
private Chronometer chronometer;
37+
private int lat;
38+
private int nrDala;
39+
private static final int nrGreseliMax = 5;
40+
private int nrGreseli;
41+
private final int[][] matrix = new int[ 256 ][ 256 ];
42+
private EditText input;
43+
private Boolean started;
44+
private Boolean finished;
45+
private Intent gameInProgressServiceIntent;
2746

2847
public View onCreateView( @NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState ) {
2948
return inflater.inflate( R.layout.fragment_game, container, false );
@@ -36,6 +55,8 @@ public GameFragment() {
3655
@Override
3756
public void onActivityCreated( @Nullable Bundle savedInstanceState ) {
3857
super.onActivityCreated( savedInstanceState );
58+
59+
//obtin din sharedPreferances cat timp am avut in app pana acum, pt a seta cronometrul
3960
long timeSpent; //timpul petrecut(cu precizie de minute) in joc
4061
sharedPreferences = super.requireContext().getSharedPreferences( pavGameSharedPreference, Context.MODE_PRIVATE );
4162
try {
@@ -46,20 +67,240 @@ public void onActivityCreated( @Nullable Bundle savedInstanceState ) {
4667
timeSpent = 0;
4768
}
4869

70+
//setez cronometrul
4971
chronometer = requireView().findViewById( R.id.chronometer );
5072
chronometer.setBase( SystemClock.elapsedRealtime() - timeSpent * 60000 );//asa se initializeaza cronometrul
5173
chronometer.start();
74+
75+
//intent pt serviciul din foreground ce se creeaza cand e un joc in desfasurare
76+
gameInProgressServiceIntent = new Intent( requireContext(), PavGameService.class );
77+
78+
//adaugam listener pt butonul de joc, pt a putea incepe jocul
79+
Button button = ( Button ) requireView().findViewById( R.id.startGameButton );
80+
button.setOnClickListener( new Button.OnClickListener() {
81+
@Override
82+
public void onClick( View v ) {
83+
startGame( v );
84+
}
85+
} );
5286
}
5387

5488
@Override
5589
public void onDestroyView() {
5690
super.onDestroyView();
91+
//luam noul timpul total petrecut in aplicatie (cat era initial + cat s-a jucat utilizatorul acum)
5792
long newTime = SystemClock.elapsedRealtime() - chronometer.getBase();//milisecunde petrecut in total, dupa acest joc
5893
newTime /= 1000; //secunde
5994
newTime /= 60; //minute
6095

96+
//convertim acest numar (valoare rotunjita la minute) tinut pe Long la json
97+
//si ii fac update in shared preferances
6198
Gson gson = new Gson();
6299
String json = gson.toJson( newTime ); ///convertim acest timp la un json string
63100
sharedPreferences.edit().putString( MainActivity.getUserName() + "", json ).apply(); ///updatam valoarea in shared preferances
101+
102+
stopGameService();
64103
}
104+
105+
public void startGame( View view ) { //crearea si initializarea butoanelor jocului
106+
String s = "", messege;
107+
started = finished = Boolean.FALSE;
108+
input = requireView().findViewById( R.id.pavGameInputText );
109+
110+
try {
111+
//obtinem nr introdus si calculam latura
112+
s = input.getText().toString();
113+
lat = 1 << Integer.parseInt( s );
114+
input.setHint( R.string.pozDala );
115+
nrDala = nrGreseli = 0;
116+
ConstraintLayout pavGameBoard = requireView().findViewById( R.id.pavGameBoard );
117+
pavGameBoard.removeAllViews();
118+
119+
for ( int i = 0; i < lat; i++ ) {
120+
for ( int j = 0; j < lat; j++ ) {
121+
//adaugam cate un buton pt fiecare casuta
122+
matrix[ i ][ j ] = 0;
123+
Button button = new Button( getContext() );
124+
button.setLayoutParams( new ConstraintLayout.LayoutParams( ConstraintLayout.LayoutParams.MATCH_CONSTRAINT_SPREAD, ConstraintLayout.LayoutParams.WRAP_CONTENT ) );
125+
button.setId( lat * i + j );
126+
button.setOnClickListener( new handleClick() );//listener pt a putea selecta optiunea
127+
pavGameBoard.addView( button );
128+
129+
130+
//setam constraint-urile
131+
ConstraintSet constraintSet = new ConstraintSet();
132+
constraintSet.clone( pavGameBoard );
133+
134+
//legatura in sus
135+
if ( i == 0 ) { //top->topOfParrent
136+
constraintSet.connect( button.getId(), ConstraintSet.TOP, R.id.pavGameBoard, ConstraintSet.TOP );
137+
} else {//top->bottomOfButton
138+
constraintSet.connect( button.getId(), ConstraintSet.TOP, button.getId() - lat, ConstraintSet.BOTTOM );
139+
//bottomOfButton->top
140+
constraintSet.connect( button.getId() - lat, ConstraintSet.BOTTOM, button.getId(), ConstraintSet.TOP );
141+
}
142+
143+
//legatura la stanga
144+
if ( j == 0 ) {//left->leftOfParrent
145+
constraintSet.connect( button.getId(), ConstraintSet.START, R.id.pavGameBoard, ConstraintSet.START );
146+
} else {//left->rightOfButton
147+
constraintSet.connect( button.getId(), ConstraintSet.START, button.getId() - ( 1 ), ConstraintSet.END );
148+
//rightOfButton->left
149+
constraintSet.connect( button.getId() - ( 1 ), ConstraintSet.END, button.getId(), ConstraintSet.START );
150+
}
151+
//legatura la dreapta
152+
//right->endOfParrent
153+
constraintSet.connect( button.getId(), ConstraintSet.END, R.id.pavGameBoard, ConstraintSet.END );
154+
155+
//legatura in jos
156+
//bottom->bottomOfParrent
157+
constraintSet.connect( button.getId(), ConstraintSet.BOTTOM, R.id.pavGameBoard, ConstraintSet.BOTTOM );
158+
159+
//aplicam modificarile
160+
constraintSet.applyTo( pavGameBoard );
161+
}
162+
}
163+
//modificam mesajul de pe buton si il dezactivam
164+
messege = getString( R.string.copac );
165+
Button gameButton = ( Button ) view;
166+
gameButton.setEnabled( false );
167+
gameButton.setText( getString( R.string.start_game ) );
168+
requireActivity().startService( gameInProgressServiceIntent );
169+
170+
} catch ( Exception e ) {
171+
if ( s.length() == 0 ) //daca s-a introdus stringul vid
172+
messege = getString( R.string.errLipsaDimLatura );
173+
else
174+
messege = getString( R.string.unknownError );
175+
}
176+
Toast.makeText( getContext(), messege, Toast.LENGTH_LONG ).show();
177+
}
178+
179+
private class handleClick implements View.OnClickListener { //controller-ele in joc
180+
//un butonel din tabla mare
181+
private Button button;
182+
183+
//colorare buton
184+
private void setButon( int nr ) {
185+
button = requireView().findViewById( nr );
186+
button.setText( String.valueOf( nrDala ) );
187+
button.setBackgroundColor( getResources().getColor( R.color.colorPrimary, requireContext().getTheme() ) );
188+
button.setTextColor( getResources().getColor( R.color.colorAccent, requireContext().getTheme() ) );
189+
}
190+
191+
public void onClick( View view ) {
192+
String messege, s1 = "", s2, result;
193+
button = ( Button ) view;
194+
//luam pozitia dalei de inserare
195+
input = requireView().findViewById( R.id.pavGameInputText );
196+
int l = button.getId() / lat;
197+
int c = button.getId() % lat;
198+
if ( !started ) {//initializarea primul buton pt gaura
199+
started = true;
200+
button.setBackgroundColor( getResources().getColor( R.color.colorAccent, requireContext().getTheme() ) );
201+
button.setText( "0" );
202+
button.setTextColor( getResources().getColor( R.color.colorPrimary, requireContext().getTheme() ) );
203+
matrix[ l ][ c ] = -1;
204+
button = requireView().findViewById( R.id.startGameButton );
205+
button.setText( R.string.alegeDala );
206+
} else if ( nrGreseli > nrGreseliMax ) { //pierdere
207+
messege = getString( R.string.esec ) + " :(";
208+
Toast.makeText( getContext(), messege, Toast.LENGTH_LONG ).show();
209+
} else if ( nrDala * 3 + 1 == lat * lat ) { //castig
210+
messege = getString( R.string.victorie ) + " :)";
211+
Toast.makeText( getContext(), messege, Toast.LENGTH_LONG ).show();
212+
} else {//jocul continua
213+
try {
214+
s1 = input.getText().toString();
215+
int tipDala = Integer.parseInt( s1 ); //obtinem val de int din input
216+
messege = getString( R.string.mutareIncorecta );
217+
if ( tipDala < 1 || tipDala > 4 ) ///verificam sa fie un tip de pozitie correct
218+
throw new Exception( getString( R.string.dalaIncorecta ) );
219+
else if ( tipDala == 1 ) {//mutarile
220+
if ( matrix[ l ][ c ] == 0 && matrix[ l + 1 ][ c ] == 0 && matrix[ l ][ c + 1 ] == 0 && ( l + 1 ) < lat && ( c + 1 ) < lat ) {
221+
nrDala++;
222+
matrix[ l ][ c ] = matrix[ l + 1 ][ c ] = matrix[ l ][ c + 1 ] = nrDala;
223+
setButon( lat * l + c );
224+
setButon( lat * ( l + 1 ) + c );
225+
setButon( lat * l + ( c + 1 ) );
226+
} else {
227+
Toast.makeText( getContext(), messege, Toast.LENGTH_SHORT ).show();
228+
nrGreseli++;
229+
}
230+
} else if ( tipDala == 2 ) {
231+
if ( matrix[ l ][ c ] == 0 && matrix[ l + 1 ][ c ] == 0 && matrix[ l ][ c - 1 ] == 0 && ( l + 1 ) < lat ) {
232+
nrDala++;
233+
matrix[ l ][ c ] = matrix[ l + 1 ][ c ] = matrix[ l ][ c - 1 ] = nrDala;
234+
setButon( lat * l + c );
235+
setButon( lat * ( l + 1 ) + c );
236+
setButon( lat * l + ( c - 1 ) );
237+
} else {
238+
Toast.makeText( getContext(), messege, Toast.LENGTH_SHORT ).show();
239+
nrGreseli++;
240+
}
241+
} else if ( tipDala == 3 ) {
242+
if ( matrix[ l ][ c ] == 0 && matrix[ l - 1 ][ c ] == 0 && matrix[ l ][ c + 1 ] == 0 && ( c + 1 ) < lat ) {
243+
nrDala++;
244+
matrix[ l ][ c ] = matrix[ l - 1 ][ c ] = matrix[ l ][ c + 1 ] = nrDala;
245+
setButon( lat * l + c );
246+
setButon( lat * ( l - 1 ) + c );
247+
setButon( lat * l + ( c + 1 ) );
248+
} else {
249+
Toast.makeText( getContext(), messege, Toast.LENGTH_SHORT ).show();
250+
nrGreseli++;
251+
}
252+
} else {
253+
if ( matrix[ l ][ c ] == 0 && matrix[ l - 1 ][ c ] == 0 && matrix[ l ][ c - 1 ] == 0 ) {
254+
nrDala++;
255+
matrix[ l ][ c ] = matrix[ l - 1 ][ c ] = matrix[ l ][ c - 1 ] = nrDala;
256+
setButon( lat * l + c );
257+
setButon( lat * ( l - 1 ) + c );
258+
setButon( lat * l + ( c - 1 ) );
259+
} else {
260+
nrGreseli++;
261+
Toast.makeText( getContext(), messege, Toast.LENGTH_SHORT ).show();
262+
}
263+
}
264+
} catch ( Exception e ) {
265+
if ( s1.length() == 0 )
266+
messege = getString( R.string.errLipsaDimLatura );
267+
else
268+
messege = getString( R.string.dalaIncorecta );
269+
Toast.makeText( getContext(), messege, Toast.LENGTH_SHORT ).show();
270+
}
271+
}
272+
if ( finished == Boolean.FALSE && ( nrDala * 3 + 1 == lat * lat || nrGreseli > nrGreseliMax ) ) {
273+
finished = Boolean.TRUE;//daca se ajunge la finish
274+
requireView().findViewById( R.id.startGameButton ).setEnabled( true );
275+
button = requireView().findViewById( R.id.startGameButton );
276+
if ( nrDala * 3 + 1 == lat * lat ) {
277+
messege = getString( R.string.victorie ) + " :)";
278+
button.setText( messege );
279+
result = "Win";
280+
s1 = getString( R.string.Win );
281+
s2 = getString( R.string.victorie ) + ", " + MainActivity.getUserName() + "!";
282+
} else {
283+
messege = getString( R.string.esec ) + " :(";
284+
button.setText( messege );
285+
result = "Lose";
286+
s1 = getString( R.string.Lose );
287+
s2 = getString( R.string.esec ) + ", " + MainActivity.getUserName() + "!";
288+
}
289+
290+
//adaugam jocul folosindu-ne de viewModel
291+
PavGameViewModel.addResult( MainActivity.getUserName(), result, "Game Type: " + lat + "x" + lat );
292+
PavGameApplication.getNotificationManager().notify( PavGameNotificationFactory.getHelloNotificationId(),
293+
PavGameNotificationFactory.createCustomHelloNotification( getContext(),
294+
s1, s2 ) );
295+
Toast.makeText( getContext(), messege, Toast.LENGTH_LONG ).show();
296+
stopGameService(); //optimi si serviciul cand se castiga/pierde jocul
297+
}
298+
}
299+
300+
}
301+
302+
private void stopGameService() {
303+
requireActivity().stopService( gameInProgressServiceIntent );//oprirea serviciului
304+
}
305+
65306
}

app/src/main/java/ro/tav/pavgame/presentation/notification/PavGameNotificationFactory.java

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -14,8 +14,22 @@
1414

1515
public class PavGameNotificationFactory {
1616
private static final int BASE_ID = 1;
17-
public static final int SERVICE_NOTIFICATION_ID = BASE_ID + 1;
18-
public static final int HELLO_NOTIFICATION_ID = SERVICE_NOTIFICATION_ID + 1;
17+
private static final int SERVICE_NOTIFICATION_ID = BASE_ID + 1;
18+
private static final int HELLO_NOTIFICATION_ID = SERVICE_NOTIFICATION_ID + 1;
19+
20+
public static int getServiceNotificationId() {
21+
return SERVICE_NOTIFICATION_ID;
22+
}
23+
24+
public static int getHelloNotificationId() {
25+
return HELLO_NOTIFICATION_ID;
26+
}
27+
28+
public static int getNotificationLaunchCode() {
29+
return NOTIFICATION_LAUNCH_CODE;
30+
}
31+
32+
private static final int NOTIFICATION_LAUNCH_CODE = 485;
1933

2034
public static Notification createProcessingWorkNotification( Context context ) {
2135
NotificationCompat.Builder builder = new NotificationCompat.Builder( context, PavGameNotificationChannelFactory.CHANNEL_ID )
@@ -61,7 +75,7 @@ private static PendingIntent createContentIntent( Context context ) {
6175
Intent intent = new Intent( context, MainActivity.class );
6276

6377
return PendingIntent.getActivity( context,
64-
MainActivity.NOTIFICATION_LAUNCH_CODE,
78+
NOTIFICATION_LAUNCH_CODE,
6579
intent,
6680
PendingIntent.FLAG_UPDATE_CURRENT
6781
);
@@ -84,5 +98,4 @@ private static PendingIntent createStopActionPendingIntent( Context context ) {
8498
PendingIntent.FLAG_UPDATE_CURRENT
8599
);
86100
}
87-
88101
}

0 commit comments

Comments
 (0)