880 likes | 1.03k Views
Java Programming. Using Greenfoot to program computer games. Object-oriented programming. Java programs have interacting objects Each object has data (fields) and behavior (functions ) The class describes the data and behavior that all objects of that class have
E N D
Java Programming Using Greenfoot to program computer games
Object-oriented programming • Java programs have interacting objects • Each object has data (fields) and behavior (functions) • The class describes the data and behavior that all objects of that class have • It classifies the objects • It also creates the objects • Object-oriented also allows for inheritance • One class inherits object fields and functions from another class
Goals of OO programming • Spread out responsibility • Objects should do what you expect them to do • No one object does everything • Make reusable classes • Minimize the effect of changes • Make it easier to create new things out of classes that have been tested • Objects should be responsible for their data • Protect their data
Objects and Classes • Classes define what objects know and can do • There is one Balloon class • Objects do the action • There can be many objects of the same class • There are many balloon objects Objects Classes
Worlds and Actors • Greenfoot has two main classes • World • Place to hold and display actors • Has a width and height and cell size • Of type integer (int) • Has a background image • Actor • Actors know how to act • Actors have a x and y location in the world
Types in Java • There are two main types in Java • Primitive types • int, double, boolean, float, short, long • Object types • An object of a class like a balloon object, a bomb object, a counter object, a string (sequence of characters) etc • Primitive types • 3 // integer (int) • -232 // integer (int) • 3.2 // double • -562.232 // double • true // boolean • false // boolean
Constructors • Used to initialize the data for an object • Like the width, height, and cell size for a new world • A class can have more than one constructor • As long as they take different parameters (passed values)
functions • Provide behavior for objects • Balloons can act and pop • public is the visibility • Who can see and execute this function • void is the return type • Nothing is returned from the function • The () means that the functions take no values
The Java Class Structure import package.class; // as needed public class Nameextends OtherName { // fields – the data for each object // constructors – initialize the fields // functions – behavior for the objects // optional main function for testing }
Packages in Java • Java has a huge number of classes in it • Related classes are grouped into packages • java.lang – the essential classes • java.io – the classes for input and output • java.awt – some classes for doing graphics and user interfaces • java.util – classes that can hold a collection of objects
Blocks in Java • The ‘{‘ and ‘}’ come in pairs • Each pair defines a block • A class is defined in a block public class Balloon extends Actor { // starts the class } // ends the class • There is a block of code that defines a function as well • Inside the class block
Statements in Java • Do some action • Like setting the location • Or playing a sound • End in ‘;’ • Are inside of function blocks • Indented to show that they are in the block
Keywords • function • Compile • Class • Comments • myWorld
Learning ObjectivesHello World program and Greenfoot interface All • Identify different parts of the Greenfoot interface • Set a background to the world • Know how to add comments • Know how to compile a program and test for errors • Create a simple “hello world” program Most • Identify the difference between a class and function Some • Test and refine your program
Hello World Click on choose scenario and open “my first program” A scenario is used in Greenfoot to describe a game program) Save the “my first program” scenario folder to your documents from the x-drive World – is the stage of your game myWorld class – contains code to set the stage i.e. what actors to display at the start of the game Actor – is a sprite in the world. When you add a actor it creates a actor class and you add code to control the events and actions for that actor. A Class contains functions functionis used to perform a set of instructions / blocks of code for a specific purpose You can write your own functions or use functions that are part of Greenfoot/JAVA classes.
Task: Label different parts of this interface. Label the stage, world class, actor classes, compile Btn & Run/Pause Btn
myWorld //Create a new world with 8x8 cells and with a cell size of 60x60 pixels public myWorld() { super(800, 400, 1); setBackground("cell.jpg"); } Task: Right click on myWorld and click on OPEN EDITOR. Change the background image to another image called space.png and click on COMPILE If the code is has no errors … at the bottom of the screen it will say “No syntax errors”
Adding Comments //Create a new world with 800 x 400 cells and //with a cell size of 1x1 pixels
First Program Task: Right click on myWorld and click on OPEN EDITOR. Add the following code in red in the myWorldfunction: public myWorld() { //Create a new world with 8x8 cells and //with a cell size of 60x60 pixels super(800, 400, 1); setBackground("space.png"); //Display Hello world in system printout System.out.println("Hello world"); } Task: Change the println output. You can use numbers and text.
Learning ObjectivesData types, variables & constants All • Identify at least 2 data types used in a program • Know what a variable is used for • Know what a constant is • Create a program that uses at least one variable Most • Know about the scope of variables different variables in a program Some • Test and refine your program
Data types • Variables can hold data with different data types i.e. numbers and text • A number is int and text is string Complete the next task to find out about different data types you can use in a program
Variables • You will be using a range of variables in your game i.e. score, levels, lives, power, number of items, text etc. • A variable is used to hold data and you can use this stored data for a number of reasons: • display the data • change the data • check the data TRY this “Hello world” is datatype String myText is the name of the variable 1) You have to declare the variable at the top of the class: private String myText; 2) Then add this code to myWorld() function You have to assign a value to the variable: myText = “Hello world”; 3) Display mytext System.out.println(myText); Task: 1) Declare another variable called myText2 2) Assign a value “Goodbye world” 3) Display mytext2
Scope of variables • Variable can be either public or private – this defines the scope of a variable • public variables can be used and changed at anytime from other classes. • private variables can only be used and changed with in a single class – you will learn about functions later • Local variable is used in a functionand you don’t need to use public or private. It only can be used and changed in a single function • Global variables last for the whole duration of the entire program. Different functions in different classes can be used to change the variable. A global variable is used for score, lives etc.
int variables and calculation Try the following code: //add this variable at the top of the class private int lives; lives = 3; System.out.println(lives); Next Try: lives = 3*2+12; Task Try your own calculations and check that the program works NB use / for divide
Constants A constant in a program is a value that always stays the same static final int levels = 3;
Learning ObjectivesIf statements All • Know what a IF statement is used for • Know what a functionis used for Most • Recognise different types of functions Some • Test and refine your program
Using a simple IF statement to make decisions Try this: Add to myWorld() //declaring a variable in a functionyou don’t need private int x= 5; int y=8; if(expression) { System.out.println(“True”); } else { System.out.println(“False”); } Task: Using the following expressions in the table, use this program to workout if the expression is true or false if(expression) { statements; } else if(expression) { statements; } else { statements; }
Another IF statement Task: Try this program…add to myWorld class int lives = 3; if(lives >0) { System.out.println(“You have lives”); } else { System.out.println(“Game Over”); } Task: Change lives to 0 and test the program
Another IF statement – nested if Task: Try this program…add to myWorld class int level = 1; if(level = 1) { System.out.println(“Level 1”); } else if(level = 2) { System.out.println(“Level 2”); { else { System.out.println(“Game Over”); } There are 3 errors in this code!!! Can you spot them…have a go!!! Task 1: Change level variable to 2 and test the program Task 2: Change level variable to 3 and test the program
functions functions are blocks of code that can be used and reused at anytime in a program. A functionis a block of code that will perform a set of specific instructions and/or return a value A booleanfunctionreturns true or false public booleanfoundLeaf() { if(lives >0) { return true; } else { return false; } } A void functionis a set of instructions only public void act() { move(); } A intfunctionreturns a number public int lives() { return lives = 3; } Task: What functionhave you been adding code to in the myWorld class?
Final Program lives = 0; System.out.println(lives); if(lives >0) { System.out.println("You still have lives"); } else { System.out.println("Game Over"); int level = 1; if(level == 1) { System.out.println(“Level 1”); } else if(level = =2) { System.out.println(“Level 2”); } else { System.out.println(“Game Over”); } } public class myWorld extends World { private String myText; private int lives; public myWorld() { /** * Create a new world with 8x8 cells and * with a cell size of 60x60 pixels */ super(8, 8, 60); setBackground("space.jpg"); myText= "Hello world"; System.out.println(myText);
Learning ObjectivesActors & movement All • Know how to add a new actor and use a suitable image • Know about x and y coordinates on the stage • Know how to use code to add a actor to the stage/world • Use move(), setRotation(degrees) & turn() functionto get the spaceship to move around the world Most • Use a range of functions to move objects around the world Some • Test and refine the program
Add a new Actor - spaceship Task • Right click on Actor and add new subclass • Name your actor “spaceship” • Import from file and find the spaceship.png image • Right click on the spaceship actor and select new spaceship() and place it on the stage.
Adding Actors to the stage Initialising a new object in myWorld class: spaceship spaceship1 = new spaceship(); addObject (spaceship1, 300, 100); 4, 8 are the coordinates on the stage Task • Add the spaceship to the centre of the stage • Add one asteroid to the stage using this code
Adding the spaceship to the stage: In myWorld class: { super(800, 400, 1); setBackground("space.png"); spaceship spaceship1 = new spaceship(); addObject (spaceship1, 300, 100); }
setRotation(degrees) function • North is setRotation(270) • South is setRotation(90) • East is setRotation(0) • West is setRotation(180) Task Practice moving the spaceship in different directions
Actors and Movement To move and turn an actor you can use a number of functions in greenfoot that have already been written for you to use. Task: Right click on the spaceship and OPEN EDITOR Add the code in red: public void act() { move(30); setRotation(90); move(30); setRotation(90); } Task 1) What does it do? 2) Modify the program and try changing the parameters and adding more instructions to get the spaceship to move around the stage
Using the turn() function In your program – instead of setRotation() use: move(30); turn(6); See the Greenfoot Class Documentation to see other actor functions that you can use in your program
When a program freezes • Go to control>Show Debugger • Click on terminate program
Adding asteroids – Random positions public void randomAsteroids(inthowMany) { for(inti=0; i<howMany; i++) { Asteroid myAsteroid= new Asteroid(); int x = Greenfoot.getRandomNumber(getWidth()); int y = Greenfoot.getRandomNumber(getHeight()); addObject(myAsteroid, x, y); } }
Random Movements Change Location to random positions: public void move() { intrandomX = Greenfoot.getRandomNumber(300); intrandomY = Greenfoot.getRandomNumber(300); setLocation(randomX, randomY); } In the act() functioncall the move function: move(); Task: Try using the getRandomNumber() functionto change the spaceship's location to random positions:
Loops/Iterations • While loop – this will continue until a condition is met Try adding this to the act() function inti = 0; while (i < 4){ setLocation(300, 300); Greenfoot.delay(5); setLocation(100,100); Greenfoot.delay(5); setLocation(600, 100); Greenfoot.delay(5); } i++; System.out.println(i); Task • Why does this program not work?? Use the system.out.println to see what is happening to the variable - What is happening to the variable? • Improve the program while (condition) { statement; Statement; }
For Loop – Another way to loop a set of instructions inthowMany = 4; for(inti=0; i<howMany; i++) { setLocation(300, 300); Greenfoot.delay(5); setLocation(100,100); Greenfoot.delay(5); setLocation(600, 100); Greenfoot.delay(5); }
Learning ObjectivesActors & movement All • Know how to add a new actor and use a suitable image • Know how to add the actor to the stage at the start of a game • Changing the location of a actor using setLocation(x,y) Most • usegetWidth() getHeight() functions to test for stage boundaries • Use Greenfoot.getRandomNumber(8) functionto set random positions Some • Test and refine the hello world program
Add a new Actor - asteroid Task • Right click on Actor and add new subclass • Name your actor “asteroid” • Import from file and find the asteroid.png image • Right click on the asteroid actor and select new spaceship() and place it on the stage.
Changing Location using setLocation(x,y) Changing the location intx = getX(); int y = getY(); setLocation(x + 1, y); Task: Try moving the spaceship to different locations on the stage. Try get it move in a pattern/ shape formation Use Greenfoot.delay(5); to slow down the movement
Moving in different directions using setLocation(x,y) Because you have set the start positions of the actors in the myWorld class , within the actors class… you just need to code the next position in the act function Left to right int x = getX(); inty = getY(); if (x >= getWorld().getWidth()-1) { setLocation(0, y); } else { setLocation(x + 1, y); } Down to Up if (y>0) { setLocation(x, y + 1); } • Task • Try out this code in the asteroid class • Change the program so that the asteroid moves down to up on the stage • Then left to right.
Random Positions int x = Greenfoot.getRandomNumber(300); int y = Greenfoot.getRandomNumber(300);