Assistance in diploma. Question programming the Arduino mega

Good afternoon. Guys help me with the code. Program:

#include <AFMotor.h> //Link library for working with shield

 // Plug motors to the terminal blocks M1, M2, M3, M4
 AF_DCMotor motor1(1);
 AF_DCMotor motor2(2);
 AF_DCMotor motor3(3);
 AF_DCMotor motor4(4);
 void setup(){
 // Set the maximum speed of the motor (similar work PWM)
 motor1.setSpeed(255);
 motor1.run(RELEASE);
 motor2.setSpeed(255);
 motor2.run(RELEASE);
 motor3.setSpeed(255);
 motor3.run(RELEASE);
 motor4.setSpeed(255);
 motor4.run(RELEASE);
 }

 void loop(){
 digitalRead(31); //reading from 31 Pin
 if (digitalRead(31) == HIGH) //condition if a high logic level
 {
//moving forward
 motor1.run(FORWARD); // Ask moving forward
 motor2.run(FORWARD);
 motor3.run(FORWARD);
 motor4.run(FORWARD);
 motor1.setSpeed(100); // Set the speed
 motor2.setSpeed(100);
 motor3.setSpeed(100);
 motor4.setSpeed(100);
 delay(5000);

 // Stop motors
 

 motor1.run(RELEASE);
 motor2.run(RELEASE);
 motor3.run(RELEASE);
 motor4.run(RELEASE);
 delay(1000);
//moving backward
 motor1.run(BACKWARD); // Ask moving backward
 motor2.run(BACKWARD);
 motor3.run(BACKWARD);
 motor4.run(BACKWARD);
 motor1.setSpeed(100); // Set the speed
 motor2.setSpeed(100);
 motor3.setSpeed(100);
 motor4.setSpeed(100);
 delay(4000);

 motor1.run(RELEASE);
 motor2.run(RELEASE);
 motor3.run(RELEASE);
 motor4.run(RELEASE);
 delay(1000);

 // move left
 motor1.run(FORWARD); // Ask moving forward 2 motors
 motor4.run(FORWARD);
 motor1.setSpeed(100); // Set the speed
 motor4.setSpeed(100);
 delay(1000);

 // Stop all motors
 /* Very not recommend sharply to switch the direction of rotation of the motor.
It is better to give a short period of time.*/

 motor1.run(RELEASE);
 motor2.run(RELEASE);
 motor3.run(RELEASE);
 motor4.run(RELEASE);
 delay(5000);
 }
 else
 {
// move left
 motor1.run(FORWARD); // Ask moving forward 2 motors
 motor4.run(FORWARD);
 motor1.setSpeed(100); // Set the speed
 motor4.setSpeed(100);
 delay(1000);

 // Stop all motors
 /* Very not recommend sharply to switch the direction of rotation of the motor.
It is better to give a short period of time.*/

 motor1.run(RELEASE);
 motor2.run(RELEASE);
 motor3.run(RELEASE);
 motor4.run(RELEASE);
 delay(5000);
 }
 }[code]

how can I make it in to Arduino saw that if the pin three times will be a logic high level then the program will end because when I have the logic level low she turn left. And I need to make when it will be 3 times as high logic level motors stopped and not turned left to infinity. [/code]