Sei sulla pagina 1di 40

CONTENTS

Part-1: C++
 Introduction
 OpenCV C++ program for face detection
 Student data management in C++
 Finding cabs nearby using Great Circle distance formula

Part-2: Java
 Introduction
 A Group chat application in java
 Generating password and OTP in java
 Creative Programming In Processing | Set 1 (Random
Walker)
1. Introduction
C++ is an object-oriented programming language. It was developed by Bjarne Stroustrup
at AT&T Bell laboratories in Murray Hill, New Jersey, USA, in the early 1980's. Stroustrup,
an admirer of Simula67 and a strong supporter of C, wanted to combine the best of both
the languages and create a more powerful language that could support object-oriented
programming features and still retain the power and elegance of C. The result was C++.
Therefore, C++ is an extension of C with a major addition of the class contruct feature of
Simula67.

C++ is a superset of C. Most of what we already know about C applies to C++ also.
Therefore, almost all C programs are also C++ programs. However, there are a few minor
differences that will prevent a C program to run under C++ compiler. We shall see these
differences later as and when they are encountered.

the object-oriented features in C++ allow programming to build large programs with
clarity, extensibility and ease of maintenance, incorporating the spirit and efficiency of C.
The eddition of new features has been transformed C from a language that currently
facilites top-down, structured design, to one that provides bottom-up, object-oriented
design.

2.OpenCV C++ Program for Face Detection

This program uses the OpenCV library to detect faces in a live stream from webcam or in
a video file stored in the local machine. This program detects faces in real time and tracks
it. It uses pre-trained XML classifiers for the same. The classifiers used in this program
have facial features trained in them. Different classifiers can be used to detect different
objects.

Requirements for running the program:


1) OpenCV must be installed on the local machine.
2) Paths to the classifier XML files must be given before the execution of the program.
These XML files can be found in the OpenCV directory “opencv/data/haarcascades”.
3) Use 0 in capture.open(0) to play webcam feed.
4) For detection in a local video provide the path to the video.

Implementation:
// CPP program to detects face in a video

// Include required header files from OpenCV directory

#include "/usr/local/include/opencv2/objdetect.hpp"

#include "/usr/local/include/opencv2/highgui.hpp"

#include "/usr/local/include/opencv2/imgproc.hpp"

#include <iostream>

using namespace std;

using namespace cv;

// Function for Face Detection

void detectAndDraw( Mat& img, CascadeClassifier& cascade,

CascadeClassifier& nestedCascade, double scale );

string cascadeName, nestedCascadeName;

int main( int argc, const char** argv )

// VideoCapture class for playing video for which faces to be detected

VideoCapture capture;

Mat frame, image;

// PreDefined trained XML classifiers with facial features

CascadeClassifier cascade, nestedCascade;

double scale=1;

// Load classifiers from "opencv/data/haarcascades" directory

nestedCascade.load( "../../haarcascade_eye_tree_eyeglasses.xml" ) ;

// Change path before execution

cascade.load( "../../haarcascade_frontalcatface.xml" ) ;

// Start Video..1) 0 for WebCam 2) "Path to Video" for a Local Video


capture.open(0);

if( capture.isOpened() )

// Capture frames from video and detect faces

cout << "Face Detection Started...." << endl;

while(1)

capture >> frame;

if( frame.empty() )

break;

Mat frame1 = frame.clone();

detectAndDraw( frame1, cascade, nestedCascade, scale );

char c = (char)waitKey(10);

// Press q to exit from window

if( c == 27 || c == 'q' || c == 'Q' )

break;

else

cout<<"Could not Open Camera";

return 0;

void detectAndDraw( Mat& img, CascadeClassifier& cascade,

CascadeClassifier& nestedCascade,

double scale)

