Pages

Showing posts with label using. Show all posts
Showing posts with label using. Show all posts

Saturday, February 4, 2017

Sun Surveyor brings augmented reality to photographers using Google Maps APIs



(Cross-posted on the Geo Developers Blog.)

Editors note: Today’s guest blogger is Adam Ratana, developer of Sun Surveyor. Read how Sun Surveyor is using Google Maps APIs to help photographers capture the perfect photo.

I’m a photography enthusiast, and I’m always looking for ways to improve my work. That’s what led me to develop Sun Surveyor, an iOS and Android app that uses Google Maps APIs to visualize the location of the sun and the moon anywhere in the world. The app makes it easy to figure out when the natural lighting will be just right — and get the ideal shot.

Sun Surveyor uses augmented reality to overlay the paths of the sun and moon on a camera’s view, so you can see where in the sky they’ll be at a specific time and place. Photographers can use it to plan their shots ahead of time, and businesses can use it to gauge things like how best to align solar panels to make the most efficient use of the angle of the sun.

The app uses multiple Google Maps APIs, including the Elevation API, the Time Zone API, the Google Maps SDK for iOS and the Google Maps Android API. The Android API, which includes Street View, was particularly helpful. It allowed me to overlay the path of the sun and moon on any Street View location anywhere in the world. For programming details, see this blog post.

The following screen captures give you a sense of how the app works. They show overlays on top of the iconic Half Dome in Yosemite National Park. The first shows the paths of the sun (yellow line) and moon (blue line) over an aerial view of Yosemite Valley. The green line shows the distance between the photographer and the object to be photographed — in this case, Half Dome.


This next screen capture shows how the app looks when in Street View mode. Again, the yellow line shows the sun’s path, and the blue line shows the moon’s path. The green line represents the horizon. You can see how the app lets you plan the right time to get a shot of the sun behind Half Dome: in this particular instance, 8:06 am.

Nearly 500,000 people around the world have downloaded the free version of Sun Surveyor, and many have paid for the full edition. They’re taking remarkable photos as a result, and what started as a hobby for me has turned into a business — thanks to Google Maps APIs.


Read More..

Thursday, November 24, 2016

Pornhub Mobile APK Pornhub Android APP Pornhub APK Free Download


Pornhub Mobile APK | Pornhub Android APP | Pornhub APK Free Download

Pornhub Mobile APK | Pornhub Android APP | Pornhub APK Free Download
Pornhub Mobile APK | Pornhub Android APP | Pornhub APK Free Download

Watch Pornhub Videos from your android mobile phone or tablet

Pornhub_2.4.2.apk

Pornhub is one of the largest sources of pornography on the internet, with thousands of videos to suit any and all tastes. The Pornhub app basically puts the website on your Android phone, and its a well-designed and professional looking app. Pornhub also publishes annual demographics display which kinds of devices have been used to access which kind of videos. Its a very useful source of pornography and statistics.

Pornhub Mobile APK | Pornhub Android APP | Pornhub APK Free Download


Click Here to Free Download Pornhub_2.4.2.apk

Pornhub Mobile APK | Pornhub Android APP | Pornhub APK Free Download

Read More..

Friday, October 28, 2016

Google Vault now covers Hangouts for work chat


As an IT admin you want your organization to be free to focus on getting stuff done. But part of your role is also to make sure you stay on top of legal compliance. Today we’re making it a little bit easier to do both with two new Hangouts features.

Over the next few days, we’ll roll out an admin option that lets you manage Hangouts chat history in your organization, so that you can make certain that it’s either on or off. People in your organization can have the freedom to chat with whomever they want — whether that person is part of your organization or not — and you can be sure that new employee conversations stay personal and private, because they’ll disappear shortly after taking place.
We’re also adding Google Apps Vault support for Hangouts chat. With Vault support for chat, organizations of all sizes can quickly find and preserve chat messages. This is a great way to safeguard business-critical information for continuity, compliance and regulatory purposes.

Find out how to tailor Hangouts to best suit your organizations compliance needs.
Read More..

Sunday, September 25, 2016

Mobile Andrio Full apk


Mobile Andrio Full Apk
Requirements: Android 1.6+

Mobile Andrio Full Overview: A jump & run game in the style of Super Mario, Giana Sisters and similar games.
A jump-and-run game in the style of Super Mario, Giana Sisters and similar games. It has 16 levels of increasing difficulty.
Highscores get uploaded to the social gaming network Scoreloop, and you can compare your highscore with those of players all around the world. Furthermore you can start challenge games against other players to determine the better player in a 1:1 situation.
The game can be controlled using keyboard (preferred), touchscreen, orientation sensor or trackball. Use Edit Settings to customize.
Full version, free of ads. Permissions required for Scoreloop features.
For more information, please check the apps website.

Whats in Mobile Andrio Full :
  • improved the placement of the on-screen controls
  • bug fixes
Mobile Andrio Full  screenshot:
Mobile Andrio Full 2.8.3 (Android) 
 
DOWNLOAD
Read More..

Thursday, July 14, 2016

m Shadi"

samsung,mobile,sdk,–,introducing,the,complete,package
Read More..

Wednesday, June 15, 2016

Stream mobile contents to your TV using new Samsung Android App

Yes, finally Samsung made it real. You can watch your videos recorded in your Android phone on your TV! The reverse is also possible, you can watch TV programs on your mobile, also you can use your phone as a remote control. Play your favorite games on your TV, control the game using your phone!

This feature is available only in Samsung Galaxy S II, but will be enabled on other Samsung smart phones soon including Samsung Galaxy Tab.

You need a TV Model greater or equal to LED 7000 from Samsung:

UA46D7000LM
UA55D8000YR

These models are capable of connecting to the the network and the Internet using a wired or WiFi connection and steam content from internet, news, videos or social media whatever it is!

Download Samsung Smart View from Android Market
Read More..

Friday, June 3, 2016

Allstate helps people uncover risks to their homes using Google Maps



Editors note: This month Google Maps turns ten! Since launching ten years ago, use cases for maps have come a long way. To celebrate a decade of mapping, we’re highlighting new and innovative ways developers are deploying maps. Read how guest blogger, Elizabeth Schreier, Director of Digital and Social Engagement at Allstate Insurance, is relying on Google Maps APIs to bring unique mapping experiences to their users.

Imagine looking at a map of your house and seeing a visual diagnosis of the biggest risks in your area — whether the risk is fire, theft or even freezing pipes. Then imagine getting helpful tips that could help you protect your home against those risks. That’s what we’ve done with GoodHome, a project we created at Allstate with our agency, T3.

We built GoodHome to make a tool that anyone would find useful, whether or not they were an insurance customer or even a homeowner. We realized we could use our proprietary information about insurance claims to help people identify the most common and costly claims in their respective ZIP codes. We decided to visualize this information, along with relevant property statistics, on an interactive map that included tips to help people mitigate potential risks.
We built GoodHome using the Google Maps APIs because of its familiarity, ease of use and comprehensive features. The development team at T3 created the GoodHome prototype using three Google Maps APIs: Static Maps, JavaScript and Street View Image APIs. They customized the maps by drawing layers, integrating a weather API and using CSS to create animations that brought the experience to life. The development process went smoothly and took just three months from concept to completion.

GoodHome is more than informative, it’s compelling. A visitor who uses the GoodHome tool is over 350% more likely to request an insurance quote than one who doesn’t. Forty percent of people type more than one address into the map, and on average, visitors stay on the site for six to seven minutes.

GoodHome also helps our agents build better relationships with customers. When an Allstate customer receives a link to the GoodHome website from their agent, the map automatically opens up to the customer’s home address. The personalized interaction helps agents connect with their clients and provide a great consulting tool that opens the door for a conversation. We plan to introduce GoodHome to all 10,000 Allstate agents across the country so they can spread the tool to their customers.

We’re excited to play a role in enhancing the home insurance experience for consumers. The power of Google Maps has helped us make a product that we hope will help people see their homes in a new way and think differently about what it means to protect what matters to them.
Read More..

Wednesday, April 13, 2016

Cameras in Phones what do we really need


An awful lot is being said about mobile phone cameras just lately; and we have HTC to thank for opening the conversation with the introduction of their HTC One which has half as many pixels at twice the size of anyone elses. Before we begin Im going to get some ground rules. I wont use marketing terms; so I will talk about how many pixels a camera sensor has, and what size they are. You wont hear me talking about mega- or ultra- anything. Next is that I will show my meaning with diagrams - Im a visual person and it helps me to explain. Please bear with me on this post; theres a lot to read but its worth it at the end.

A digital camera uses a lens to focus an image onto an oblong of special material which has a number of sensors on it; each sensor is called a pixel and usually contains three sub-pixels; a red, a blue (actually two blues but dont worry about that) and a green one. Each of these sends a signal to the camera depending how much light of that colour is falling onto it. Bigger pixels produce a bigger signal for the same amount of light than smaller ones. When signals are small, the amount of noise (erroneous signal levels produced simply by electrons moving around) is a bigger percentage of the whole signal because noise is a constant backdrop. When the signals are bigger therefore, its easier to pick out the signal, from the noise. More noise means that the signal produced by a smaller pixel is less accurate which means the final photo may not have exactly the same colour from each pixel receiving the same light.

Camera sensors line up their pixels in rows and columns - and the cameras rating is often quoted by counting them. For instance a 10MP camera contains ten million pixels (roughly). These are arranged in a rectangular grid with a side length ratio of 16:9 - so thats 4213 pixels across and 2370 pixels high. If you have a sensor which is 7mm across, each pixel is 7/4213=1.662 microns across (microns = thousandths of a millimetre).

In the real world, standard sensor sizes and pixel sizes exist; a 13 million pixel camera in a phone will have pixels about 1.1 microns across; this gives a sensor width of about 4.55mm (there are 4128 pixels across the image). In the HTC One, the best photos are 2688 pixels across, and the pixels are 2 microns across giving a sensor width of about 5.4mm.
Figure 1 - 4 million large pixels
Figure 1 - 4 million large pixels

Figure 2 - 8 million (smaller) pixels on same size sensor
Figure 2 - 8 million (smaller) pixels on same size sensor
Now we can start looking at construction. Take a look at Figure 1. This shows a camera with large pixels - the lens is focussing the image onto an area exactly the same size as the sensor. In Figure 2, we gave the camera more pixels (which really does give more detail in the image but at the expense of noise and grain - and also less sensitivity at low light levels). Of course; straight away you want more, BIGGER pixels. Figure 3 shows that if you make that happen, the image doesnt cover the whole sensor; the light falls on a little bit of it. So - in Figure 4 we move the sensor further away to ensure the image covers all the pixels.
Figure 3 - 8 million large pixels with no other changes
Figure 3 - 8 million large pixels with no other changes

