Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.example.eurynomus.trafficlightmine;
- import android.graphics.Color;
- import android.support.v7.app.AppCompatActivity;
- import android.os.Bundle;
- import android.view.View;
- import android.widget.Button;
- import android.widget.TextView;
- import com.example.eurynomus.trafficlightmine.R;
- public class MainActivity extends AppCompatActivity
- {
- // Define constant Logic
- //----------------------------------------------------------------------------------------------
- // С goToRed и goToGreen оказват посоката на движение на светлината на светофара.
- private final int goToRed = 0;
- private final int goToGreen = 2;
- // Използваме redLight, yellowLight, greenLight, за да поясним в кода(най-вече в switch-овете)
- // в какво състояние е светофара и какво се случваа, докато е в това състояние.
- private final int redLight = 0;
- private final int yellowLight = 1;
- private final int greenLight = 2;
- // Layout Resources
- //----------------------------------------------------------------------------------------------
- // Създаваме променливи, с които ще манипулираме ресурсите във View-то.
- private TextView redLightTextView;
- private TextView yellowLightTextView;
- private TextView greenLightTextView;
- private Button startBtn;
- private Button resetBtn;
- private Button stopBtn;
- // logic Variables
- //----------------------------------------------------------------------------------------------
- // Използваме isWorking САМО когато пускаме нишката в началото със Start бутона, понеже след
- // натискане на STOP нишката не спира, а по-скоро е в режим Pause и при повторно натискане на
- // START ние не трябва да пускаме нова нишка, а просто да продължим настоящата(Resume work)
- private boolean isWorking;
- // Използва се в случай, че RESET бутона е натиснат. Когато isReset стане true ще се изпълни
- // логиката, която сме написали и след това ще се върне в състояние false
- private boolean isReset;
- // Използва се, когато натискаме STOP бутона. Служи като тригер, чрез който светофара се спира
- // (PAUSE) и започва да се изпълнява новата логика. При натискането на START или RESET бутона,
- // светофара продължава работата си (RESUME WORK) както следва по логиката на натиснатият бутон.
- private boolean isStopped;
- // В nCurrentLight се пази настоящата светлина,
- // работеща на светофара(redLight, yellowLifht, greenLight)
- private int nCurrentLight;
- // В nLightPath се пази пътя на светлината на светофата (дали е goToRed или goToGreen)
- private int nLightPath;
- // Overrides
- //----------------------------------------------------------------------------------------------
- @Override
- protected void onCreate(Bundle savedInstanceState)
- {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- setLayoutResources();
- initializeLogicVariables();
- // В началото светофарът е спрян, затова всичките му светлини трябва да са Сиви/Черни/etc.
- setTrafficLightsColor(Color.GRAY, Color.GRAY, Color.GRAY);
- startBtn.setOnClickListener(new View.OnClickListener()
- {
- @Override
- public void onClick(View v)
- {
- // Понеже в началото светофарът е изключен, ще влезем в този IF statement.
- // Вътре ще го включим и повече няма да влезем в този IF statement.
- if(!isWorking)
- {
- // Задаваме стойност true, което означава, че светофарът работи.
- isWorking = true;
- // Извикваме метода, който включва светофара.
- startTrafficLight();
- }
- // След като натиснем един бутон, другите се връщат в началното си състояние(RESET),
- // а натиснатият бутон се изключва, за да не бъде натиснат повторно.
- isReset = false;
- isStopped = false;
- startBtn.setEnabled(false);
- resetBtn.setEnabled(true);
- stopBtn.setEnabled(true);
- }
- });
- resetBtn.setOnClickListener(new View.OnClickListener()
- {
- @Override
- public void onClick(View v)
- {
- // След като натиснем един бутон, другите се връщат в началното си състояние(RESET),
- // а натиснатият бутон се изключва, за да не бъде натиснат повторно.
- isStopped = false;
- isReset = true;
- startBtn.setEnabled(true);
- resetBtn.setEnabled(false);
- stopBtn.setEnabled(true);
- }
- });
- stopBtn.setOnClickListener(new View.OnClickListener()
- {
- @Override
- public void onClick(View v)
- {
- // След като натиснем един бутон, другите се връщат в началното си състояние(RESET),
- // а натиснатият бутон се изключва, за да не бъде натиснат повторно.
- isStopped = true;
- isReset = false;
- stopBtn.setEnabled(false);
- startBtn.setEnabled(true);
- resetBtn.setEnabled(true);
- // Когато светофарът спре, тогава свети само Жълто(по-условие).
- nCurrentLight = yellowLight;
- }
- });
- }
- // Methods
- //----------------------------------------------------------------------------------------------
- // Този метод създава НИШКА, която включва светофара и я стартира.
- //
- private void startTrafficLight()
- {
- // Създаваме нишката
- Thread trafficLightThread = new Thread(new Runnable()
- {
- // В RUN описваме логиката, която нишката ще изпълнява.
- @Override
- public void run()
- {
- // Докато светофарът работи, нишката няма да спре работа.
- // (В случеят имаме безкраен цикъл и нишката няма да завърши).
- while(isWorking)
- {
- trafficLightSwitch();
- }
- }
- });
- // Стартираме нишката
- trafficLightThread.start();
- }
- // Този Метод проверява коя светлина на светофара работи на момента и изпълнява логиката
- // свързана с нея(смяна на цветовете на светофара, задържане в същото състояние за определен
- // интервал от време, смяна на светлината, смяна на посоката на светлината, etc.).
- private void trafficLightSwitch()
- {
- switch (nCurrentLight)
- {
- case redLight:
- nLightPath = greenLight;
- trafficLightColorSwitch();
- nCurrentLight = yellowLight;
- sameLightLooper(5);
- break;
- case yellowLight:
- trafficLightColorSwitch();
- if(nLightPath == goToGreen)
- nCurrentLight = greenLight;
- else if(nLightPath == goToRed)
- nCurrentLight = redLight;
- sameLightLooper(3);
- break;
- case greenLight:
- nLightPath = redLight;
- trafficLightColorSwitch();
- nCurrentLight = yellowLight;
- sameLightLooper(5);
- break;
- }
- }
- // Този метод променя цветовете на светофара в зависимост от състоянието на работещата
- // в момента светлина.
- private void trafficLightColorSwitch()
- {
- switch (nCurrentLight)
- {
- case redLight:
- setTrafficLightsColor(Color.RED, Color.GRAY, Color.GRAY);
- break;
- case yellowLight:
- setTrafficLightsColor(Color.GRAY, Color.YELLOW, Color.GRAY);
- break;
- case greenLight:
- setTrafficLightsColor(Color.GRAY, Color.GRAY, Color.GREEN);
- break;
- }
- }
- // Този метод отговаря за циклите и времето, което светофарът ще стои в дадена позиция.
- private void sameLightLooper(int maxLoopTime)
- {
- // nLoopTimePassed оказва колко време е минало от началото на светлината.
- int nLoopTimePassed = 0;
- // nMaxLoopTime оказва колко време светлината трябва да стои в дадено състояние.
- int nMaxLoopTime = maxLoopTime * 100;
- // Това не знам защо го имам ама май ми трябваше, за да не се чупи много =D
- boolean toReturn = false;
- // Blink се използва за минагето на жълтият светофар, докато е в режим STOP
- int blink = 0;
- // Цикълът, който се изпълнява докато сме в режим STOP(т.е. натиснали сме STOP бутона).
- while(isStopped && !isReset)
- {
- if(!toReturn)
- toReturn = !toReturn;
- nLoopTimePassed++;
- if (nLoopTimePassed % 50 == 0)
- {
- nLoopTimePassed = 0;
- if (blink == 0)
- {
- blink = 1;
- setTrafficLightsColor(Color.GRAY, Color.GRAY, Color.GRAY);
- } else if (blink == 1)
- {
- blink = 0;
- setTrafficLightsColor(Color.GRAY, Color.YELLOW, Color.GRAY);
- }
- }
- try
- {
- Thread.sleep(10);
- } catch (InterruptedException e)
- {
- e.printStackTrace();
- }
- }
- // Цикълът, който се изпълнява когато влезем в режим RESET(т.е. натиснали сме RESET бутона).
- if(isReset)
- {
- isReset = false;
- nCurrentLight = yellowLight;
- nLightPath = greenLight;
- runOnUiThread(new Runnable()
- {
- @Override
- public void run() {
- resetBtn.setEnabled(false);
- }
- });
- return;
- }
- if(toReturn)
- return;
- // Цикълът, който се изпълнява когато влезем в режим START или след RESET или когато
- // пуснем светофара за пръв път(т.е. натиснали сме START бутона или т.н.)
- // P.S. - Това е обикновената(нормалната) работа да светофара.
- while((nLoopTimePassed < nMaxLoopTime) && !isStopped && !isReset)
- {
- if(!toReturn)
- toReturn = !toReturn;
- nLoopTimePassed++;
- try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); }
- }
- }
- // Метод, който присвоява на ресурсните променливи ресурсите КОИТО взимаме от View-то
- // и с които ще работим в последствие
- private void setLayoutResources()
- {
- redLightTextView = (TextView) findViewById(R.id.redLightTextView);
- yellowLightTextView = (TextView) findViewById(R.id.yellowLightTextView);
- greenLightTextView = (TextView) findViewById(R.id.greenLightTextView);
- startBtn = (Button) findViewById(R.id.startBtn);
- resetBtn = (Button) findViewById(R.id.resetBtn);
- stopBtn = (Button) findViewById(R.id.stopBtn);
- }
- // Метод за Инициализиране на променливите с начални стойности
- private void initializeLogicVariables()
- {
- isWorking = false;
- isReset = false;
- isStopped = false;
- nCurrentLight = redLight;
- nLightPath = goToGreen;
- }
- // С този Метод Задаваме цветовете на Трите слетлини на светофара.
- // Използваме го при смяната на светлините.
- private void setTrafficLightsColor(int nRedLightColor, int nYellowLightColor, int nGreenLightColor)
- {
- redLightTextView.setBackgroundColor(nRedLightColor);
- yellowLightTextView.setBackgroundColor(nYellowLightColor);
- greenLightTextView.setBackgroundColor(nGreenLightColor);
- }
- }
- <?xml version="1.0" encoding="utf-8"?>
- <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:app="http://schemas.android.com/apk/res-auto"
- xmlns:tools="http://schemas.android.com/tools"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- tools:context=".MainActivity">
- <TextView
- android:id="@+id/redLightTextView"
- android:layout_width="100dp"
- android:layout_height="100dp"
- android:layout_marginStart="8dp"
- android:layout_marginLeft="8dp"
- android:layout_marginTop="8dp"
- android:layout_marginEnd="8dp"
- android:layout_marginRight="8dp"
- android:layout_marginBottom="8dp"
- android:background="#333333"
- android:textSize="26sp"
- app:layout_constraintBottom_toBottomOf="parent"
- app:layout_constraintEnd_toEndOf="parent"
- app:layout_constraintStart_toStartOf="parent"
- app:layout_constraintTop_toTopOf="parent"
- app:layout_constraintVertical_bias="0.16000003" />
- <TextView
- android:id="@+id/yellowLightTextView"
- android:layout_width="100dp"
- android:layout_height="100dp"
- android:layout_marginStart="8dp"
- android:layout_marginLeft="8dp"
- android:layout_marginTop="8dp"
- android:layout_marginEnd="8dp"
- android:layout_marginRight="8dp"
- android:layout_marginBottom="8dp"
- android:background="#333333"
- app:layout_constraintBottom_toBottomOf="parent"
- app:layout_constraintEnd_toEndOf="parent"
- app:layout_constraintStart_toStartOf="parent"
- app:layout_constraintTop_toBottomOf="@+id/redLightTextView"
- app:layout_constraintVertical_bias="0.0" />
- <TextView
- android:id="@+id/greenLightTextView"
- android:layout_width="100dp"
- android:layout_height="100dp"
- android:layout_marginStart="8dp"
- android:layout_marginLeft="8dp"
- android:layout_marginTop="8dp"
- android:layout_marginEnd="8dp"
- android:layout_marginRight="8dp"
- android:layout_marginBottom="8dp"
- android:background="#333333"
- app:layout_constraintBottom_toBottomOf="parent"
- app:layout_constraintEnd_toEndOf="parent"
- app:layout_constraintStart_toStartOf="parent"
- app:layout_constraintTop_toBottomOf="@+id/yellowLightTextView"
- app:layout_constraintVertical_bias="0.0" />
- <Button
- android:id="@+id/startBtn"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_marginStart="8dp"
- android:layout_marginLeft="8dp"
- android:layout_marginTop="8dp"
- android:layout_marginEnd="8dp"
- android:layout_marginRight="8dp"
- android:layout_marginBottom="8dp"
- android:text="Start"
- app:layout_constraintBottom_toBottomOf="parent"
- app:layout_constraintEnd_toEndOf="parent"
- app:layout_constraintHorizontal_bias="0.07"
- app:layout_constraintStart_toStartOf="parent"
- app:layout_constraintTop_toBottomOf="@+id/greenLightTextView"
- app:layout_constraintVertical_bias="0.31" />
- <Button
- android:id="@+id/resetBtn"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_marginStart="8dp"
- android:layout_marginLeft="8dp"
- android:layout_marginTop="8dp"
- android:layout_marginEnd="8dp"
- android:layout_marginRight="8dp"
- android:layout_marginBottom="8dp"
- android:text="Reset"
- app:layout_constraintBottom_toBottomOf="parent"
- app:layout_constraintEnd_toEndOf="parent"
- app:layout_constraintHorizontal_bias="0.16"
- app:layout_constraintStart_toEndOf="@+id/startBtn"
- app:layout_constraintTop_toBottomOf="@+id/greenLightTextView"
- app:layout_constraintVertical_bias="0.311" />
- <Button
- android:id="@+id/stopBtn"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_marginStart="8dp"
- android:layout_marginLeft="8dp"
- android:layout_marginTop="8dp"
- android:layout_marginEnd="8dp"
- android:layout_marginRight="8dp"
- android:layout_marginBottom="8dp"
- android:text="Stop"
- app:layout_constraintBottom_toBottomOf="parent"
- app:layout_constraintEnd_toEndOf="parent"
- app:layout_constraintHorizontal_bias="0.46"
- app:layout_constraintStart_toEndOf="@+id/resetBtn"
- app:layout_constraintTop_toBottomOf="@+id/greenLightTextView"
- app:layout_constraintVertical_bias="0.311" />
- </android.support.constraint.ConstraintLayout>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement