trying to create a sound sampler that can play a recorded sample at different frequencies/rates and am using TickRate to change the rate of playback, similar to the TickRate example. when i run i get a NullPointerException here player.patch(rateControl).patch(out); but can't figure out why, any ideas why?
import ddf.minim.*;
import ddf.minim.analysis.*;
import ddf.minim.signals.*;
import ddf.minim.ugens.*;
import ddf.minim.spi.*;
Minim minim;
AudioOutput out;
AudioSample sample1;
AudioInput in;
AudioRecorder recorder;
boolean recorded;
FilePlayer player;
TickRate rateControl;
void setup()
{
size(512, 200, P3D);
minim = new Minim(this);
in = minim.getLineIn(Minim.STEREO, 512);
recorder = minim.createRecorder(in, "myrecording2.wav");
rateControl = new TickRate(1.f);
out = minim.getLineOut(Minim.STEREO, 512);
player.patch(rateControl).patch(out);
textFont(createFont("Arial", 12));
}
void draw()
{
if ( recorder.isRecording() )
{
fill(255,255,255);
text("Now recording, press the r key to stop recording.", 5, 310);
}
else if ( !recorded )
{
fill(255,255,255);
text("Press the r key to start recording.", 5, 315);
}
else
{
fill(255,255,255);
text("Press the q key to save the recording to disk as a sample.", 5, 315);
}
for(int i = 0; i < out.bufferSize() - 1; i++)
{
float x1 = map(i, 0, out.bufferSize(), 0, width);
float x2 = map(i+1, 0, out.bufferSize(), 0, width);
line(x1, 50 + out.left.get(i)*50, x2, 50 + out.left.get(i+1)*50);
line(x1, 150 + out.right.get(i)*50, x2, 150 + out.right.get(i+1)*50);
}
}
void keyReleased()
{
if ( !recorded && key == 'r' )
{
if ( recorder.isRecording() )
{
recorder.endRecord();
recorded = true;
}
else
{
recorder.beginRecord();
}
}
if ( recorded && key == 'q' )
{
player = new FilePlayer( recorder.save() );
sample1 = minim.loadSample( "myrecording.wav" , 512 );
if ( sample1 == null ) println("didn't get sample");
}
}
void keyPressed()
{
if ( key == 's' )
{
sample1.trigger();
}
else if ( key == 'd' )
{
rateControl.value.setLastValue(3.0f);
sample1.trigger();
}
}
You only set player equal to something in the keyReleased() function. So when setup() is run, player still has the default null value.
Taking a step back, you should get into the habit of debugging your code. When you get a NullPointerException, try printing out the value of every variable on that line. You'll find which one is null, and then you can figure out why.
Related
enter image description here
enter image description here
I created an App and when I run it on a Motorola Xoom it executes the main activity as I expected but when I run it on a Huawei phone it displays Hello World and never executes the main activity. (Android 4.1.2 and 8 respectively. I have created projects using the Basic Activity and the Empty Activity and get the same result with both). How do I stop the Hello World?
package com.example.xoom;
import android.hardware.usb.UsbConstants;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.app.PendingIntent;
import android.content.Intent;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.text.style.RelativeSizeSpan;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Button;
import android.content.Context;
import android.hardware.usb.UsbManager;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbEndpoint;
import android.hardware.usb.UsbInterface;
import android.graphics.Color;
import android.graphics.Typeface;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.HashMap;
public class MainActivity extends AppCompatActivity
{
final Button[] pitchButton = new Button[50];
int startLength;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String ACTION_USB_PERMISSION = "com.example.xoom";
byte[] sendChar = {0x5A}; // ASCII "Z"
byte[] getChar = new byte[200];
boolean addListener;
TextView tv = new TextView(this);
int buttonCount = 0;
for (int i = 0; i < 50; i++)
{
pitchButton[i] = new Button(this);
pitchButton[i].setTypeface(Typeface.MONOSPACE);
}
tv.setTextSize(20);
getWindow().getDecorView().setBackgroundColor(Color.CYAN);
UsbManager manager = (UsbManager) getSystemService(Context.USB_SERVICE);
if (manager.getDeviceList().isEmpty()) // The device list is empty
{
tv.setTextColor(Color.RED);
tv.append("No USB Devices Found");
}
else
{
tv.setTextColor(Color.BLUE);
HashMap<String, UsbDevice> deviceList = manager.getDeviceList();
Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
UsbDevice device = deviceIterator.next(); // Get first device in list
PendingIntent pi = PendingIntent.getBroadcast(this, 0,
new Intent(ACTION_USB_PERMISSION), 0);
manager.requestPermission(device, pi);
UsbDeviceConnection connection = manager.openDevice(device);
getDeviceProperties(device, manager, tv); // Show USB device properties
getInterfaceProperties(device, connection, tv); // Show USB Interface properties
tv.setText(""); // Clear information from above because you don't want to see
// it normally but sometimes you do. Make this statement
// a comment if you do.
setConnectionProperties(connection); // Set speed etc of connection
UsbEndpoint endpointOut = device.getInterface(1).getEndpoint(1);
UsbEndpoint endpointIn = device.getInterface(1).getEndpoint(0);
connection.bulkTransfer(endpointOut, sendChar, 1, 500); // Send request for data
//
// It takes more than one read to get the data out of the FIFO
// Build up message by polling the FIFO until there is nothing left
// This has taken a lot of fiddling about to make it work. The baud
// and the timeouts have to be just so.
// (9600 and 200 work here but why who knows (or cares))
//
int k = 0;
char[] labelStr = new char[20];
int flag = Spanned.SPAN_EXCLUSIVE_EXCLUSIVE;
int bytesReceived = connection.bulkTransfer(endpointIn, getChar, 200, 200);
while (bytesReceived > 0)
{
for (int j = 0; j < bytesReceived; j++)
{
labelStr[k++] = (char) getChar[j];
if (getChar[j] == 13) // Carriage return
{
String label = String.valueOf(labelStr, 1, k - 1);
SpannableString spanLabel = new SpannableString(label);
spanLabel.setSpan(new RelativeSizeSpan(1.0f), 0, spanLabel.length(), flag);
addListener = true;
if (label.contains("Cross Slide"))
{ // Start adding pitches
spanLabel = new SpannableString("Pitch");
spanLabel.setSpan(new ForegroundColorSpan(Color.RED), 0, spanLabel.length(), flag);
addListener = false;
}
if (label.contains("End"))
{ // Start adding lengths
spanLabel = new SpannableString("Length");
spanLabel.setSpan(new ForegroundColorSpan(Color.RED), 0, spanLabel.length(), flag);
addListener = false;
if (startLength == 0) // Avoid the second "End" messages from MCU
startLength = buttonCount;
}
pitchButton[buttonCount].setText(spanLabel);
pitchButton[buttonCount].setId(buttonCount);
if (addListener)
{
pitchButton[buttonCount].setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
int buttonIndex;
Button buttonText = (Button) v;
String bt = buttonText.getText().toString();
String message;
if (bt.contains(".")) // On Button press display selected value
{
message = "Pitch ";
buttonIndex = 0;
}
else
{
message = "Length ";
buttonIndex = startLength;
}
message = message + bt;
pitchButton[buttonIndex].setText(message);
pitchButton[buttonIndex].setBackgroundColor(Color.GREEN);
}
});
}
buttonCount++;
k = 0;
}
}
bytesReceived = connection.bulkTransfer(endpointIn, getChar, 200, 200);
}
connection.close();
RelativeLayout.LayoutParams[] params = new RelativeLayout.LayoutParams[100];
RelativeLayout rel = new RelativeLayout(this);
rel.addView(tv);
int leftMargin = 0;
int topMargin = 0;
int lineCount = 0;
for (int i = 0; i < buttonCount - 1; i++)
{
params[i] = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
params[i].width = 150;
params[i].height = 50;
if (Math.IEEEremainder(lineCount, 5) == 0) // Put 5 buttons per line
{
topMargin = topMargin + params[i].height;
leftMargin = 0;
}
lineCount++;
if (pitchButton[i].getText().toString().contains("Pitch"))
{
topMargin = topMargin + params[i].height;
leftMargin = 0;
lineCount = 0;
}
if (pitchButton[i].getText().toString().contains("Length"))
{
topMargin = topMargin + params[i].height;
leftMargin = 0;
lineCount = 0;
}
params[i].leftMargin = leftMargin;
leftMargin = leftMargin + params[i].width;
params[i].topMargin = topMargin;
pitchButton[i].setLayoutParams(params[i]);
rel.addView(pitchButton[i]);
}
//
//Add control for setting taper
//
ArrayList<String> taperArray = new ArrayList<String>();
taperArray.add("1");
taperArray.add("2");
taperArray.add("3");
Spinner spinner = new Spinner(this,Spinner.MODE_DIALOG);
spinner.setBackgroundColor(Color.BLUE);
String taperPrompt = "Set Taper Angle";
RelativeLayout.LayoutParams spinnerParams = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
spinnerParams.width = 50;
spinnerParams.height = 40;
spinnerParams.topMargin = 600;
spinnerParams.leftMargin = 200;
spinner.setPrompt("Select Taper Angle");
spinner.setLayoutParams(spinnerParams);
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, taperArray);
spinner.setAdapter(spinnerArrayAdapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l)
{
}
public void onNothingSelected(AdapterView<?> adapterView)
{
}
});
RelativeLayout.LayoutParams taperParams = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
taperParams.width = 200;
taperParams.height = 50;
taperParams.topMargin = 600;
taperParams.leftMargin = 10;
TextView taperView = new TextView(this);
taperView.setLayoutParams(taperParams);
taperView.setText(taperPrompt);
taperView.setTextColor(Color.RED);
taperView.setTextSize(20);
rel.addView(taperView);
rel.addView(spinner);
setContentView(rel);
}
}
public void setConnectionProperties(UsbDeviceConnection connection)
{
connection.controlTransfer(0x40, 0, 0, 0, null, 0, 0);// reset
// mConnection.controlTransfer(0×40,
// 0, 1, 0, null, 0,
// 0);//clear Rx
connection.controlTransfer(0x40, 0, 2, 0, null, 0, 0);// clear Tx
connection.controlTransfer(0x40, 0x02, 0x0000, 0, null, 0, 0);// flow
// control
// none
connection.controlTransfer(0x40, 0x03, 0x4138, 0, null, 0, 0);// baudrate
// 9600 (4138 is 9600, 1A is 115200 0271 is 4800)
connection.controlTransfer(0x40, 0x04, 0x0008, 0, null, 0, 0);// data bit
// 8, parity
// none,
// stop bit
// 1, tx off
}
public void getInterfaceProperties(UsbDevice device, UsbDeviceConnection connection, TextView tv)
{
int interfaceCount = device.getInterfaceCount();
int endPointCount;
for (int i=0; i < interfaceCount-1; i++)
{
if (connection.claimInterface(device.getInterface(i), true)) {
tv.append("\nConnection Interface " + i + " Claim succeeded \n");
UsbInterface interfce = device.getInterface(i);
endPointCount = interfce.getEndpointCount();
tv.append("Endpoint count for Interface " + i + " is " + endPointCount + "\n");
for (int j = 0; j < endPointCount; j++) {
if (interfce.getEndpoint(j).getType() == UsbConstants.USB_ENDPOINT_XFER_INT)
tv.append("Endpoint " + j + " Type is Xfer Int \n");
if (interfce.getEndpoint(j).getType() == UsbConstants.USB_ENDPOINT_XFER_BULK)
tv.append("Endpoint " + j + " Type is Bulk Xfer \n");
if (interfce.getEndpoint(j).getDirection() == UsbConstants.USB_DIR_IN)
tv.append("Endpoint " + j + " Direction is IN \n");
if (interfce.getEndpoint(j).getDirection() == UsbConstants.USB_DIR_OUT)
tv.append("Endpoint " + j + " Direction is OUT \n");
tv.append("Max packet size = " + interfce.getEndpoint(j).getMaxPacketSize() + "\n");
}
tv.append("Interface Protocol is " + interfce.getInterfaceProtocol() + "\n");
}
}
}
public void getDeviceProperties(UsbDevice device, UsbManager manager, TextView tv)
{
tv.setTextSize(20);
tv.setTextColor(Color.BLUE);
tv.append("USB Device name = " + device.getDeviceName() + "\n");
tv.append("USB Product Id = " + device.getProductId() + "\n");
tv.append("USB Vendor Id = " + device.getVendorId() + "\n");
tv.append("USB Device Id = " + device.getDeviceId() + "\n");
if (manager.hasPermission(device)) // Can the App access the device ?
{
tv.append("Device Permission = Yes \n");
}
else
{
tv.append("Device Permission = No \n");
}
}
}
I have found the answer – when no USB devices are attached to the phone the message No USB Devices Found could ever be displayed on the screen. By adding the line setContentView(tv) after the line tv.append(“No USB Devices Found”) leaves this message on the screen rather than falling back to the Hello World message. Thank you for looking at it. I would still like to know if it is possible to get rid of the Hello World fragment as it seems totally unnecessary (or maybe it is).
I wanna write a Snake game with javaFX , but there is exception that I don't know about and I want to know how to fix it. ( i know it's not complete yet )
and I want to know , the class that extends Application ( with start override )
is exactly the main in other programs?
as you see , here is not static void main BC I didn't need, but if i want to add main where shoud i do?
it's the Exeption...
Exception in Application constructor
Exception in thread "main" java.lang.NoSuchMethodException: Main_Snake.main([Ljava.lang.String;)
at java.lang.Class.getMethod(Class.java:1819)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:125)
and my code is :
import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.BorderPane;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import java.util.ArrayList;
/**
* Created by Nadia on 1/5/2016.
*/
public class Main_Snake extends Application{
Snake snake = new Snake();
Apple apple = new Apple();
Canvas canvas = new Canvas(800, 600);
boolean goNorth = true, goSouth, goWest, goEast;
int x, y = 0; // marbut be apple
boolean j = false;
// int gm_ov = 0; // vase game over shodan
ArrayList<Integer> X = new ArrayList<Integer>();
ArrayList<Integer> Y = new ArrayList<>();
#Override
public void start(Stage primaryStage) throws Exception {
BorderPane b = new BorderPane(canvas);
Scene scene = new Scene(b, 800, 600);
primaryStage.setScene(scene);
primaryStage.show();
//KeyBoard(scene);
scene.setOnKeyPressed(new EventHandler<KeyEvent>() {
#Override
public void handle(KeyEvent e) {
switch (e.getText()) {
case "w":
if (!goSouth) {
goNorth = true;
goSouth = false;
goWest = false;
goEast = false;
}
break;
case "s":
if (!goNorth) {
goSouth = true;
goNorth = false;
goWest = false;
goEast = false;
}
break;
case "a":
if (!goEast) {
goWest = true;
goEast = false;
goSouth = false;
goNorth = false;
}
break;
case "d":
if (!goWest) {
goEast = true;
goWest = false;
goSouth = false;
goNorth = false;
}
break;
}
}
});
play();
}
public void play(){
AnimationTimer timer = new AnimationTimer() {
private long lastUpdate = 0;
#Override
public void handle(long now) {
if (now - lastUpdate >= 40_000_000) { // payin avordane sor#
snake.pos_S(); // har bar mar rasm mishe bad az move va ye sib ba X,Y khodesh rasm mishe tu tabe move dar morede tabe Point hast
apple.pos_A();
apple.random_Pos();
snake.Move();
lastUpdate = now; // sor#
}
}
};
timer.start();
}
/* public void KeyBoard(Scene scene) {
}*/
}
class Apple extends Main_Snake {
public void random_Pos() {
if (j == false) { // ye sib bede ke ru mar nabashe ( rasmesh tu rasme )
do {
x = (int) (Math.random() * 790 + 1);
y = (int) (Math.random() * 590 + 1);
} while (X.indexOf(x) != -1 && Y.get(X.indexOf(x)) == y || x % 10 != 0 || y % 10 != 0);
/*inja aval chek kardam tu araylist x hast ya na ag bud sharte aval ok hala sharte do ke tu Y ham mibinim tu hamun shomare khune
y barabare y mast ag bud pas ina bar ham montabeghan va sharte dovom ham ok . 2 sharte akhar ham vase ine ke mare ma faghat mazrab
haye 10 and pas ta vaghti in se shart bargharare jahayie ke ma nemikhaym va hey jaye dg mide*/
j = true;
}
}
public void pos_A() {
GraphicsContext gc = canvas.getGraphicsContext2D();
gc.setFill(Color.BLACK);
gc.fillRect(x, y, 10, 10);
}
public void Point() {
if (X.get(0) == x && Y.get(0) == y) {
j = false;
}
}
}
class Snake extends Main_Snake {
Snake(){ //cunstructor
X.add(400);
Y.add(300);
X.add(400);
Y.add(310);
X.add(400);
Y.add(320);
X.add(400);
Y.add(330);
X.add(400);
Y.add(340);
}
public void pos_S(){
GraphicsContext gc = canvas.getGraphicsContext2D();
gc.setFill(Color.WHITE);
gc.fillRect(0, 0, canvas.getWidth(), canvas.getHeight());
apple.pos_A();
// keshidane mar (body yeki ezafe tar az adade morabaA mide)
for (int i = X.size() - 1; i >= 0; i--)
gc.fillRect(X.get(i), Y.get(i), 10, 10);
}
public void Move(){
int Px = X.get(X.size() - 1);
int Py = Y.get(Y.size() - 1);
for (int z = X.size() - 1 ; z > 0 ; z--){
X.remove(z);
X.add(z , X.get(z-1) ) ;
Y.remove(z);
Y.add(z , Y.get(z-1) ) ;
}
if (goNorth) {
Y.add(0 , Y.get(0) - 10);
Y.remove(1);
}
if (goSouth) {
Y.add(0 , Y.get(0) + 10);
Y.remove(1);
}
if (goEast) {
X.add(0 , X.get(0) + 10);
X.remove(1);
}
if (goWest) {
X.add(0 , X.get(0) - 10);
X.remove(1);
}
apple.Point(); // emtiaz gerefte
if ( j == false) {
X.add(Px);
Y.add(Py);
}
if ( X.get(0) > 790 ){
X.remove(0);
X.add(0 , 0);
}
if ( X.get(0) < 0 ){
X.remove(0);
X.add(0 , 800);
}
if ( Y.get(0) > 590 ){
Y.remove(0);
Y.add(0 , 0);
}
if ( Y.get(0) < 0 ){
Y.remove(0);
Y.add(0 , 600);
}
}
}
The standard Oracle Java Runtime Environment can execute Application subclasses directly from the command line, even if they do not contain a main method. So assuming you are using a standard JRE, from the command line you can execute
java Main_Snake
and it will run (assuming no other errors, etc).
Other environments, and most IDEs, don't support this execution mode, so if you want to run in those environments (including running in Eclipse, for example), you need a main(...) method which launches your JavaFX application. So just add
public static void main(String[] args) {
launch(args);
}
to the Main_Snake class.
Im using clientcanvas to edit pictures in my app created with tabris. So far it's working quite well, but I got a problem to save the edited picture as a new image. Does anybody has any experience with that?
You need to convert the swt ImageData to an awt BufferedImage and save it. A util for this may look like this:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.IndexColorModel;
import java.awt.image.WritableRaster;
import org.eclipse.swt.graphics.ImageData;
import org.eclipse.swt.graphics.PaletteData;
import org.eclipse.swt.graphics.RGB;
public class ImageUtil {
public static BufferedImage convertToAWT( ImageData data ) {
BufferedImage imageToDraw = bgToAWT( data, data.width, data.height );
BufferedImage result = new BufferedImage( data.width, data.height, BufferedImage.TYPE_INT_RGB );
drawWhiteBackground( result );
Graphics graphics = result.getGraphics();
graphics.drawImage( imageToDraw, 0, 0, null );
graphics.dispose();
return result;
}
/*
* See
* http://m4tx.pl/en/2013/01/01/java-swt-to-awt-and-vice-versa-image-conversion
* -with-transparency-support/
*/
public static BufferedImage bgToAWT( ImageData data, int width, int height ) {
BufferedImage result = null;
ColorModel colorModel = null;
PaletteData palette = data.palette;
if( palette.isDirect ) {
BufferedImage bufferedImage = new BufferedImage( width, height, BufferedImage.TYPE_INT_ARGB );
for( int y = 0; y < data.height; y++ ) {
for( int x = 0; x < data.width; x++ ) {
int pixel = data.getPixel( x, y );
RGB rgb = palette.getRGB( pixel );
bufferedImage.setRGB( x, y, data.getAlpha( x, y ) << 24
| rgb.red << 16
| rgb.green << 8
| rgb.blue );
}
}
result = bufferedImage;
} else {
RGB[] rgbs = palette.getRGBs();
byte[] red = new byte[ rgbs.length ];
byte[] green = new byte[ rgbs.length ];
byte[] blue = new byte[ rgbs.length ];
for( int i = 0; i < rgbs.length; i++ ) {
RGB rgb = rgbs[ i ];
red[ i ] = ( byte )rgb.red;
green[ i ] = ( byte )rgb.green;
blue[ i ] = ( byte )rgb.blue;
}
if( data.transparentPixel != -1 ) {
colorModel = new IndexColorModel( data.depth,
rgbs.length,
red,
green,
blue,
data.transparentPixel );
} else {
colorModel = new IndexColorModel( data.depth, rgbs.length, red, green, blue );
}
BufferedImage bufferedImage = new BufferedImage( colorModel,
colorModel.createCompatibleWritableRaster( width,
height ),
false,
null );
WritableRaster raster = bufferedImage.getRaster();
int[] pixelArray = new int[ 1 ];
for( int y = 0; y < data.height; y++ ) {
for( int x = 0; x < data.width; x++ ) {
int pixel = data.getPixel( x, y );
pixelArray[ 0 ] = pixel;
raster.setPixel( x, y, pixelArray );
}
}
result = bufferedImage;
}
return result;
}
private static void drawWhiteBackground( BufferedImage bufferedImage ) {
Graphics2D graphics = bufferedImage.createGraphics();
graphics.setColor( new Color( 255, 255, 255 ) );
graphics.fillRect( 0, 0, bufferedImage.getWidth(), bufferedImage.getHeight() );
}
}
here is my code for the snake game, the thing i need to do is generate location for the snake food, once the snake touch the snake food, it will regenerate the location of the food~pls, i really need your guys help!!! just kindly have a look
package snake;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Graphics;
public class SnakeCanvas extends Canvas{
private int currentX =getWidth()/2;
private int currentY =getHeight()/2;
private boolean condition = false;
private boolean position = false;
Random rand = new Random();
int randomX=rand.nextInt(180) + 20;
int randomY =rand.nextInt(250) + 20;
private final Midlet midlet;
private int score = 0;
Timer t;
public SnakeCanvas(Midlet midlet)
{
this.midlet = midlet;
t = new Timer();
t.schedule(new TimerTask() {
public void run() {
if((condition==false)&&(position==false))
{
currentY -= 5 ;
}
if((condition==false)&&(position==true))
{
currentY += 5 ;
}
if((condition==true)&&(position==false))
{
currentX -= 5 ;
}
if((condition==true)&&(position==true))
{
currentX += 5 ;
}
}
}, 50, 50);
}
public void paint(Graphics g) {
boolean touch=false;
//drawing Background
g.setColor(0x000000);
g.fillRect(0, 0, getWidth(), getHeight());
//drawing snake
g.setColor(0xffffff);
g.fillRoundRect(currentX, currentY, 20, 20, 5, 5);
//snake food
g.setColor(234,41,42);
g.fillRect(randomX,randomY,10,10);
if((currentX-9<=randomX+4&¤tX+9>=randomX-4)&&(currentY-9<=randomY+4&¤tY+9>=randomY-4)){
addScore();
}
//drawing block
g.setColor(82,133,190);
g.fillRect(0, 0, getWidth(), 5);
g.fillRect(0, getHeight()-5, getWidth(), 5);
g.fillRect(0, 0, 5, getHeight());
g.fillRect(getWidth()-5, 0, 5, getHeight());
if((currentX>=getWidth()-10)||(currentX<5)||(currentY>=getHeight()-5)||(currentY<5))
midlet.GameOver();
g.setColor(142,255,17);
g.drawString("Score : "+score, 8, 7, Graphics.TOP|Graphics.LEFT);
repaint();
}
protected void keyPressed(int keyCode) {
System.out.println(keyCode);
switch(keyCode)
{
case -1:
condition = false;
position = false;
break;
case -2:
condition = false;
position = true;
break;
case -3:
condition = true;
position = false;
break;
case -4:
condition = true;
position= true;
break;
}
repaint();
}
private void addScore() {
score=score+1;**strong text**
}
private void food(){
Random rand = new Random();
int randomX=rand.nextInt(150) + 20;
int randomY=rand.nextInt(250) + 20;
}
}
Okay. I don't know if you managed to solve your problem but there seems to be a couple things wrong with your code.
First in this code block in the beginning:
Private int currentX =getWidth()/2;
private int currentY =getHeight()/2;
private boolean condition = false;
private boolean position = false;
Random rand = new Random();
int randomX=rand.nextInt(180) + 20;
int randomY =rand.nextInt(250) + 20;
^I am sure this does not compile, you can't have function calls when declaring header variables.
Second
if((condition==false)&&(position==false))
{
currentY -= 5 ;
}
if((condition==false)&&(position==true))
{
currentY += 5 ;
}
if((condition==true)&&(position==false))
{
currentX -= 5 ;
}
if((condition==true)&&(position==true))
{
currentX += 5 ;
}
}
}, 50, 50);
}
Your block coding style is horrible and hard to read. http://en.wikipedia.org/wiki/Programming_style#Indentation has a good guide on mastering this, read it!
This applies to your switch/case statements too!
Lastly your question:
private void food(){
Random rand = new Random();
int randomX=rand.nextInt(150) + 20;
int randomY=rand.nextInt(250) + 20;
}
^ Just generates random numbers, but doesn't do anything with them. I am guessing you meant:
private void food(){
Random rand = new Random();
randomX=rand.nextInt(150) + 20;
randomY=rand.nextInt(250) + 20;
}
which sets the classes global randomX and randomY to new values.
This doesn't help though since you don't actually call the Food() function anywhere in this class! And considering it is "Private" and can only be used by this class that must be an error.
tl;dr You need to study programming some more, but it is a good effort. I will help you more in the comments if you like. If my answer helped, please accept it.
Fenix
Here is what I have:
2 buttons
2 sounds
when button 1 press I want sound 1 played when button 2 pressed i want only sound2 played.
My code:
import ddf.minim.*;
RadioButtons r;
boolean showGUI = false;
Minim minim;
AudioPlayer player_1;
AudioPlayer player_2;
PImage img, img2;
PShape img1;
void setup() {
size(1024,735);
String[] radioNames = {"Button1", "Button2"};
r = new RadioButtons(radioNames.length, 20,700,50,30, HORIZONTAL);
r.setNames(radioNames);
img = loadImage("img.jpg");
img1 = loadImage("img1.png");
img2 = loadShape("img1.svg");
minim = new Minim(this);
//sound1
player_1 = minim.loadFile("sound1.wav");
//sound2
player_2 = minim.loadFile("soun2d2.wav");
}
void draw() {
//background(0);
//println (mouseX +"," + mouseY);
// Draw the image to the screen at coordinate (0,0)
//sound1
image(img,0,0);
if(r.get() == 0)
shape(img1,695,106);
if(mousePressed){
if(mouseX>695 && mouseX <695+190 && mouseY>106 && mouseY <106+180){
fill(0,0,0,0);
image(img2,300,150);
player_1.cue(0);
player_1.play();
}
}
//sound2
if(r.get() == 1)
shape(img1,695,106);
if(mousePressed){
if(mouseX>695 && mouseX <695+190 && mouseY>106 && mouseY <106+180){
fill(0,0,0,0);
image(img2,300,150);
player_2.cue(0);
player_2.play();
}
}
if(showGUI)
{
r.display();
}
}
void mouseReleased()
{
if(showGUI){
if(mouseY> height-60)
r.mouseReleased();
else
showGUI = false;
}
else{
showGUI = true;
}
}
At the moment both sounds play at the same time.
What am I missing?
You have to stop the current sample before you start the other one.
If you want to play player_2, you have to call:
player_1.pause();
player_1.rewind();
before you call player_2.play(); and the other way around.
UPDATE::
I Solved this by
Adding IF & ELSE IF statements.
EXAMPLE BELOW.
void draw() {
//background(0);
//println (mouseX +"," + mouseY);
// Draw the image to the screen at coordinate (0,0)
//sound1
image(img,0,0);
if(r.get() == 0)
{
code...
}
}
}
//sound2
else if(r.get() == 1)
{
code...
}
}
}
if(showGUI)
{
r.display();
}
}
I made this very stupid example, is it any help? It is stupid, specially the button class and event handling, but as I don't know which RadioButtons you are using I putted those lines together... maybe it can inspire you.
import ddf.minim.*;
PVector pOne, pTwo;
Button one, two;
Minim minim;
AudioPlayer player_1;
AudioPlayer player_2;
void setup() {
size(300,300);
pOne = new PVector(50, 150);
pTwo = new PVector(150, 150);
one = new Button (pOne, "one");
two = new Button (pTwo, "two");
minim = new Minim(this);
//sound1
player_2 = minim.loadFile("down_in_the_hole.mp3");
//sound2
player_1 = minim.loadFile("emotional_rescue.mp3");
}
void draw() {
background(220);
one.display();
one.update();
two.display();
two.update();
if(one.pressed){
player_2.pause();
player_1.rewind();
player_1.play();
ellipse(30,30,10,20);
// two.pressed = false;
}
if(two.pressed){
player_1.pause();
player_2.rewind();
player_2.play();
ellipse(130,30,10,20);
//one.pressed = false;
}
}
void mouseReleased(){
one.pressed = false;
two.pressed = false;
}
class Button{
String name;
PVector pos;
boolean pressed = false;
int xsz = 40;
int ysz = 20;
Button(PVector _pos, String _name ){
pos = _pos;
name = _name;
}
void display(){
color c = isOver()? 255:120;
fill(c);
rect(pos.x, pos.y, xsz, ysz);
fill(0);
text(name, pos.x+5, pos.y +ysz/2);
}
void update(){
if(isOver() && mousePressed)
pressed = true;
}
boolean isOver(){
return mouseX > pos.x && mouseX < pos.x + xsz &&
mouseY > pos.y && mouseY < pos.y + ysz;
}
}