Figure 4 - Sensor moved away, but the lens size is unchanged.
Figure 4 - Sensor moved away, but the lens size is unchanged.
However; the same amount of light, entering the lens, is now spread over a wider area: this dims the light hitting each individual pixel, which reduces the signal output and increases the noise. The only way to change this is to make the lens bigger - the aperture wider - so that more light gets in. This is shown finally in Figure 5.
Figure 5 - all required changes incorporated.
Figure 5 - all required changes incorporated.
So - how far back do we have to move the lens? Simple trig shows us the answer. Imagine the "field of view" of the lens is about 60° (not unreasonable): the light coming in from the left and right cross over in the centre of the lens and make a triangle with the sensor as the base... an equilateral triangle is formed with all angles at 60° and all sides the same length (lets call it 5.4mm to stick with the HTC Ones sensor size). So the lens must be 2.7mm away from the sensor. If we now make the sensor an 8MP one (3800x2140 pixels) that gives a width of 7.6mm - the lens still has a viewing angle of 60° so that means the sensor has to be 3.8mm away from the lens. Obviously I have used 60° as the lens viewing angle because it makes the angles, sines and side lengths easy to calculate - the numbers are probably quite different in real life but you get the idea: to get double the megapixels you have to move the sensor further from the lens, which means you need a bigger lens to gather the light needed to adequately illuminate it. Lenses very rapidly increase in price with size - a lens 4mm across instead of 2mm might cost three or four times as much. (BTW - the large circular opening on the back of the phone is NOT the lens; the lens is the tiny dark speck in the centre of it).

In practical terms for a smartphone? This means that, to get an 8 million pixel camera, with pixels 2 microns across, your phone would need to be about 16-18mm thick (at least at the cameras location); and the phone would cost upwards of US$1000 - possibly even more - JUST because of the lens.

This isnt something which can be corrected with better design, or better lenses; the only way to mitigate this increase in size and cost would be to make smaller pixels which had the properties of larger ones - and that my friends is the nirvana of a pixel scientist! The very best technology available is going into these phones - and with todays tech were stuck with these limitations. In another article Ill talk about why I believe 4MP at 2 microns across is enough.


This article is also to be found on its author personal blog.

Have any questions or comments? Feel free to share! Also, if you like this article, please use the media sharing buttons (Twitter, G+, Facebook) under this post!
Read More..

Saturday, April 9, 2016

Keep all of your work more secure with Google Drive



Since we launched Drive for Work 9 months ago, weve watched as more and more businesses moved to the cloud — and seen that they prioritize data security as much as we do. Security ranks at the top of the list of concerns that companies have about moving to the cloud, which is why we’ve put security front and center in our products from the beginning. And to keep your company’s data even more secure in Drive, we’re launching new sharing controls, alerts and audit events to Google Drive for Work and Google for Education over the next several weeks.

For Google Drive for Work customers:
Set sharing settings by department
Sometimes different file settings make sense. You might, for example, have a research department that needs to keep information confidential and a sales team that needs to share presentations with their clients. To help manage these different sharing needs, now when you make selections in Drive settings from the Admin console, you can turn off sharing outside the domain for one organizational unit, while still allowing others to work and share files with anyone they need to.

Create custom Drive alerts and track more events with Drive audit
To keep track of when specific actions are taken in Drive, you can set up custom Drive alerts. So if you want to know when a file containing the word “confidential” in the title is shared outside the company, now you’ll know. And there are more events coming to Drive audit, including download, print and preview.
For all Google Apps for Work customers:
Set up custom admin alerts to find out when things change
There are lots of moving parts to running a company, and now it’s easier for IT to find out about the things they care about with custom alerts — like when a new app is installed or a shared calendar is deleted — and get those right in their inbox.

Let people reset their own passwords
Recovering passwords isn’t the most pleasant thing we do in our lives. But now IT can let employees securely reset their own passwords, so they don’t lose valuable time being locked out of their account. If this doesn’t make sense for your organization, admins can simply turn this ability off.

Available for all to use:
Disable downloading, printing and copying of any file with IRM
With Information Rights Management (“IRM”) you can disable downloading, printing and copying from the advanced sharing menu – perfect for when the file you’re sharing is only meant for a few select people. This new option is available for any file stored in Google Drive, including documents, spreadsheets and presentations created in Google Docs.

Share quickly with anyone outside your organization
When it comes to sharing, like giving final inventory lists to your caterer or last minute logos to your design agency, you want to make sure people can see it right away — whether they use Drive or not. Now, you can share with any email address and they’ll be able to view the files you share —without having to sign-in to a Google account. Admins can disable this feature for certain departments that want to require sign-in before , while enabling it for others.

