Você está na página 1de 56

1

PROJECT REPORT
ON

CORE JAVA-GAMING
SUBMITTED IN FULFILLMENT OF THE DEGREE UNDER THE PANJAB UNIVERSITY (B.C.A-2010-2013 Batch)
GGDSD COLLEGE,SEC-32C,CHANDIGARH

Submitted to:

Submitted By:

TEACHER HEAD-Ms.Gagandeep Kaur H.O.D-Mr Virender singh

Sahil singla Rollno.18010000580 Peeyush gupta Rollno.18010000570

CERTIFICATE
It is to certify that the project work entitled CORE JAVA GAMING which is being submitted by us as a part of Graduation Project undertaken in the month of March is an authentic work carried out by us at Department of Computer applications, under the supervision and guidance of Ms.GaganDeep Kaur.

The matter imbedded in this project work has not been submitted earlier for the award of any other degree student.

Sahil singla Rollno.18010000580 Peeyush gupta Rollno.18010000570

Acknowledgement
I take this opportunity to express my deepest gratitude to those who have generously helped me in providing the valuable knowledge and expertise during my making of project.

I am thankful to Department of Information technology

for his

thorough guidance right from day 1st till the end of the graduation(3rd year). I shall also like to specially thank our Incharge, Ms.GaganDeep Kaur (Lecturer) for giving me the required guidance and removing any difficulties faced by me during the project. And finally, I would like to thank each and every person who has contributed in any of the ways in my Project.

Sahil singla Rollno.18010000580 Peeyush gupta Rollno.18010000570

INDEX
PAGE CONTENTS
INTRODUCTION TO POJECT:
-PURPOSE -PROJECT SCOPE 7 7

NO.

REMARKS

PRODUCT FEATURES SECURITY LEVEL OPERATING ENVIRONMENT DESIGN AND IMPLEMENTATION CONSTRAINTS:
-SYSTEM FEATURES -FUNCTIONAL REQUIREMENTS -RESPONSE SEQUENCES

8 8 8

9 9 9

-EXTERNAL INTERFACE REQUIREMENTS -SOFTWARE QUALITY ATTRIBUTES

9-10

10

OBJECTIVES OF PROJECT SYSTEM REQUIREMENTS:


-PROBLEM RECOGNITION -FUNCTIONS TO BE PROVIDED

11-12

13-14 14 15-16

INTRODUCTION TO J2EE FRAMEWORK OOP PRINCIPLES SOFTWARE REQUIREMENT SPECIFICATION(SRS) SYSTEM DESIGN: -THE EXTERNAL DESIGN
-DESIGN OBJECTIVES -CHARACTERISTICS

17-19 20-22

23 23 24

SYSTEM IMPLEMENTATION:
-INTRODUCTION -TYPES -TOOLS 25-26 26 27-29 30-52

CODING OF PROJECTGAMING PACMAN SCREEN LAYOUT REFRENCES

53-55 56

INTRODUCTION TO PROJECT
1. Introduction
1.1 Purpose
This project is provide you a information of core java concept i.e applet.in project we used a applet concept in which we use their cycle concept and made a game known as Pacman,in this game there is a creature try to collect the coins as more as possible . To make this we use applet viewer window and applet functions.

1.2

Project Scope

Expert Rating is a skill assessment. It is an effective method of ensuring you have the skills needed for your job. Expert Ratings testing tool creates valid tests for various skill levels. Save your time and money, and reduce the possibility of interview failure by giving a pre-hiring skill assessment directly over the CMD. No software other than a Command Prompt is needed. Expert Rating assures a reliable service, ease-of-use. Work to be done: To handle the control navigation from other Applet window. Writing the Code Behind pages for the project. Database Design if needed. Apply all the check constraints according to the requirements.

Product Features :
This product have following features : 1. 2. 3. 4. 5. 6. It handle the customer interest. It also provides the fun game activities. Free of cost entertaintment. Free to select game i.e PacMan It also provide the users the facility to give feedback. User can play it any time using command prompt.

Security level :
Administrator provides the proper facility for users authentification and handle the login system.Thus, this apply the different types of security policies over the system to increase the robustness of the system.

Operating Environment:
On the following environment it will work more smoothly:1) 2) 3) 4) Pentium III processor , 256MB Ram, 20 GB Hard disk, Printer Windows environment MYSQL database system (optional) Java jdk5.0

Design and Implementation Constraints


It will needed windows environment. It will work on linux platform also. The 128MB minimum RAM is required for the system to use. It will only work on single pc not on the network but with different byte code.

System Features
This section illustrates the functional features of the system. It gives the total description about the system functionalities that are provided by the system.

Functional Requirements
* The main requirement is that JRE(JAVA RUNTIME ENVIRONMENT) with environment variables class path set.

Stimulus /Response Sequences


After compiling it using (javac) the option it show you the option to run it using applet viewer command which you wanted.

External Interface Requirements


User Interfaces:
The system should be highly user friendly so the user interface mut be Graphical user interface. Every option should in the menus of the GUI.

Hardware Interfaces:
It is not applicable yet.

10

Software Interfaces:
1 2 3 4 Software component Java jdk1.5 Databases- Oracle 9i (optional) Windows Xp Sp2 Any text Editor

Software Quality Attributes:


1 2 3 4 5 Highly user friendly- GUI High security system reliable, robustness is the characterstics of the system. Easily learnable for the new user. Customer cant do any change to the project.

11

OBJECTIVES OF PROJECT:
There are some Objectives, which are Envisaged under the Project:Practicality: The system should be sable and can be operated with average intelligence. Efficiency: There should be balance amongst various factors like accuracy, comprehensiveness on one hand and response timeliness of the system on the other hand. Cost: It is desirable to aim for the system with a minimum cost subject to the condition that it must satisfy the entire requirement. Flexibility: The system should be modifiable depending on the changing needs of the employee or department. Such modifications should entail extensive reconstructing. It should also be portable to different computer systems. Security: This is very important aspect requiring rigorous designing of database including hardware reliability, fallback procedures and physical security of data. The development of the proposed system is done keeping in view the problems in the existing system. The proposed system will not only overcome the limitations of the present system but will also provide the following characteristics. The objective of the system would be: To reduce the time constraint involved. To centralize all the data needed. To provide fun game activites. To maintain the information about the users of the organization. To generate various reports as required.

12

Technologies Used:
1. a. b. 2. a. b. 3. a. Model: Core Java Applet Design HTML JavaScript Database(optional) mysql

13

SYSTEM REQUIREMENTS:
Problem Recognition:
A problem is well defined very rarely. It corps out with a vague feeling of some statements that lead to vague conclusions. So the first task is to get more crucial information by interviewing and meeting concerned people. It clarifies how the problem is felt, how often it occurs, how it affects the business and which departments are suffering with this. This phase consists of the following tasks. Problem Definition And Initial Investigation This was a preliminary investigation done with a view to have a feel of the working of the proposed system. This phase has been identified the end-user directly involved in the system who were the managers, assistant officer and database administrator, and the development department. By understanding the working of database, its flow and also after conducting meetings and interviews with the concerned persons of the department, a clear idea about the working was obtained. A flexible approach is adapted towards people who are interviewed. Short hand written notes are prepared based on the response of the employees. The interviews are preferably conducted at the work place of the person being interviewed. Detailed investigation is done in order to define the scope of the problem .The interview is concluded with a quick resume of the ground covered during the interview .The Questionnaire technique is combined with interviews to get the best result. Proper care has been taken in the design of such questionnaires so that the persons answering these questions dose not feel hesitant. An explanatory note that serves to gain cooperation and avoid misunderstanding by setting out the purpose of the exercise clearly accomplishes each questionnaire.

14

Observation technique is also used for fact finding. The work described at the time of interview is observed personally ads it reduces the chances of misunderstanding and omissions. Some important things observed are like the flow of information through the system and important data transactions, the data being maintained and the frequency of their updating. By the end of this phase, idea as to how the information enters the system, how it is stored, how it is processed, how information changes affects the working of the system and finally the output format required by the end-user was collected. All the information generated from this phase acted as an input to the next phase.

Function to be Provided:
This phase provides the overall requirement for the system what is to be done. Input for this phase is the information collected through several data collecting schemes such as survey, cross-questioning-answering etc and the raw data obtained which is not properly ordered and not in the precise manner. So here this raw data is converted into useful information written in precise manner and thus output is a formal document. After collecting all the information and requirements, they were verified from the concerned persons by presenting a diagrammatic version of the proposed system. The points missing were added to the system specifications for the desired system. So this final document provides the system requirement specifications for the desired system. It helps in reducing the total development cost and also establishes the various points for validation and verification.

15

Introduction to J2EE Framework:


