So I'm creating a soundboard for my CS project using java. The soundboard consists of an 8 piece drum set that is supposed to play its set sound when clicked. I've set the area to be clicked but don't know how to implement sound that'll start when the set area is clicked.
// FinalProjectst.java
// AP Computer ScienceStudent Version
import java.awt.*;
import java.applet.*;
import java.awt.geom.Ellipse2D;
public class FinalProjectst extends Applet
{
Image picture;
Ellipse2D base, bT, snare, lT, rT, hh, lC, rC;
int numColor;
public void init()
{
picture = getImage(getDocumentBase(),"drumSet.jpg");
base = new Ellipse2D.Double (355, 415, 305, 240); //Bass
bT = new Ellipse2D.Double (715, 360, 325, 245); //Bottom Tom
snare = new Ellipse2D.Double ( 35, 410, 290, 200); //Snare
lT = new Ellipse2D.Double (283, 130, 185, 165); //Left Tom
rT = new Ellipse2D.Double (543, 120, 200, 175); //Right Tom
hh = new Ellipse2D.Double ( 0, 225, 250, 150); //High Hat
lC = new Ellipse2D.Double ( 10, 0, 305, 195); //Left Cymbal
rC = new Ellipse2D.Double (765, 0, 505, 275); //Right Cymbal
}
public boolean contains(Event e, int x, int y)
{
if(base.contains(x,y))
numColor = 1;
else if(bT.contains(x,y))
numColor = 2;
else if(snare.contains(x,y))
numColor = 3;
else if(lT.contains(x,y))
numColor = 4;
else if(rT.contains(x,y))
numColor = 5;
else if(hh.contains(x,y))
numColor = 6;
else if(lC.contains(x,y))
numColor = 7;
else if(rC.contains(x,y))
numColor = 8;
else
numColor = 9;
repaint();
return true;
}
public void paint(Graphics g)
{
g.drawImage(picture, 0, 0, this);
}
}
There are a lot of different ways to play a sound but for example you could do something like this:
public static void playSound(File soundfile) throws LineUnavailableException, UnsupportedAudioFileException, IOException{
AudioInputStream audioInputStream = null;
audioInputStream = AudioSystem.getAudioInputStream(soundfile);
Clip clip = AudioSystem.getClip();
clip.open(audioInputStream);
clip.start();
}
This code will play wav files without a problem and I think that it will also play other types of sound files, but I am not sure what sound types it will play and what sound types it will not.
I hope this help :)
EDIT:
As you can see there are a lot of exceptions that can be thrown from this code, so you probably want to handle them in an appropriate way.
Related
So I am trying to call an entity called Mothership with a texture. What should be happening is that the image appears where the player is (temporary place till it appears). Instead, no matter where I move it, it does not appear.
This dropbox link is to the whole game because it all links together.
https://www.dropbox.com/sh/kuvoxzjf00wa8jf/AAD-MaXXcnHMn4PtW-X_vHcUa?dl=0
I thought maybe it's because of Controller.java, not initialising it but I was getting errors. In the end, I want the mothership to be stationary and appear on the side that the player spawns on. The mothership will lose health from enemy bullets which I am working on at the moment.
But here are the bits that I have been focussing my attention to:
public void render(Graphics g) {
g.drawImage(tex.nmothership, (int) x, (int) y, null);
}
^This is in Mothership.java
public void init(){
requestFocus();
BufferedImageLoader loader = new BufferedImageLoader();
try {
spriteSheet = loader.loadImage("/spriteSheet.png");
background = loader.loadImage("/background.png");
}catch(IOException e) {
e.printStackTrace();
}
tex = new Textures(this);
c = new Controller(tex, this);
p = new Player(200, 200, tex, this, c);
menu = new Menu();
mothership = new Mothership(200, 200, tex);
ea = c.getEntityA();
eb = c.getEntityB();
this.addKeyListener(new KeyInput(this));
this.addMouseListener(new MouseInput());
c.createEnemy(enemy_count);
//e = error
}
^In Game.java (the main engine of the game)
private void getTextures() {
player = ss.grabImage(1, 1, 32, 32);
missile = ss.grabImage(2, 1, 32, 32);
enemy = ss.grabImage(3, 1, 32, 32);
emissile = ss.grabImage(4, 1, 32, 32);
nmothership = ss.grabImage(1, 1, 128, 128);
^In Textures.java - the grabImage is from Spritesheet.java
After some playing around I managed to get the "mothership" to spawn however it has come at the price of commenting out the mothership's physics mechanic. I will make another post about it if I am still having trouble.
This is my current code:
int doorCounter = 0;
void setup()
{
size(512, 348); //width and height of screen
doorCounter = (int)random(180,300);
}
void draw()
{
display();
doorCounter = doorCounter - 1; // Decrease count by 1
if (doorCounter <= 0)
{
fill(255);
rect(420, 190, 55, 100); //house door outline
rect(435, 210, 25, 25, 7); // house door window
ellipse(435, 255, 8, 8); // house door handle
doorCounter = (int)random(180,480);
}
}
void display()
{
fill(255);
rect(420, 190, 55, 100); //house door outline
fill(0,0,0); // fill the following polygons in black
rect(435, 210, 25, 25, 7); // house door window
ellipse(435, 255, 8, 8); // house door handle
}
However what this code does is just makes the object disappear for a fraction of a second and just makes it reappear instantly. How do I make it so that the object stays disappeared for 3-8 seconds on a random interval just like how the object disappears every 3-8 seconds given that its still on the screen?
P.s I don't know if what I'm trying to achieve makes sense so please feel free to question.
An idea is to use a timestamp and check the time elapsed from it, something like this:
int min_time = 3000; // in ms
int max_time = 8000; // in ms
int time_frame = (int)random(min_time, max_time);
int time_stamp = 0;
boolean show_door = true;
void setup()
{
size(512, 348); //width and height of screen
}
void draw()
{
background(200);
int time_passed = millis() - time_stamp;
if (time_passed < time_frame && show_door) {
display();
} else if (time_passed >= time_frame) {
time_stamp = millis();
time_frame = (int)random(min_time, max_time);
show_door = !show_door;
}
}
void display()
{
fill(255);
rect(420, 190, 55, 100); //house door outline
fill(0, 0, 0); // fill the following polygons in black
rect(435, 210, 25, 25, 7); // house door window
ellipse(435, 255, 8, 8); // house door handle
}
Please help me how to make this eye move or to make it blink using repaint, thread and implements runnable. I don't know where to place the right codes to make it work. Please help me guys! Thank you!
Here is the code:
import java.awt.*;
import java.applet.*;
public class Pucca extends Applet {
public Pucca(){
setSize(700, 700); }
//paint method
public void paint(Graphics g){
Color white = new Color(255,255,255);
g.setColor(white);
g.fillOval(600, 100, 125, 125); //left white fill eye
g.setColor(Color.BLACK);
g.drawOval(600, 100, 125, 125); // left big black line eye
g.setColor(white);
g.fillOval(700, 100, 125, 125); //right white fill eye
g.setColor(Color.BLACK);
g.drawOval(700, 100, 125, 125); //right big black line eye
Color blue = new Color(0, 160, 198);
g.setColor(blue);
g.fillOval(635, 130, 51, 51); // left blue fill eye
g.setColor(Color.BLACK);
g.drawOval(635, 130, 50, 50); // left black small line eye
g.setColor(blue);
g.fillOval(735, 130, 51, 51); // right blue fill eye
g.setColor(Color.BLACK);
g.drawOval(735, 130, 50, 50); // right black small line eye
g.setColor(Color.BLACK);
g.fillOval(650, 145, 20, 20); // left black iris
g.setColor(Color.BLACK);
g.fillOval(750, 145, 20, 20); // right black iris
}
}
When it comes to animation, everything becomes variable. You also have a lot of repeated code (seriously, if you can paint one eye, you can paint lots).
The first thing you need to is make all the values of the eye as variable as possible.
The follow makes the eye size and position variable and the iris and pupil a scaled value of the eye size, which makes the whole process simpler to animate.
Next, you need an updated loop, which can update the state of the values you want to change. To keep it simple, I've set it up so that the pupil has a variable offset, which is changed over time.
import java.applet.Applet;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.Rectangle;
public class Pucca extends Applet {
public Pucca() {
setSize(700, 700);
Thread t = new Thread(new Runnable() {
private int xDelta = -1;
private int yDelta = 0;
private int blinkCount = 0;
#Override
public void run() {
while (true) {
try {
Thread.sleep(40);
} catch (InterruptedException ex) {
}
xOffset += xDelta;
double irisSize = eyeSize.width * irisScale;
double range = ((eyeSize.width - irisSize) / 2);
if (xOffset <= -range) {
xOffset = -(int) range;
xDelta *= -1;
} else if (xOffset >= range) {
xOffset = (int) range;
xDelta *= -1;
}
blinkCount++;
if (blink && blinkCount > 10) {
blink = false;
blinkCount = 0;
} else if (blinkCount > 25) {
blink = true;
blinkCount = 0;
}
repaint();
}
}
});
t.setDaemon(true);
t.start();
}
private boolean blink = false;
private int xOffset, yOffset = 0;
private Dimension eyeSize = new Dimension(125, 125);
private Point left = new Point(20, 20);
private Point right = new Point(left.x + 100, left.y);
private double irisScale = 0.4;
private double pupilScale = 0.16;
//paint method
#Override
public void paint(Graphics g) {
super.paint(g);
paintEye(g, new Rectangle(left, eyeSize));
paintEye(g, new Rectangle(right, eyeSize));
}
protected void paintEye(Graphics g, Rectangle bounds) {
Color white = new Color(255, 255, 255);
if (blink) {
g.setColor(Color.YELLOW);
} else {
g.setColor(white);
}
g.fillOval(bounds.x, bounds.y, bounds.width, bounds.height); //left white fill eye
g.setColor(Color.BLACK);
g.drawOval(bounds.x, bounds.y, bounds.width, bounds.height); // left big black line eye
if (!blink) {
Color blue = new Color(0, 160, 198);
paintEyePartAt(g, bounds, irisScale, blue);
paintEyePartAt(g, bounds, pupilScale, Color.BLACK);
}
}
private void paintEyePartAt(Graphics g, Rectangle bounds, double delta, Color color) {
int width = (int) (bounds.width * delta);
int height = (int) (bounds.height * delta);
g.setColor(color);
g.fillOval(
xOffset + bounds.x + ((bounds.width - width) / 2),
yOffset + bounds.y + ((bounds.height - height) / 2),
width, height); // left blue fill eye
g.setColor(Color.BLACK);
g.drawOval(
xOffset + bounds.x + ((bounds.width - width) / 2),
yOffset + bounds.y + ((bounds.height - height) / 2),
width,
height); // left blue fill eye
}
}
This complicates things, as painting can occur for any number of reasons, many of which you don't have control over or will be notified about, so you should be very careful about where and when you change values.
You should also have a look at Java Plugin support deprecated and Moving to a Plugin-Free Web and Why CS teachers should stop teaching Java applets.
Applets are simply a dead technology and given the inherent complexities involved in using them, you should instead focus you should probably attention towards window based programs.
Personally, I'd start with having a look at Painting in AWT and Swing and Performing Custom Painting
I am having a some difficulty with developing of my code. Since I am not too advanced with Java I need some help. I am trying to develop Mini Tennis game using Threads. The aim of this game is to catch the balls moving on the window with the paddle that can be controlled with the left and right buttons on the keyboard.
Those balls should move diagonally on the window and when they touch to any of the corner (out of bottom) they should change their ways like light reflection. Apart from this, when a ball touches to one of the obstacles they should change their ways as well.
Paddle on the bottom of the window can be controlled with left and right keys.The task of the player is to catch the balls. The number of balls that the user catches will be shown on the Score part with the total number of balls going to the bottom corner.
User may need to save the state of the game. When the user clicks to the “save game” button; ball locations and score should save to the file. And when the user clicks to the open button, the state of game should be reloaded.
My source code files are:
public class BallPanel extends JPanel implements Runnable {
int RED, GREEN, BLUE;
int Xdirection = 1, Ydirection = 1;
boolean pleaseWait = false;
BallPanel(int X, int Y){
locateBall(X, Y, 30, 30);
/* Random r = new Random();
RED = r.nextInt(255);
GREEN = r.nextInt(255);
BLUE = r.nextInt(255);
*/
}
public void paint(Graphics g){
int panelWidth = this.getWidth();
int panelHeight = this.getHeight();
// g.setColor( new Color(RED, GREEN, BLUE ));
g.setColor(Color.ORANGE);
g.fillOval(panelWidth/2, panelHeight/2,panelWidth/2, panelHeight/2);
}
public void locateBall(int x, int y, int width, int height){
setBounds(x, y, width, height);
repaint();
}
public void run() {
int width = this.getWidth();
int height = this.getHeight();
Random r = new Random();
while(true){
if(!pleaseWait){
int lastX = this.getX();
int lastY = this.getY();
if (lastX > 675) Xdirection = -1;
if (lastY > 485) Ydirection = -1;
if (lastX < -5) Xdirection = 1;
if (lastY < -5) Ydirection = 1;
/* if(lastX > 280 && lastY > 170){
Xdirection = -1;
Ydirection = -1;
}
*/
locateBall(lastX + Xdirection*r.nextInt(3),
lastY + Ydirection*r.nextInt(3),
width, height );
}
try{
Thread.sleep(5);
}catch(Exception e){};
}
}
}
public class BallWindow extends JFrame implements ActionListener{
JButton btnStop = new JButton("STOP");
JButton btnSave = new JButton("SAVE");
Vector<BallPanel> ballVector = new Vector<BallPanel>();
JPanel p1 = createPanel(280, 200, 200, 20, Color.gray);
JPanel p2 = createPanel(280, 300, 200, 20, Color.gray);
JPanel bottomp = createPanel(345, 540, 70, 15, Color.black);
JPanel lborder = createPanel(10, 10, 2, 560, Color.black);
JPanel rborder = createPanel(720, 10, 2, 560, Color.black);
JPanel tborder = createPanel(10, 10, 710, 2, Color.black);
public BallWindow() {
setLayout(null);
btnStop.setBounds(12, 15, 100, 30);
btnStop.addActionListener(this);
add(btnStop);
btnSave.setBounds(12, 50, 100, 30);
//btnSave.addActionListener(this);
add(btnSave);
Random r = new Random();
for(int i=0; i<7; i++){
BallPanel bp = new BallPanel(r.nextInt(740), r.nextInt(590));
Thread t = new Thread(bp);
ballVector.add(bp);
t.start();
add(bp);
}
add(p1);
add(p2);
add(bottomp);
add(lborder);
add(rborder);
add(tborder);
setSize(740, 590);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
repaint();
}
JPanel createPanel(int x, int y, int width, int height, Color pColor){
JPanel temp = new JPanel();
temp.setBackground(pColor);
temp.setBounds(x, y, width, height);
return temp;
}
public static void main(String[] args) {
new BallWindow();
}
public void actionPerformed(ActionEvent arg0) {
for (BallPanel ball : ballVector) {
ball.pleaseWait = !ball.pleaseWait;
}
if( btnStop.getText().equalsIgnoreCase("STOP"))
btnStop.setText("START");
else
btnStop.setText("STOP");
// if(arg0.getSource())
}
}
I'm stuck with obstacles part and the keylistener. Any type of help will be greatly appreciated.
Hava a look at http://zetcode.com/tutorials/javagamestutorial/
You should especially check out the Basics and the Animation section. It will help clean up the animation and thread stuff you are doing. It also shows a general pattern how one could implement a java game.
I am doing this small race between two cars, in a java applet.
Just two pictures moving at random speed. I am calculating the distance between current position and the finish line, and you are suppose to be able to see the distance in the upper corner.
The thing is I am not able to refresh the text field, instead it just applies a new layer on top of the old number so it is almost impossible to read.
Here are pictures to demonstrate my problem.
I thought I would be able to solve it by creating the blue rectangle at the start of each loop but that does not seem to solve it.
public void action(){
Random rand = new Random();
boolean race = true;
int x1 =500, y1 = 233;
int x2 = 500, y2 = 333;
int speed1 = rand.nextInt(15) + -16;
int speed2 = rand.nextInt(15) + -16;
int finishline = 30;
Text winnerBlue = new Text("Winner: BLUE",new Font("SansSerif",Font.BOLD,20), Color.blue,Color.white);
Text winnerRed = new Text("Winner: RED",new Font("SansSerif",Font.BOLD,20), Color.red,Color.white);
//background
Text text =null;
Text text2 = null;
window.fillRect(0, 0, 600, 400, Color.GREEN);
//track 1
window.fillRect(20, 330, 550, 39, Color.gray);
//track2
window.fillRect(20, 230, 550, 39, Color.gray);
//Finish line
window.fillRect(40, 210, 10, 180, Color.BLACK);
while(race){
text = new Text(Integer.toString(x1),new Font("Courier",Font.BOLD,20), Color.WHITE);
text2 = new Text(Integer.toString(x2),new Font("SansSerif",Font.BOLD,20), Color.WHITE);
window.fillRect(0, 0, 70, 50, Color.blue);
window.fillRect(70, 0, 70, 50, Color.red);
window.showImage(text, 0, 0);
window.showImage(text2, 70, 0);
window.showImage(car1.getImage(), x1, y1);
window.showImage(car2.getImage(), x2, y2);
car1.moveTo(x1 += speed1, y1);
car2.moveTo(x2 += speed2, y2);
window.pause(50);
if(x1 <= (finishline ) ){
speed1 = 0;
speed2 = 0;
window.showImage(winnerBlue, 200, 200);
race = false;
}
if(x2 <= (finishline)){
speed2 = 0;
speed1 = 0;
window.showImage(winnerRed, 200, 200);
race = false;
}
}
}
}
For the two screen shots and supplied code snippt, it's clear that you don't understand how painting works in Swing/AWT.
Do NOT ever, maintain any kind of refernce to the Graphics context out side of the paintXxx methods.
The paint methods perform a number of very important steps to prepare the Graphics context for painting
Start by taking a look through Performing Custom Painting