{
vector<Rect> faces, faces2;

Mat gray, smallImg;

cvtColor( img, gray, COLOR_BGR2GRAY ); // Convert to Gray Scale

double fx = 1 / scale;

// Resize the Grayscale Image

resize( gray, smallImg, Size(), fx, fx, INTER_LINEAR );

equalizeHist( smallImg, smallImg );

// Detect faces of different sizes using cascade classifier

cascade.detectMultiScale( smallImg, faces, 1.1,

2, 0|CASCADE_SCALE_IMAGE, Size(30, 30) );

// Draw circles around the faces

for ( size_t i = 0; i < faces.size(); i++ )

Rect r = faces[i];

Mat smallImgROI;

vector<Rect> nestedObjects;

Point center;

Scalar color = Scalar(255, 0, 0); // Color for Drawing tool

int radius;

double aspect_ratio = (double)r.width/r.height;

if( 0.75 < aspect_ratio && aspect_ratio < 1.3 )

center.x = cvRound((r.x + r.width*0.5)*scale);


center.y = cvRound((r.y + r.height*0.5)*scale);

radius = cvRound((r.width + r.height)*0.25*scale);

circle( img, center, radius, color, 3, 8, 0 );

else

rectangle( img, cvPoint(cvRound(r.x*scale), cvRound(r.y*scale)),

cvPoint(cvRound((r.x + r.width-1)*scale),

cvRound((r.y + r.height-1)*scale)), color, 3, 8, 0);

if( nestedCascade.empty() )

continue;

smallImgROI = smallImg( r );

// Detection of eyes int the input image

nestedCascade.detectMultiScale( smallImgROI, nestedObjects, 1.1, 2,

0|CASCADE_SCALE_IMAGE, Size(30, 30) );

// Draw circles around eyes

for ( size_t j = 0; j < nestedObjects.size(); j++ )

Rect nr = nestedObjects[j];

center.x = cvRound((r.x + nr.x + nr.width*0.5)*scale);

center.y = cvRound((r.y + nr.y + nr.height*0.5)*scale);

radius = cvRound((nr.width + nr.height)*0.25*scale);

circle( img, center, radius, color, 3, 8, 0 );

// Show Processed Image with detected faces


imshow( "Face Detection", img );

References:
1) http://docs.opencv.org/2.4/modules/contrib/doc/facerec/facerec_tutorial.html
2)http://docs.opencv.org/2.4/doc/tutorials/objdetect/cascade_classifier/cascade_classifier.html

3.Student Data Management in C++


Databases are being used in every aspect of our lives right now. Trillions of bytes of data are being
stored in servers around the world. SQL is one of the most basic methods to use such a database.
But have you ever thought about using C++ to maintain such a database. In this post, we will talk
about implementing different views on a text file according to the type of user and edit accordingly.
The data stored using this code are:
1) Registration number
2) Name
3) Marks in CSE1001
4) Marks in CSE1002
5) Proctor ID
Following code is a simple implementation of Student Management Project written in C++

//Include all the necessary libraries.

#include<stdio.h>

#include<iostream>

#include<fstream>

#include<string.h>

using namespace std;