Java is an object-oriented programming language with a built-in application programming interface (API) that can handle graphics and user interfaces and that can be used to create applications or applets. Because of its rich set of API's, similar to Macintosh and Windows, and its platform independence, Java can also be thought of as a platform in itself. Java also has standard libraries for doing mathematics. Much of the syntax of Java is the same as C and C++. One major difference is that Java does not have pointers. However, the biggest difference is that you must write object oriented code in Java. Procedural pieces of code can only be embedded in objects. In the following we assume that the reader has some familiarity with a programming language. In particular, some familiarity with the syntax of C/C++ is useful. In Java we distinguish between applications, which are programs that perform the same functions as those written in other programming languages, and applets, which are programs that can be embedded in a Web page and accessed over the Internet. Our initial focus will be on writing applications. When a program is compiled, a byte code is produced that can be read and executed by any platform that can run Java. Java is platform independent. A Java program can run equally well on any architecture that has a Java enabled browser. With the release of Netscape Navigator 2.0 that includes Windows 95, Windows NT , Sun Solaris, Sun OS 4.1.3, SGI IRIX, OSF/1, HP-UX with more to come. Java isn't just for web sites. Java is a programming language that lets you do almost anything you can do with a traditional programming language like Fortran or C++. However Java has learned from the mistakes of its predecessors. It is considerably cleaner and easier to use than those languages.

16

Advantages of Java:
1) Simple: Java has the bare bones functionality needed to implement its rich feature set. It does not add lots of syntactic sugar or unnecessary features. 2) Object-Oriented: Almost everything in Java is either a class, a method or an object. Only the most basic primitive operations and data types (int, for, while, etc.) are at a sub-object level. 3) Platform Independent : Java programs are compiled to a byte code format that can be read and run by interpreters on many platforms including Windows 95, Windows NT, and Solaris 2.3 and later. 4) Safe: Java code can be executed in an environment that prohibits it from introducing viruses, deleting or modifying files, or otherwise performing data destroying and computer crashing operations. 5) High Performance: Java can be compiled on the fly with a Just-In-Time compiler (JIT) to code that rivals C++ in speed. 6) Multi-Threaded: Java is inherently multi-threaded. A single Java program can have many different things processing independently and continuously.

17

OOP Principles:
The object oriented programming languages provide mechanisms that help you implement the object oriented model.

1) Data Hiding and Encapsulation: One of the important object-oriented techniques is hiding the data within the class and making it available only through the methods. This technique is known as encapsulation because it seals the data (and internal methods) safely inside the "capsule" of the class, where it can be accessed only by trusted users (i.e., by the methods of the class). The most important reason is to hide the internal implementation details of your class. If you prevent programmers from relying on those details, you can safely modify the implementation without worrying that you will break existing code that uses the class. Another reason for encapsulation is to protect your class against accidental or willful stupidity. A class often contains a number of interdependent fields that must be in a consistent state. If you allow a programmer (including yourself) to manipulate those fields directly, he may change one field without changing important related fields, thus leaving the class in an inconsistent state. If, instead, he has to call a method to change the field, that method can be sure to do everything necessary to keep the state consistent. Similarly, if a class defines certain methods for internal use only, hiding these methods prevents users of the class from calling them. When all the data for a class is hidden, the methods define the only possible operations that can be performed on objects of that class. Once you have carefully tested and debugged your methods, you can be confident that the class will work as expected. On the other hand, if all the fields of the class can be

18

directly manipulated, the number of possibilities you have to test becomes unmanageable. There are other reasons to hide fields and methods of a class, as well: Internal fields and methods that are visible outside the class just clutter up the API. Keeping visible fields to a minimum keeps your class tidy and therefore easier to use and understand. If a field or method is visible to the users of your class, you have to document it. Save yourself time and effort by hiding it instead.

2) Inheritance: Inheritance is the process by which one object acquires the properties of another object. This is important because it supports the concept of hierarchical classification. Most knowledge is made by hierarchical classification. Inheritance is a compile-time mechanism in Java that allows you to extend a class (called the base class or super class) with another class (called the derived class or subclass). In Java, inheritance is used for two purposes: Class inheritance - create a new class as an extension of another class, primarily for the purpose of code reuse. That is, the derived class inherits the methods of the base class. Interface inheritance - create a new class to implement the methods defined as part of an interface for the purpose of sub typing. That is a class that implements an interface conforms to the interface. In Java, unlike C++, these two types of inheritance are made distinct by using different language syntax. For class inheritance, Java uses the keyword extends and for interface inheritance Java uses the keyword implements.

