Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

Java Help I need the image of that green ship (the player) to be able to move left and right using the arrow keys. I

Java Help

image text in transcribed

I need the image of that green ship (the player) to be able to move left and right using the arrow keys. I need to do this using KeyListener.

Also when the user lets go of the left or right arrow keys the ship will stop. The variable I use to denote the green ships x coordinate is "xPos".

Here is my code :

InvadersApplication class:

import javax.swing.*; import java.awt.*; import java.awt.event.*; public class InvadersApplication extends JFrame implements Runnable, KeyListener { //member data private static final Dimension WindowSize = new Dimension(600, 600); private static final int NUMALIENS = 30; private Sprite2D[] AliensArray = new Sprite2D[NUMALIENS]; private boolean isInitialised = false; //constructor public InvadersApplication() { //create and set up window this.setTitle("Space Invaders"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Dimension screensize = java.awt.Toolkit.getDefaultToolkit().getScreenSize(); int x = screensize.width / 2 - WindowSize.width / 2; int y = screensize.height / 2 - WindowSize.height / 2; setBounds(x, y, WindowSize.width, WindowSize.height); setVisible(true); for (int i = 0; i  

Sprite2D class:

import javax.swing.*; import java.awt.*; public class Sprite2D { //member data private double x,y; private final Image alienImage; private final Image player; private double xPos = 255; //this is the player ship's x coordinate //constructor public Sprite2D() { ImageIcon icon = new ImageIcon("alien_ship_1.png"); alienImage = icon.getImage(); ImageIcon icon2 = new ImageIcon("player_ship.png"); player = icon2.getImage(); x = Math.random()*600; y = Math.random()*300; } //public interface public void moveEnemy(){ x += 10*(Math.random()-Math.random()); y += 10*(Math.random()-Math.random()); } public void paint(Graphics g){ g.drawImage(alienImage, (int)x, (int)y, null); g.drawImage(player, (int)xPos , 550, null); } } 

Here are the images used:

image text in transcribed

image text in transcribed

Space Invaders

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

More Books

Students also viewed these Databases questions

Question

Provide examples of KPIs in Human Capital Management.

Answered: 1 week ago

Question

What are OLAP Cubes?

Answered: 1 week ago