All the above are rolling out over the next month.

Stay tuned for more
We’re also working on the ability to establish trusted domains, so businesses and schools that have multiple Google Apps domains or want to work with trusted partners or customers, can select multiple Google Apps domains that are OK to share with from Drive and Classroom. And on expiring access, because occasionally you only want to share files for a temporary amount of time. With expiring access you can set a future date when access will be removed. Stay tuned, theres more to come from Drive and Drive for Work.
Read More..

Thursday, March 24, 2016

Doctor on Demand Improves Patient Care using Google Maps APIs



Editors note: Since the launch of Google Maps ten years ago, maps have come a long way. To celebrate a decade of map innovation, we’re highlighting unique maps built by our developer community. Read how guest bloggers, Ed Bindl and Jacinda Shelly, Software Engineers for Doctor on Demand, use the Google Maps APIs to bring unique mapping experiences to users.

Maps can do much more for an online business than help people get from point A to point B. You might not think that a website for making video appointments with medical professionals would benefit from mapping — but at Doctor on Demand, maps connect our patients to physicians faster and allow physicians to prescribe medications at the right pharmacies. Google Maps make our user experience much more satisfying, which means patients will use our service again.
We use the Google Maps APIs, including the Geolocation and Javascript APIs, to show patients a map of nearby pharmacies before they start a video call with a medical professional. For our users, maps make it easy and convenient to connect with physicians and pick up prescriptions at the pharmacy. But maps can be helpful for other businesses in other ways. And now that we see the great value of incorporating reliable map functionality into our app, wed love to share how you can do the same:

  • Choose a familiar interface. Use a map that’s easy for people to navigate – if it’s hard to understand and requires extensive instructions, they won’t use it. We picked Google Maps because our patients know them well.

  • Configure maps for many platforms. If your users find maps helpful on your desktop website, they’ll want to use maps from any browser or device. We’ve made sure our maps work just as well on iOS and Android devices as they do on a desktop computer.

  • Maintain accuracy. In our case, we have to update the geolocation information for about 65,000 pharmacies across the country every evening. We use the Google Maps Geocoding API, which minimizes the time it takes to keep our map accurate. We keep a database of all pharmacies from Surescripts, a healthcare network, and each night we get an update to that database that adds, removes, and updates pharmacies and their locations. We use the Google Maps Javascript API to place the pharmacies on our map when a patient is asked to select a pharmacy.

  • Meet compliance standards. In order to comply with medical regulations, Doctor On Demand must connect patients with physicians licensed in their state. We use the Google Maps Reverse Geocoding API to accurately determine the state a patient is located in before connecting them with a physician.

  • Help users save time and make better choices. Before we built our pharmacy map, patients had to tell doctors which pharmacy they wanted to use. Then doctors emailed us the details. However, our support team had to follow up with doctors and patients to make sure we had the right pharmacy, since patients might say something like, “the drugstore down the street from my house.” Today, there’s no doubt about which pharmacy is the right one, since patients can clearly see their local outlets on the map.

Our pharmacy map inspires us to think about new ways to use maps in the future – like plotting the movement of cold and flu outbreaks and sharing this data with patients and doctors. We see a direct connection between maps and improving patient care. In the greater scheme, Google Maps improve the health of our patients, and, the health of our business.


Read More..

Monday, March 14, 2016

Madison Fifth builds interactive mall experiences for kiosks and mobile using Google Maps APIs


Editors note: Today we hear from Chris Shirer, President and Chief Strategist of the digital brand management agency Madison + Fifth. Read how Madison + Fifth and Google Maps for Work Partner Woolpert used Google Maps APIs to build an interactive kiosk and mobile apps for the 60-acre Liberty Center mixed-use shopping center.