19

For example: class Base { private int x; public int f() { ... } protected int g() { ... } // NOTE: protected access means visible to subclass only } class Derived extends Base { private int y; public void h() { y = g(); ... } } In Java, unlike C++, only single class inheritance is supported. I.e., for a given class, there is only one super class. 3) Polymorphism Polymorphism is the capability of an action or method to do different things based on the object that it is acting upon. This is the third basic principle of object oriented programming. Two types of polymorphism: Overloading and Overriding. Dynamic method binding.

20

SOFTWARE REQUIREMENT SPECIFICATION (SRS)


System Analysis: System Analysis is the process of studying the business processors and procedures, generally referred to as business system, to see how they can operate and whether improvement is needed. This may involve examining data moments and storage, machines and technology used in the system., programs that control the machines, people providing inputs, doing the processing and receiving the outputs.

1) Investigation Phase: The Investigation Phase is also known as the FactFinding stage or the analysis of the current system. This is detailed study conducted with the purpose of wanting to fully understand the existing system and to identify the basic information requirement. 2) Detailed Study of the Existing System: This phase provides the overall requirement for the system what is to be done. Input for this phase is the information collected through several data collecting schemes such as survey, cross-questioning-answering etc and the raw data obtained which is not properly ordered and not in the precise manner. So here this raw data is converted into useful information written in precise manner and thus output is a formal document. After collecting all the information and requirements, they were verified from the concerned persons by presenting a diagrammatic version of the proposed system. The points missing were added to the system specifications for the desired system. So this final document provides the system requirement specifications for the desired system. It helps in reducing the total development cost and also establishes the various points for validation and verification.

21

Software Requirement Specification: Software Requirement Specification is produced at the culmination of the analysis task. The function and performance allocated to software as part of system engineering are refined by establishing a complete information description, a detailed functional description, a representation of system behavior, and indication of performance requirement and design constraints appropriate validation criteria, and other information pertinent to requirement. The introduction to SRS specification states the goals and objectives of the software, describing it in the context of the computer based system. The Information Description provides a detailed description of the problem that the software must solve. Information content, flow and structure are documented. A description of each function required to solve the problem is presented in the functional description. Validation Criteria is the mos important and ironically the most often neglected section of the software requirement specification. SRS can be used for the different purposes. Here are the major uses: 1) Statement of User Need: Since end users are the ones who are finally going to use the system, their requirements need to be identified. This involves questioning the end users what their expectations were. The main requirement of the end user is that the system should be easy to use and take less time. In addition to these another important factor was to eliminate the need for database conversion and migration that had to be carried out presently. After conducting interviews with the users a document called the software requirement specification was created. This is the most important document that forms the basis for system development. It should be consistent, complete, unambiguous, traceable and inter-related.

22

This document has the following components:


Functional Requirements: The functional requirements specify relationship between the inputs and outputs. All the operations to be performed on the input data to obtain output are to be specified. This includes specifying the validity checks on the input and output data, parameters affected by the operations and the other operations, which must be used to transform the inputs into outputs. Functional requirements specify the behavior of the system for valid input and outputs. Statements of requirements for implementation: This section includes performance of the product that are set by user interaction and studying the existing system of the organization. These are stated in complete measurable terms, so that they can be verified during system evaluation phase. Some of the performance requirements are stated below. User Friendly: the system produced is user friendly, understandable and easy to use so that the users of the system can easily learn to use the system. For this the system is made menu-driven with well-documented programs. Time Element (response and processing time): the response time of the system is very less and takes less time to execute queries and triggers. Maximum Throughput: the system gives maximum throughput with relevant output Robustness: the system will be able to handle undesirable situations and errors encountered at various levels e.g. if the user supplies invalid input for processing, the system gracefully halts, displaying a message to the user indicating the cause of the error and prompting him it enter the correct input. Flexibility: the system is flexible in nature so that likely changes and alterations can easily be made.

23

SYSTEM DESIGN
After the analysis phase we have with us the details of the existing system and the requirements of the user for the new system. This phase diverts focus from the problem domain to the solution domain. It acts as a bridge between the requirement phase and its solution. The design phase focuses on the detailed implementation of the system recommended in the feasibility study. Emphasis is on translating performance specifications into design specifications.