int main(){

//Considering the max length of data entered (name) to be 15.

char data[15];
int n = 0, option = 0, count_n = 0;

//This is the initial mark alloted to a subject.

string empty = "00";

string proctor = "";

//Name of the file in which DB is stored.

ifstream f("Example.txt");

string line;

//The following for loop counts the total number of lines in the file.

for (int i = 0; std::getline(f, line); ++i){

count_n++;}

while(option != 6){

//This prints out all the available options in the DB

cout << "\nAvailable operations: \n1. Add New Students\n2."

<< "Student Login\n3. Faculty Login\n4. Proctor Login\n5. Admin View\n"

<< "6. Exit\nEnter option: ";

cin >> option;

if(option == 1){

cout << "Enter the number of students: ";

cin >> n;

count_n = count_n + n;
for (int i = 0;i < n;i++){

ofstream outfile;

outfile.open("Example.txt",ios::app);

//The entire data of a single student is stored line-by-line.

cout << "Enter your registration number: ";

cin >> data;

outfile << data << "\t";

cout << "Enter your name: ";

cin >> data;

int len = strlen(data);

while (len < 15){

data[len] = ' ';

len = len + 1;

outfile << data << "\t";

//Inserting empty data initially into the file

outfile << empty << "\t";

outfile << empty << "\t";

cout << "Enter your proctor ID: ";

cin >> proctor;


outfile << proctor << endl;

}}

else if (option == 2){

char regno[9];

cout << "Enter your registration number: ";

cin >> regno;

ifstream infile;

int check = 0;

infile.open("Example.txt",ios::in);

//This loop prints out the data according to the registration number specified.

while (infile >> data){

if (strcmp(data,regno) == 0){

cout << "\nRegistration Number: " << data << endl;

infile >> data;

cout << "Name: " << data << endl;

infile >> data;

cout << "CSE1001 mark: " << data << endl;

infile>>data;

cout<<"CSE1002 mark: "<<data<<endl;


infile>>data;

cout<<"Proctor ID: "<<data<<endl;

infile.close();

check = 1;}

if (check == 0){

cout<<"No such registration number found!"<<endl;}

//This loop is used to view and add marks to the database of a student.

else if (option == 3){

char subcode[7];

cout << "Enter your subject code: ";

cin >> subcode;

string code1 = "CSE1001", code2 = "CSE1002",mark = "";

ifstream infile;

int check = 0;

cout << "\nAvailable operations: \n1. Add data about marks\n"

<< "2. View data\nEnter option: ";

cin >> option;


if (option == 1){

cout << "Warning! You would need to add mark"

<< "details for all the students!" << endl;

for(int i = 0;i < count_n;i++){

fstream file("Example.txt");

//The seek in file has been done according to the


length

//of the data being inserted. It needs to adjusted accordingly

//for diffferent lengths of data.

if(strcmp(subcode,code1.c_str()) == 0){

file.seekp(26+37*i,std::ios_base::beg);

cout << "Enter the mark of student#" << (i+1) << " : ";

cin >> mark;

file.write(mark.c_str(),2);}

if(strcmp(subcode,code2.c_str()) == 0){

file.seekp(29+37*i,std::ios_base::beg);

cout << "Enter the mark of student#" << (i+1) << " : ";

cin >> mark;

file.write(mark.c_str(),2);}

}
//This loop is used to view marks of a student.

//The extra infile commands have been used to get a specific mark

//only since the data has been seperated by a tabspace.

else if(option == 2){

infile.open("Example.txt",ios::in);

if (strcmp(subcode,code1.c_str()) == 0){

cout << "Registration number - Marks\n" << endl;

while(infile >> data){

cout << data;

infile >> data;

infile >> data;

cout << " - " << data << endl;

infile >> data;

infile >> data;

check = 1;

infile.close();

infile.open("Example.txt",ios::in);

if(strcmp(subcode,code2.c_str()) == 0){

cout << "Registration number - Marks\n" << endl;


while(infile >> data){

cout << data;

infile >> data;

infile >> data;

infile >> data;

cout << " - " << data << endl;

infile >> data;

check = 1;

}}

infile.close();

if (check == 0){

cout << "No such subject code found!" << endl;

//This loop displays all the details of students under the same proctor ID.

else if (option == 4){

char procid[7];

cout << "Enter your proctor ID: ";

cin >> procid;

int check = 1;
char temp1[100], temp2[100], temp3[100];

char temp4[100], id[100];

ifstream infile;

infile.open("Example.txt",ios::in);

while (infile >> temp1){

infile >> temp2;

infile >> temp3;

infile >> temp4;

infile >> id;

if (strcmp(id,procid) == 0){

cout << "\nRegistration Number: " << temp1 << endl;

cout << "Name: " << temp2 << endl;

cout << "CSE1001 Mark: " << temp3 << endl;

cout << "CSE1002 Mark: " << temp4 << endl;

check = 1;

if (check == 0){

cout << "No such proctor ID found!" << endl;

}}

//This loop acts as an admin view to see all the data in the file.
else if(option == 5)

char password[25];

cout << "Enter the admin password: ";

cin >> password;

//This variable value can be changed according to your requirement

//of the administrator password.

string admin_pass = "admin";

if (strcmp(password,admin_pass.c_str()) == 0){

cout << "Reg No. \tName\tCSE1001\tCSE1002\tProctor ID" << endl;

ifstream infile;

infile.open("Example.txt",ios::in);

char data[20];

while(infile >> data){

cout << data << "\t";

infile >> data;

cout << data << "\t";

infile >> data;

cout << data << "\t";

infile >> data;


cout << data << "\t";

infile >> data;

cout << data << endl;

}}

Reference: https://www.geeksforgeeks.org/student-data-management-c/

4.Finding cabs nearby using Great Circle Distance


formula
Given GPS co-ordinates(in degrees) of a person who needs a cab and co-ordinates of all the cabs in
the city stored in a text file in JSON format, find the user-id and name of all the cab drivers available
in 50 km proximity.

Examples:

Input : file customers.json which contains GPS co-ordinates of a person who needs a cab in degrees
and co-ordinates of all the cabs in the city stored in a text file in JSON format.

Output : file answers.json which contains user-id and Name of all the cab drivers available in 50 km
proximity stored in a new file.

Approach Used:

1. Obtain latitude and longitude of each cab in string format along with their user-id and name from
the JSON encoded input file.

2. Convert latitude and longitude of the cab present in string format to double.

3. Convert latitude and longitude of both, the user and the cab present in degrees to radians.

4. Calculate distance between the user’s location and the cab using Great Circle Distance formula.

5. If distance is found to be less than or equal to 50 kms then output the user-id and name of the cab
driver to a new file else take no action.
Procedure to run the program :
1. Save the code and the file customers.json in a same location.

2. Now, compile the code(using cmd : g++ file_name.cpp) and run it(using cmd : ./a.out
/home/gfg/customers.json) with passing file name customers.json along with proper location(e.g.
/home/gfg/customers.json).

3. A file named answers.json will be created on the same location where code and customers.json
file is existing.

// C++ code to find cabs nearby

#include <bits/stdc++.h>

using namespace std;

// Latitude of customer who needs a cab.

#define lat1d 12.9611159

// Longitude of customer who needs a cab.

#define lon1d 77.6362214

#define pi 3.14159265358979323846

#define earth_radius 6371.0

ifstream customer_list ("customers.json");

ofstream out ("answer.json");

// Function to convert degree to radian.

double degtorad(double deg)

{
return ( deg * pi / 180);

// Function to calculate distance

// between 2 given locations

// using Great Circle Distance Formula.

double distanceEarth(double lat2d, double lon2d)

double lat1, lon1, lat2, lon2,

delta_lon, central_ang;

lat1 = degtorad(lat1d);

lon1 = degtorad(lon1d);

lat2 = degtorad(lat2d);

lon2 = degtorad(lon2d);

delta_lon = lon2 - lon1;

// great circle distance formula.

central_ang = acos ( sin(lat1) *

sin(lat2) + cos(lat1) *

cos(lat2) * cos(delta_lon) );

return (earth_radius * central_ang);

}
// Structure which contains data and

// functions for accessing and processing

// data from the given customers.json file.

struct json

/* i and j are used to access various

elements of the char arrays. x is used

to measure the size of the element of

latitude_as_string array. y is used to

measure the size of the element of

longitude_as_string array. m is used

to measure the size of the element

of id_as_string array. n is used to

measure the size of the element of

name array. f keeps count of " " "

symbol. fi keeps count of " : " symbol.

*/

long long int length, i, j, x, y, m,

n, f, fi, id[100000];

char latitude_as_string[1000],

longitude_as_string[1000],

id_as_string[1000], name[1000];
double lat2d, lon2d;

// To get each line of customers.json

// file as string.

string line;

// Function to check whether distance between

// 2 points is less than 50km or not.

void distance_calculator()

if (distanceEarth(lat2d, lon2d) <= 50.0000)

// Converting id to int format.

id[i] = atoll(id_as_string);

i++;

out << "{\"user_id\": " << id[i - 1] <<

", \"name\": " << name << "}" << endl;

// Function to read various attributes

// like latitude, longitude, name , id,

// etc, from customers.json file. simplistic

// approach is used to get JSON attributes.

void json_parser()
{

if (customer_list.is_open())

while (getline(customer_list, line))

f = 0; x = 0; y = 0; fi = 0; m = 0, n = 0;

length = line.size();

for (j = 0; j < length; j++)

if (line[j] == '"')

f++;

else if (line[j] == ':')

fi++;

// To get latitude of the location.

if (f == 3)

j++;

while (line[j] != '"')


{

latitude_as_string[x] = line[j];

x++; j++;

j--; latitude_as_string[x] = '\0';

// To get longitude of the location.

else if (f == 13)

j++;

while (line[j] != '"')

longitude_as_string[y] = line[j];

y++; j++;

j--; longitude_as_string[y] = '\0';

// To get id of the friend.

if (fi == 2)

{
j += 2;

while (line[j] != ',')

id_as_string[m] = line[j];

m++; j++;

j--; id_as_string[m] = '\0';

fi++;

// To get name of the friend.

else if (fi == 4)

j += 2;

while (line[j] != ',')

name[n] = line[j];

n++; j++;

j--; name[n] = '\0';

fi++; f += 2;

}
// Converting latitude and longitude

// in string to float.

lat2d = atof(latitude_as_string);

lon2d = atof(longitude_as_string);

distance_calculator();

// closing stream of customer's file.

customer_list.close();

// closing stream of answer's file.

out.close();

};

int main()

// Creating object of the structure json

json obj;

// To read customers.json file.

obj.json_parser();

return 0;

References:
1.Great Circle Distance
2. https://www.geeksforgeeks.org/finding-cabs-nearby-using-great-circle-distance-formula/
1. Introduction
Java is a general purpose, high-level programming language developed by Sun Microsystems.
The Java programming language was developed by a small team of engineers, known as
the Green Team, who initiated the language in 1991.

Originally called OAK, the Java language was designed for handheld devices and set-top boxes.
Oak was unsuccessful and in 1995 Sun changed the name to Java and modified the language to
take advantage of the burgeoning World Wide Web.

Later, in 2009, Oracle Corporation acquired Sun Microsystems and took ownership of two key
Sun software assets: Java and Solaris.

Java is defined as an object-oriented language similar to C++, but simplified to eliminate


language features that cause common programming errors. The source code files (files with
a .java extension) are compiled into a format called bytecode (files with a .class extension),
which can then be executed by a Java interpreter. Compiled Java code can run on most
computers because Java interpreters and runtime environments, known as Java Virtual
Machines (VMs), exist for most operating systems, including UNIX, the Macintosh OS,
and Windows. Bytecode can also be converted directly into machine language instructions by
a just-in-time compiler (JIT). In 2007, most Java technologies were released under the GNU
General Public License.
2. A Group chat application in Java
In this post, a group chat application using MulticastSocket (Java Platform SE 7) class is
discussed. A MulticastSocket is a (UDP) DatagramSocket, with additional capabilities for
joining “groups” of other multicast hosts on the internet.

Implementation:

import java.net.*;

import java.io.*;

import java.util.*;

public class GroupChat

private static final String TERMINATE = "Exit";

static String name;

static volatile boolean finished = false;

public static void main(String[] args)

if (args.length != 2)

System.out.println("Two arguments required: <multicast-host> <port-number>");

else

try

InetAddress group = InetAddress.getByName(args[0]);

int port = Integer.parseInt(args[1]);

Scanner sc = new Scanner(System.in);


System.out.print("Enter your name: ");

name = sc.nextLine();

MulticastSocket socket = new MulticastSocket(port);

// Since we are deploying

socket.setTimeToLive(0);

//this on localhost only (For a subnet set it as 1)

socket.joinGroup(group);

Thread t = new Thread(new

ReadThread(socket,group,port));

// Spawn a thread for reading messages

t.start();

// sent to the current group

System.out.println("Start typing messages...\n");

while(true)

String message;

message = sc.nextLine();

if(message.equalsIgnoreCase(GroupChat.TERMINATE))

{
finished = true;

socket.leaveGroup(group);

socket.close();

break;

message = name + ": " + message;

byte[] buffer = message.getBytes();

DatagramPacket datagram = new

DatagramPacket(buffer,buffer.length,group,port);

socket.send(datagram);

catch(SocketException se)

System.out.println("Error creating socket");

se.printStackTrace();

catch(IOException ie)

System.out.println("Error reading/writing from/to socket");

ie.printStackTrace();

}
}

class ReadThread implements Runnable

private MulticastSocket socket;

private InetAddress group;

private int port;

private static final int MAX_LEN = 1000;

ReadThread(MulticastSocket socket,InetAddress group,int port)

this.socket = socket;

this.group = group;

this.port = port;

@Override

public void run()

while(!GroupChat.finished)

byte[] buffer = new byte[ReadThread.MAX_LEN];

DatagramPacket datagram = new

DatagramPacket(buffer,buffer.length,group,port);

String message;
try

socket.receive(datagram);

message = new

String(buffer,0,datagram.getLength(),"UTF-8");

if(!message.startsWith(GroupChat.name))

System.out.println(message);

catch(IOException e)

System.out.println("Socket closed!");

Save the file as GroupChat.java and compile it using javac and then run the program using two
command line arguments as specified. A multicast host is specified by a class D IP address and
by a standard UDP port number. Class D IP addresses are in the range 224.0.0.0 to
239.255.255.255, inclusive. The address 224.0.0.0 is reserved and should not be used.

Additional points:

 You can incorporate network security feature by performing encryption before sending the
message over the network.

 Primitive techniques such as Caesar cipher or advanced methods such as RSA can be used
to perform encryption-decryption. You can try using Java’s RMI (Remote Method
Invocation) to perform the same task.
 Here, you can leverage the abstraction offered by Java to maximum extent. However, if
your primary objective is efficiency, then Socket programming is the best choice. Since it
doesn’t require any run time support, it is a bit faster compared to RMI.

Reference: https://www.geeksforgeeks.org/a-group-chat-application-in-java/

3. Generating Password and OTP in Java


You may go through Generate a One Time Password or Unique Identification URL article
before this for better understanding.

Many a times we forget our passwords and we opt for Forget password option and within no
time we get a new password at our registered email-ID or phone no. to login our account.
And every time we get a different password.
Sometime we access our bank accounts while shopping from an online store or many more
ways, in order to verify our transition from the bank account they send us OTP(One Time
Password) on our registered phone no. or our email-ID, within no time.
The following code explains how to generate such Passwords and OTP within no time and
what code we can use if in case we need to do so.
Java program explaining the generation of Password

// Java code to explain how to generate random

// password

// Here we are using random() method of util

// class in Java
import java.util.*;

public class NewClass

public static void main(String[] args)

// Length of your password as I have choose

// here to be 8

int length = 10;

System.out.println(geek_Password(length));

// This our Password generating method

// We have use static here, so that we not to

// make any object for it

static char[] geek_Password(int len)

System.out.println("Generating password using random() : ");

System.out.print("Your new password is : ");

// A strong password has Cap_chars, Lower_chars,

// numeric value and symbols. So we are using all of

// them to generate our password

String Capital_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

String Small_chars = "abcdefghijklmnopqrstuvwxyz";

String numbers = "0123456789";

String symbols = "!@#$%^&*_=+-/.?<>)";


String values = Capital_chars + Small_chars +

numbers + symbols;

// Using random method

Random rndm_method = new Random();

char[] password = new char[len];

for (int i = 0; i < len; i++)

// Use of charAt() method : to get character value

// Use of nextInt() as it is scanning the value as int

password[i] =

values.charAt(rndm_method.nextInt(values.length()));

return password;

Java program explaining the generation of OTP(One Time Password)

// Java code to explain how to generate OTP

// Here we are using random() method of util

// class in Java

import java.util.*;

public class NewClass

static char[] OTP(int len)

System.out.println("Generating OTP using random() : ");

System.out.print("You OTP is : ");


// Using numeric values

String numbers = "0123456789";

// Using random method

Random rndm_method = new Random();

char[] otp = new char[len];

for (int i = 0; i < len; i++)

// Use of charAt() method : to get character value

// Use of nextInt() as it is scanning the value as int

otp[i] =

numbers.charAt(rndm_method.nextInt(numbers.length()));

return otp;

public static void main(String[] args)

int length = 4;

System.out.println(OTP(length));

Reference: https://www.geeksforgeeks.org/generating-password-otp-java/
4. Creative Programming In Processing | Set 1 (Random
Walker)
Creative programming is a type of programming approach in which the goal is to
create something expressive and visual instead of something that is purely
functional. This type of programming approach is used to create live artworks,
graphical simulations and visualize algorithms. There exists a number of tools and
libraries for creative or visual programming of which Processing is the most widely
used. Processing is an open source programming language and IDE that built for
visual programming purposes. It is also available as a python dialect and a javascript
framework. In this article we will build a simple random walker program which is just
a ball moving randomly across the canvas.
Each processing sketch typically consists of two functions:

(i) setup() – It is called once at the beginning and is generally used for initialization
purposes.
(ii) draw() – It is called 30 times per second by default making the default framerate
of the animation being 30 frames per second.

Implementation of sketch:

The sample codes have been written in java using the processing library and the
processing IDE.

Walker w; // Walker object

void setup() // Called at the beginning once


{
size(640, 360); // Declaring size of the output window
w = new Walker(); // Initializing the new walker object
}

void draw() // Called every frame


{
background(255); // Setting a white background
w.display(); // Displaying the walker object
}

Implementation of Walker class:

class Walker // The walker class


{
PVector location; // A vector object representing the location

Walker() // Constructor to initialize the data member.


{

// Initial location of the walker object is


// set to the middle of the output window.
location = new PVector(width / 2, height / 2);
}

void display() // Function to display the walker object


{
// Drawing a black circle of radius 10 at location
fill(0);
ellipse(location.x, location.y, 10, 10);
}
}
At this point if we run the sketch, it just displays a ball that sits at the center of the
output screen-
In order to move the walker object, we will add a walk() function to the Walker class
and call it inside the draw() function in the sketch. We also a checkEdges() function
in Walker to prevent the Walker object from moving out of the screen. We must also
modify the sketch to include the new functions we add in the Walker class. We can
also do one more thing, move the background() function inside setup(). This way, the
background will not be updated every time and we will be able to see the trail, the
Walker object leaves behind.

Modified Implementation of sketch:

// Program to implement random walker

Walker w; // Walker object

void setup() // Called at the beginning once


{
size(640, 360); // Declaring size of the output window
background(255); // Setting a white background
w = new Walker(); // Initializing the new walker object
}

void draw() // Called every frame


{
w.walk(); // Walking the Walker object
w.checkEdges(); // Checking for edges of the output screen.
w.display(); // Displaying the walker object
}

Modified Implementation of Walker class:

class Walker // The walker class


{
PVector location; // A vector object representing the location

Walker() // Constructor to initialize the data member.


{
// Initial location of the walker object is
// set to the middle of the output window.
location = new PVector(width / 2, height / 2);
}

void walk()
{
// The x and y values of the location
// vector are incremented by a random value
// between -5 and 5
location.x += random(-5, 5);
location.y += random(-5, 5);
}

// Function to prevent the Walker to move out of the screen


void checkEdges()
{
if (location.x < 0)
location.x = 0;
else if (location.x > width)
location.x = width;
if (location.y < 0)
location.y = 0;
else if (location.y > height)
location.y = height;
}

void display() // Function to display the walker object


{
// Drawing a black circle of radius 10 at location
fill(0);
ellipse(location.x, location.y, 10, 10);
}
}

Reference: https://www.geeksforgeeks.org/creative-programming-processing-set-1-
random-walker/

Potrebbero piacerti anche