When the Liberty Center retail center outside of Cincinnati approached us to provide accessible, intuitive wayfinding for visitors, we saw the opportunity to create something unique — not just a standard kiosk and printed directory. The center includes shopping, restaurants, a hotel, offices and luxury housing, so we wanted to make sure visitors could get around quickly, especially during busy times like this past holiday shopping season. We decided to build a solution that would work on touchscreen kiosks and mobile devices to detect visitors’ locations and give them interactive walking directions in real time.

We chose Google Maps and Google Maps APIs to do it because Google offers a familiar interface for our customers, lets us layer custom information on top of maps and provides a platform that will allow us to add new features, like delivering relevant, location-based ads. We worked closely with Google Maps for Work Partner Woolpert to build the solution. Woolpert not only helped us with licensing information, but also did the programming based on our design and requirements.

Because we wanted the directory to work with both touchscreen kiosks and iOS and Android devices, we built a Web app using the Google Maps JavaScript API. The app scales automatically up to the large size of the kiosk and down to smartphones’ small screen sizes. With a Web app, we don’t have to build and maintain apps on multiple devices, and visitors with smartphones don’t have to download anything to use the service.
We started building the app before the Liberty Center was finished and opened to the public, which meant that Google didn’t yet have mapping information for the center’s streets and stores. We solved this by building a layer with the required information on top of the map. In addition, we had no routing information, so we built an algorithm to provide directions using open source Google Optimization Tools.

Liberty Center opened its doors on October 22, 2015, and thanks to Google Maps, we’re now delivering an engaging, interactive experience for visitors. People who walk up to the kiosks or use the Web app on their smartphones get customized walking directions based on their current location, and can zoom in and out around the property to explore shops and other destinations. Liberty Center shoppers can spend less time getting from place to place and more time in stores and enjoying time together in restaurants.
Read More..

Saturday, April 12, 2014

Using Virtual Base Classes to Avoid Ambiguity

Let’s start this with the following example program:



// this program contains errors
#include<iostream.h>

// base class
class base
{
public:
int a;
};

// derived class (1)
class derived1:public base
{
public:
int b;
};

// derived class (2)
class derived2:public base
{
public:
int c;
};

// derived class (3)
class derived3:public derived1, public derived2
{
public:
int d;
};

// main
void main()
{
derived3 ob;

// this is ambiguous
// since two copies of
// base is present in
// the class derived3
// one from derived1 &
// the other from derived2
ob.a=10;
}


The program above contains an error (as stated) in the following line:


ob.a=10;


Since the base class is inherited by the two classes (derived1 and derived2),
which are again inherited (both together) by another class derived3, there are
two copies of the base class (and hence two copies of variable ‘a’
too).


Therefore when we refer to the variable ‘a’ with respect to the
derived3 class then as there are two copies of it, it becomes ambiguous or confusing
for the compiler to select one from the two and hence it is reported as an ERROR.


This is very common error which creeps in when you write long and complex program
consisting of classes some of which are hierarchically inherited.


So how can we prevent this from happening?


Actually, we can prevent this by using the scope resolution operator but this
is not a permanent solution besides having other flaws. Then what else can we
do?


Yeah, you guessed it right; Virtual Base Class is he answer.


Now, have a look at the same program with slight modification (as to apply
the virtual base class method), now it’s perfectly all right!



// Virtual base classes
#include<iostream.h>

// base class
class base
{
public:
int a;
};

// derived class (1)
// notice the use of virtual keyword
class derived1:virtual public base
{
public:
int b;
};

// derived class (2)
// notice the use of virtual keyword
class derived2:virtual public base
{
public:
int c;
};

// derived class (3)
class derived3:public derived1, public derived2
{
public:
int d;
};

// main
void main()
{
derived3 ob;

// now its O. K.
ob.a=10;
}


As you can see, we’re using virtual keyword to derive the classes (derived1
and derived2) from the base class.


This prevents other inheriting classes (which inherits more than one such derived
classes) to have only one copy of the base class and hence ruling out chances
of ambiguity.