The External Design


External design consists of conceiving, planning out and specifying the externally observable characteristics of the software product. These characteristics include user displays or user interface forms and the report formats, external data sources and the functional characteristics, performance requirements etc. External design begins during the analysis phase and continues into the design phase.

Design objectives:The primary objective of the design is to deliver the requirements as specified in the feasibility report. These are the some of the objectives, which I kept in mind. 1) Practicality: The system is quite stable and can be operated by the people with average intelligence. 2) Efficiency: I tried to involve accuracy, timeliness and comprehensiveness of the system output.

24

3) Cost: It is desirable to aim for the system with a minimum cost subject to the condition that it must satisfy the entire requirement. 4) Flexibility: I have tried that the system should be modifiable depending on the changing needs of the user. Such modifications should entail extensive reconstructing or recreation of software. It should also be portable to different computer systems. 5)Security: This is very important aspect which I followed in this designing phase and tried to covers the areas of hardware reliability, fallback procedures, and physical security of data.

Characteristics of a Well Defined System


In design an efficient and effective system is of great importance to consider the human factor and equipment that these will require to use. System analyst must evaluate the capabilities and limitations of the personal and corresponding factors of the equipment itself.

The characteristics associated with effective system operations are: 1) Accessibility 1) Decision Making Ability 3) Economy 4) Flexibility 5) Reliability 6) Simplicity

25

SYSTEM IMPLEMENTATION
INTRODUCTION
Software testing is used in association with verification and validation (V&V). Verification is the checking of or testing of items, including software, for conformance and consistency with an associated specification. Software testing is just one kind of verification, which also uses techniques such as reviews, inspections, and walkthroughs. Validation is the process of checking what has been specified is what the user actually wanted. Verification: Have we built the software right? (i.e. does it match the specification). Validation: Have we built the right software? (i.e. Is this what the customer wants?) Implementation is the stage in the project where the theoretical design is turned into the working system and is giving confidence to the new system for the users i.e. will work efficiently and effectively. It involves careful planning, investigation of the current system and its constraints on implementation, design of method to achieve the change over, an evaluation, of change over methods. A part from planning major task of preparing the implementation is education of users. The more complex system is implemented, the more involved will be the system analysis and design effort required just for implementation. An implementation coordinating committee based on policies of individual organization has been appointed. The implementation process begins with preparing a plan for the implementation for the system. According to this plan, the activities are to be carried out, discussions may regarding the equipment has to be acquired to implement the new system. Implementation is the final and important phase. The most critical stage is in achieving a successful new system and in giving the users confidence that the

26

new system will work and be effective. The system can be implemented only after thorough testing is done and if it found to working according to the specification. This method also offers the greatest security since the old system can take over if the errors are found or inability to handle certain types of transaction while using the new system. At the beginning of the development phase a preliminary implementation plan is created to schedule and manage the many different activities that must be integrated into plan. The implementation plan is updated throughout the development phase, culminating in a change over plan for the operation phase. The major elements of implementation plan are test plan, training plan, equipment installation plan, and a conversion plan.

Types Of Implementation
There are three types of implementation: Implementation of a computer system to replace a manual system. Implementation of a new computer system to replace an existing system. Implementation of a modified application to replace an existing one, using the same computer. Successful implementation may not guarantee improvement in the organization using the new system, but improper installation will prevent it. It has been observed that even the best system cannot show good result if the analysts managing the implementation do not attend to every important detail. This is an area where the systems analysts need to work with utmost care.

27

IMPLEMENTATION TOOLS:
Training personnel Conversion Procedures Post-implementation review

Training of Personnel involved with system


Even well designed system can succeed or fail because of the way they are operated and used. Therefore, the quality of training received by the personal involved with the system in various capacities helps or hinders and may even prevent the successful implementation of management information system.

Those who are directly or indirectly related with the system development work must know in detail what must know in detail what their roles will be, how they can make efficient use of the system and what the system will or will not do for them. Both system operators and users need training.

28

System Operators Training


Running of the system successfully depend on the personnel working in the Computer Centre. They are Responsible for providing the necessary support. Their training must ensure that they are able to handle all possible operations, both routine and extra-ordinary in nature. If the system calls for the installation of new equipment, such as new computer system, special terminals or different data entry machines, the operators training should include such fundamentals as how to turn the equipment on and use it, how to power off and a knowledge of what constitutes normal operations. The operators should also be trained on different type of malfunctioning, how to recognize them and what steps should also be taken whenever they arise.

User Training
User may be trained on use equipment, particularly in the case where, e.g. a micro computer is in use and individual involved is both operator and user. In such cases, user must be given training on how to operate and user. In such cases, user must be given training on how to operator the system also. Questions that may be trivial to the analyst, such as how to turn on a terminal, how to insert a diskette into a micro-computer or when it is safe to turn off equipment with out danger of data loss are significant problems to new users who are not familiar.

29

Conversion Methods
A conversion is the process of changing from the old system to the new one. It must be properly planned and executed. Four methods are common in use. They are Parallel Systems, Direct Conversion, Pilot System and Phase In method. Each method should be considered in the light of the opportunities that it offers and problems that it may create. In general, system conversion should be accomplished in shortest possible time. Long conversion periods create problems for all persons involved including both analysts and users.

Parallel systems:
The most secure method of converting from an old to new system is to run both systems in parallel. This method is safest one because it ensures that in case of any problem in using new system, the organization can still fall back to the old system without the loss of time and money. The disadvantages of parallel systems approach are: It doubles operating costs.The new system may not get fair trial.

30

The coding of project-GAMING PACMAN IS:


import java.awt.*; import java.applet.Applet; /*<applet code="PacMan.class" height="400" width="400"></applet>*/

public class PacMan extends Applet implements Runnable { Dimension d; Font Font largefont = new Font("Helvetica", Font.BOLD, 24); smallfont = new Font("Helvetica", Font.BOLD, 14);

FontMetrics Graphics Image Thread goff;

fmsmall, fmlarge;

ii; thethread;

MediaTracker thetracker = null; Color int int Color dotcolor=new Color(192,192,0); bigdotcolor=192; dbigdotcolor=-2; mazecolor;

31

boolean

ingame=false;

public void PlayDemo() { CheckScared(); MoveGhosts(); ShowIntroScreen(); }

public void Death() { int k;

deathcounter--; k=(deathcounter&15)/4; switch(k) { case 0: goff.drawImage(pacman4up,pacmanx+1,pacmany+1,this); break; case 1:

32

goff.drawImage(pacman4right,pacmanx+1,pacmany+1,this); break; case 2: goff.drawImage(pacman4down,pacmanx+1,pacmany+1,this); break; default: goff.drawImage(pacman4left,pacmanx+1,pacmany+1,this); } if (deathcounter==0) { pacsleft--; if (pacsleft==0) ingame=false; LevelContinue(); } }

public void MoveGhosts() { short i; int pos; int count;

33

for (i=0; i<nrofghosts; i++) { if (ghostx[i]%blocksize==0 && ghosty[i]%blocksize==0) { pos=ghostx[i]/blocksize+nrofblocks*(int)(ghosty[i]/blocksize);

count=0; if ((screendata[pos]&1)==0 && ghostdx[i]!=1) { dx[count]=-1; dy[count]=0; count++; } if ((screendata[pos]&2)==0 && ghostdy[i]!=1) { dx[count]=0; dy[count]=-1; count++; } if ((screendata[pos]&4)==0 && ghostdx[i]!=-1) { dx[count]=1;

34

dy[count]=0; count++; } if ((screendata[pos]&8)==0 && ghostdy[i]!=-1) { dx[count]=0; dy[count]=1; count++; } if (count==0) { if ((screendata[pos]&15)==15) { ghostdx[i]=0; ghostdy[i]=0; } else { ghostdx[i]=-ghostdx[i]; ghostdy[i]=-ghostdy[i]; } } else

35

{ count=(int)(Math.random()*count); if (count>3) count=3; ghostdx[i]=dx[count]; ghostdy[i]=dy[count]; } } ghostx[i]=ghostx[i]+(ghostdx[i]*ghostspeed[i]); ghosty[i]=ghosty[i]+(ghostdy[i]*ghostspeed[i]); DrawGhost(ghostx[i]+1,ghosty[i]+1);

if (pacmanx>(ghostx[i]-12) && pacmanx<(ghostx[i]+12) && pacmany>(ghosty[i]-12) && pacmany<(ghosty[i]+12) && ingame) { if (scared) { score+=10; ghostx[i]=7*blocksize; ghosty[i]=7*blocksize; } else { dying=true;

36

deathcounter=64; } } } }

public void DrawGhost(int x, int y) { if (ghostanimpos==0 && !scared) { goff.drawImage(ghost1,x,y,this); } else if (ghostanimpos==1 && !scared) { goff.drawImage(ghost2,x,y,this); } else if (ghostanimpos==0 && scared) { goff.drawImage(ghostscared1,x,y,this); } else if (ghostanimpos==1 && scared) {

37

goff.drawImage(ghostscared2,x,y,this); } }

public void MovePacMan() { int pos;

short ch;

if (reqdx==-pacmandx && reqdy==-pacmandy) { pacmandx=reqdx; pacmandy=reqdy; viewdx=pacmandx; viewdy=pacmandy; } if (pacmanx%blocksize==0 && pacmany%blocksize==0) { pos=pacmanx/blocksize+nrofblocks*(int)(pacmany/blocksize); ch=screendata[pos]; if ((ch&16)!=0) {

38

screendata[pos]=(short)(ch&15); score++; } if ((ch&32)!=0) { scared=true; scaredcount=scaredtime; screendata[pos]=(short)(ch&15); score+=5; }

if (reqdx!=0 || reqdy!=0) { if (!( (reqdx==-1 && reqdy==0 && (ch&1)!=0) || (reqdx==1 && reqdy==0 && (ch&4)!=0) || (reqdx==0 && reqdy==-1 && (ch&2)!=0) || (reqdx==0 && reqdy==1 && (ch&8)!=0))) { pacmandx=reqdx; pacmandy=reqdy; viewdx=pacmandx; viewdy=pacmandy; }

39

if ( (pacmandx==-1 && pacmandy==0 && (ch&1)!=0) || (pacmandx==1 && pacmandy==0 && (ch&4)!=0) || (pacmandx==0 && pacmandy==-1 && (ch&2)!=0) || (pacmandx==0 && pacmandy==1 && (ch&8)!=0)) { pacmandx=0; pacmandy=0; } } pacmanx=pacmanx+pacmanspeed*pacmandx; pacmany=pacmany+pacmanspeed*pacmandy; }

public void DrawPacMan() { if (viewdx==-1) DrawPacManLeft(); else if (viewdx==1) DrawPacManRight();

40

else if (viewdy==-1) DrawPacManUp(); else DrawPacManDown(); }

public void DrawPacManUp() { switch(pacmananimpos) { case 1: goff.drawImage(pacman2up,pacmanx+1,pacmany+1,this); break; case 2: goff.drawImage(pacman3up,pacmanx+1,pacmany+1,this); break; case 3: goff.drawImage(pacman4up,pacmanx+1,pacmany+1,this); break; default: goff.drawImage(pacman1,pacmanx+1,pacmany+1,this); break; }

41

public void DrawPacManDown() { switch(pacmananimpos) { case 1: goff.drawImage(pacman2down,pacmanx+1,pacmany+1,this); break; case 2: goff.drawImage(pacman3down,pacmanx+1,pacmany+1,this); break; case 3: goff.drawImage(pacman4down,pacmanx+1,pacmany+1,this); break; default: goff.drawImage(pacman1,pacmanx+1,pacmany+1,this); break; } }

42

public void DrawPacManLeft() { switch(pacmananimpos) { case 1: goff.drawImage(pacman2left,pacmanx+1,pacmany+1,this); break; case 2: goff.drawImage(pacman3left,pacmanx+1,pacmany+1,this); break; case 3: goff.drawImage(pacman4left,pacmanx+1,pacmany+1,this); break; default: goff.drawImage(pacman1,pacmanx+1,pacmany+1,this); break; } }

public void DrawPacManRight() { switch(pacmananimpos)

43

{ case 1: goff.drawImage(pacman2right,pacmanx+1,pacmany+1,this); break; case 2: goff.drawImage(pacman3right,pacmanx+1,pacmany+1,this); break; case 3: goff.drawImage(pacman4right,pacmanx+1,pacmany+1,this); break; default: goff.drawImage(pacman1,pacmanx+1,pacmany+1,this); break; } }

public void DrawMaze() { short i=0; int x,y;

bigdotcolor=bigdotcolor+dbigdotcolor;

44

if (bigdotcolor<=64 || bigdotcolor>=192) dbigdotcolor=-dbigdotcolor;

for (y=0; y<scrsize; y+=blocksize) { for (x=0; x<scrsize; x+=blocksize) { goff.setColor(mazecolor); if ((screendata[i]&1)!=0) { goff.drawLine(x,y,x,y+blocksize-1); } if ((screendata[i]&2)!=0) { goff.drawLine(x,y,x+blocksize-1,y); } if ((screendata[i]&4)!=0) { goff.drawLine(x+blocksize-1,y,x+blocksize-1,y+blocksize-1); } if ((screendata[i]&8)!=0) { goff.drawLine(x,y+blocksize-1,x+blocksize-1,y+blocksize-1);

45

} if ((screendata[i]&16)!=0) { goff.setColor(dotcolor); goff.fillRect(x+11,y+11,2,2); } if ((screendata[i]&32)!=0) { goff.setColor(new Color(224,224-bigdotcolor,bigdotcolor)); goff.fillRect(x+8,y+8,8,8); } i++; } } }

public void ShowIntroScreen() { String s;

goff.setFont(largefont);

goff.setColor(new Color(0,32,48));

46

goff.fillRect(16, scrsize/2 - 40, scrsize-32,80); goff.setColor(Color.white); goff.drawRect(16, scrsize/2 - 40, scrsize-32,80);

if (showtitle) { s="Java PacMan"; scared=false;

goff.setColor(Color.white); goff.drawString(s,(scrsize-fmlarge.stringWidth(s)) / 2 +2, scrsize/2 - 20 +2); goff.setColor(new Color(96,128,255)); goff.drawString(s,(scrsize-fmlarge.stringWidth(s)) / 2, scrsize/2 - 20);

s="Sahil Singla"; goff.setFont(smallfont); goff.setColor(new Color(255,160,64)); goff.drawString(s,(scrsize-fmsmall.stringWidth(s))/2,scrsize/2 + 10);

s="GGDSD"; goff.setColor(new Color(255,160,64)); goff.drawString(s,(scrsize-fmsmall.stringWidth(s))/2,scrsize/2 + 30); }

47

else { goff.setFont(smallfont); goff.setColor(new Color(96,128,255)); s="'S' to start game"; goff.drawString(s,(scrsize-fmsmall.stringWidth(s))/2,scrsize/2 - 10); goff.setColor(new Color(255,160,64)); s="Use cursor keys to move"; goff.drawString(s,(scrsize-fmsmall.stringWidth(s))/2,scrsize/2 + 20); scared=true; } count--; if (count<=0) { count=screendelay; showtitle=!showtitle; } }

public void DrawScore() { int i; String s;

goff.setFont(smallfont);

48

goff.setColor(new Color(96,128,255)); s="Score: "+score; goff.drawString(s,scrsize/2+96,scrsize+16); for (i=0; i<pacsleft; i++) { goff.drawImage(pacman3left,i*28+8,scrsize+1,this); } }

public void CheckScared() { scaredcount--; if (scaredcount<=0) scared=false;

if (scared && scaredcount>=30) mazecolor=new Color(192,32,255); else mazecolor=new Color(32,192,255);

if (scared) {

49

screendata[7*nrofblocks+6]=11; screendata[7*nrofblocks+8]=14; } else { screendata[7*nrofblocks+6]=10; screendata[7*nrofblocks+8]=10; } }

public void CheckMaze() { short i=0; boolean finished=true;

while (i<nrofblocks*nrofblocks && finished) { if ((screendata[i]&48)!=0) finished=false; i++; } if (finished)

50

{ score+=50; DrawScore(); try { Thread.sleep(3000); } catch (InterruptedException e) { } if (nrofghosts < maxghosts) nrofghosts++; if (currentspeed<maxspeed) currentspeed++; scaredtime=scaredtime-20; if (scaredtime<minscaredtime) scaredtime=minscaredtime; LevelInit(); } }

public void run()

51

{ long starttime; Graphics g;

Thread.currentThread().setPriority(Thread.MAX_PRIORITY); g=getGraphics();

while(true) { starttime=System.currentTimeMillis(); try { paint(g); starttime += 40; Thread.sleep(Math.max(0, starttime-System.currentTimeMillis())); } catch (InterruptedException e) { break; } } }

52

public void start() { if (thethread == null) { thethread = new Thread(this); thethread.start(); } }

public void stop() { if (thethread != null) { thethread.stop(); thethread = null; } } }

53

SCREEN LAYOUT:

54

55

56

REFRENCES:
Book: Programming with java Author: E.Balagurusamy www.wikkipedia.com www.cpprefrence.com

Você também pode gostar