Please note that the derived classes (derived1 and derived2 individually) still
contains one-one copy of base class, it is only when they are inherited is the
virtual nature comes into action.


We conclude this article with the following example program to illustrate all
that we have discussed so far in this article.



// Virtual base classes
#include<iostream.h>

// base class
class base
{
public:
int a;
};

// derived class (1)
// notice the use of virtual keyword
class derived1:virtual public base
{
public:
int b;
};

// derived class (2)
// notice the use of virtual keyword
class derived2:virtual public base
{
public:
int c;
};

// derived class (3)
class derived3:public derived1, public derived2
{
public:
int d;
};

// main
void main()
{
derived1 ob1;
derived2 ob2;
derived3 ob3;

// derived classes still
// contain one-one copy
// of the base class
ob1.a=10;
ob2.a=20;

// but the class derived
// form the classes of
// the above two objects
// contains only one copy
// of the base class
ob3.a=100;
}


Related Articles:


Read More..

Tuesday, April 8, 2014

A Simple Pong Game using JavaScript

Pong Game in JavaScript Screenshot


Having the knowledge of moving images using JavaScript, we’ll be creating a small Ping Pong game as an example for this post.


Today we’ll learn to do a few new things in JavaScript:


1. Executing some code every specified time interval (for game loop).

2. Tracking and using mouse movements.

3. Attaching code (function) to events.


Game Theory


As you should be knowing, in this game there is one ball and two paddles at two ends. One is user-controlled the other, for this example, is CPU controlled. User has to move the paddle in order not to let the ball pass through, CPU also has to do the same thing. Whoever’s side the ball passes through looses the game.


There are a few objects which can interact with each other, these are ball, paddles, walls. Let’s see the various interactions that can take place between these:




  1. Ball Hitting Upper/Lower Wall – Ball will bounce off.




  2. Ball Passing Through Either Side – Player or CPU, depending on whose side ball passed through, will loose the game.




  3. Ball Hitting Paddle – It’ll bounce off




We’ll need to take care of these events:




  1. Page Load – Game objects will be initialized




  2. Game Start – Mouse click on the player paddle will start the game.




  3. Mouse Movements – Inside the game area (a div), the paddle will follow the y-position of the mouse. Paddle however should not get past the boundaries.




  4. CPU Paddle – The paddle will follow the ball by moving up/down depending the relative position of the ball. We’ve added a little intelligence by only moving the paddle while ball is coming towards it. This will make the movement as well as the game look more real.




Code


NOTE: Put two files ball_small.png, paddle.png (Right-Click "Save As") in the same directory the script is in.



<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Pong Game In JavaScript</title>

<style>
#box
{
width: 500px;
height: 300px;
margin: auto;
border: 5px solid #ccc;
position: relative;
overflow: hidden;
}

.ob
{
position: absolute;
border: 0px;
}
</style>
<script type="application/javascript">

// CHANGE THESE, IF REQUIRED
var Speed = 5; // Speed of ball (pixels/step)
var CPUSpeed = 5; // Speed of CPU Paddle (pixels/step)

// Short references to objects
var paddle1;
var paddle2;
var ball;
var box;
var msg;


// For internal use
var dx, dy; // Speed in x and y directions
var ballX, ballY; // x and y positions of ball
var playerY; // y position of player paddle (x fixed)

var cpuY; // y position of CPU paddle (x fixed)
var iID; // To store ID of set interval used to clear it when required

// Attach a function to onLoad event
window.onload = Init;

// INITIALIZE GAME OBJECTS
function Init()
{
// Make short refrences to objects

paddle1 = document.getElementById(paddle1);
paddle2 = document.getElementById(paddle2);
ball = document.getElementById(ball);
box = document.getElementById(box);
msg = document.getElementById(msg);

// Initial values
ballX = (box.offsetWidth / 2) - (ball.offsetWidth / 2);
ballY = (box.offsetHeight / 2) - (ball.offsetHeight / 2);
cpuY = (box.offsetHeight / 2) - (paddle2.offsetHeight / 2);
playerY = (box.offsetHeight / 2) - (paddle1.offsetHeight / 2);
dx = dy = Speed;

paddle1.style.left = 20 + px;
paddle1.style.top = playerY + px;
paddle2.style.left = box.offsetWidth - (20 + paddle2.offsetWidth) + px;
paddle2.style.top = cpuY + px;
ball.style.left = ballX + px;
ball.style.top = ballY + px;

// Show message

msg.innerHTML = <h2>Click on Paddle to Start Game.</h2>;
}

// START GAME
function Start()
{
// Attach a function to onmousemove event of the box
box.onmousemove = MovePaddle;
// Call GameLoop() function every 10 milliseconds

iID = setInterval(GameLoop(), 10);

msg.innerHTML = ;
}

// MAIN GAME LOOP, CALLED REPEATEDLY
function GameLoop()
{
// MOVE BALL
ballX += dx;
ballY += dy;

// See if ball is past player paddle

if(ballX < 0)
{
clearInterval(iID);
Init();

box.onmousemove = ;

msg.innerHTML = <h2>You Loose!<br/>Click on Paddle to Re-Start Game.</h2>;
}

// See if ball is past CPU paddle

if((ballX + ball.offsetWidth) > box.offsetWidth)
{
clearInterval(iID);
Init();

box.onmousemove = ;

msg.innerHTML = <h2>You Win!<br/>Click on Paddle to Re-Start Game.</h2>;
}

// COLLISION DETECTION

// If ball hits upper or lower wall
if(ballY < 0 || ((ballY + ball.offsetHeight) > box.offsetHeight))
dy = -dy; // Make x direction opposite

// If ball hits player paddle

if(ballX < (paddle1.offsetLeft + paddle1.offsetWidth))
if(((ballY + ball.offsetHeight) > playerY) && ballY < (playerY + paddle1.offsetHeight))
dx = -dx;

// If ball hits CPU paddle
if((ballX + ball.offsetWidth) > paddle2.offsetLeft)
if(((ballY + ball.offsetHeight) > cpuY) && ballY < (cpuY + paddle2.offsetHeight))
dx = -dx;

// Place ball at calculated positions

ball.style.left = ballX + px;
ball.style.top = ballY + px;

// MOVE CPU PADDLE
// Move paddle only if ball is coming towards the CPU paddle
if(dx > 0)
{
if((cpuY + (paddle2.offsetHeight / 2)) > (ballY + ball.offsetHeight)) cpuY -= CPUSpeed;
else cpuY += CPUSpeed;

paddle2.style.top = cpuY + px;
}
}


// TO MOVE PLAYER PADDLE ON MOUSE MOVE EVENT
function MovePaddle(e)
{
// Fetch y coordinate of mouse
var y = (e.clientY - (box.offsetTop - document.documentElement.scrollTop));
// Here, (box.offsetTop - document.documentElement.scrollTop) will get the relative
// position of "box" w.r.t to current scroll postion

// If y below lower boundary (cannot go above upper boundary -
// mousemove event only generated when mouse is inside box
if(y > (box.offsetHeight - paddle1.offsetHeight))
y = (box.offsetHeight - paddle1.offsetHeight);

// Copy position
playerY = y;
// Set position

paddle1.style.top = y + px;
}
</script>
</head>

<body bgcolor="#fff">
<h1 align="center">Pong Game Example in JavaScript</h1>

<div id="box">
<img class="ob" id="paddle1" src="paddle.PNG" onclick="javascript: Start()"/>

<img class="ob" id="paddle2" src="paddle.PNG" />
<img class="ob" id="ball" src="ball_small.PNG" />

</div>
<div id="msg" align="center"></div>
</body>
</html>

Related Posts:


Read More..