im very new to java & android development,
I want a textfield that changes 50% to "You win!" or 50% to "You Lose!" when i click/tap a button.
And a image rotating randomly, like it is 0° then it will get a number between 0 and 100 (higher then 50 is clockwise lower then 50 is counter-clockwise)
i might be asking to much xD but i really dont know how i do this.
How do i do this ?
I actually dont want very advanced answers because im very new to java.
Theres is pretty much nothing in my code except for a button and a textfield.
Here a little help to start off.
First you should add an OnClickListener to your button:
yourButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
handleButtonClick();
}
});
The handleButtonClick()-method could look like this:
private void handleButtonClick() {
// Here we get a random integer between 0 and 99 (including 0 and 99)
int randomNumber = new Random().nextInt(100);
// Here we check if the random number is even
boolean isEven = randomNumber % 2 == 0;
// Now you can do stuff depending on the integer itself (rotation)
// and depending on whether it's even or not.
if(randomNumber < 50){
// do this
} else {
// do that
}
if(isEven){
// do this
} else {
// do that
}
}
To change the text you use:
yourText.setText(...);
But this is really basic stuff you could read on Android TextView
And rotating images was discussed here Android: Rotate image in imageview by an angle
Please read tutorials or refer to this before asking every little thing you could easily look up. Feel free to ask again when you get stuck.
Good luck.
Math.random() method gives you a floating point number between 0-1 but not included 1.
All you have to do is:
int randomNumber = (int)(Math.random()*101);
if(randomNumber < 50)
...
else
...
Related
So for a school project, I have to create a game with a program called 'Processing'.
I am creating a main menu with the switch statement. For that I want to use the buttons 'Start', 'Help', and 'exit'.i would like to use those buttons to change the variables of the switch statement. Therefore I'm using "mousePressed". The problem is that which button I'm pressing, is giving me the same result as the 'exit' button. Could somebody give me tips on how I can structure my menu better or even make my button work? I am using a library on Processing called 'ControlP5' to make my buttons.
here is my code so far:
int mode; // 1: intro screen, 2: game , 3: game over
final int INTRO = 1;
final int PLAY = 2;
final int GAMEOVER = 3;
//==============================================================
void setup(){
size(1920,1080);
mode = 1;
}
//========================================================
void draw(){
if(mode == 1){
introScreen();
}
else if (mode == 2){
gameItself();
}
else if (mode == 3){
gameOver();
}
else println("mode error");{
}
}
void introScreen(){
mode = 1;
static int Page = 0;
import controlP5.*;
ControlP5 cp5;
cp5= new ControlP5(this);
switch(Page){
case 0: // main menu
cp5.addButton("Start").setValue(0).setPosition(1420,250).setSize(400,100);
cp5.addButton("Exit").setValue(0).setPosition(1420,650).setSize(400,100);
cp5.addButton("Help").setValue(0).setPosition(1420,450).setSize(400,100);
break;
case 1: //help menu
cp5.addButton("Back").setValue(0).setPosition(1420,450).setSize(400,100);
break;
}
public void Start(){
if(mousePressed){
mode = 2; // switching to the game itself
}
println("Start");
}
public void Exit(){
if(mousePressed){
exit(); }
println("Exit");
}
public void Help(){
Page = 1;
println("Help");
}
public void Back(){
if(mousePressed){
Page = 0;
}
println("Back");
}
void gameItself(){
// game and stuff
}
void gameOver(){
//gameover
}
Take a look at how the mousePressed event works. You may use this information useful.
To achieve your goal as to change the Page variable by clicking buttons, there are multiple options. First, I'll go with the easier one, the one which doesn't need an import but just check for coordinates. Then I'll do the same thing, but with controlP5.
1. Just checking where the clicks lands
I'll go with the most basic one: detecting the "click" and checking if it's coordinates are inside a button.
First, we'll add the mouseClicked() method. This method is called every time a mouse button is pressed.
// I'm typing this out of IDE si there may be some quirks to fix in the code
void mouseClicked() {
switch(Page) {
case 0:
if (mouseX > 1420 && mouseX < 1420+400 && mouseY > 250 && mouseY < 250+100) {
// You're in the main menu and Start was clicked
}
if (mouseX > 1420 && mouseX < 1420+400 && mouseY > 650 && mouseY < 650+100) {
// You're in the main menu and Exit was clicked
}
if (mouseX > 1420 && mouseX < 1420+400 && mouseY > 450 && mouseY < 450+100) {
// You're in the main menu and Help was clicked
}
// You should use 'else if' instead of 3 different if, but I coded it like that so it would be easier to see the small differences between the coordinates
case 1:
if (mouseX > 1420 && mouseX < 1420+400 && mouseY > 450 && mouseY < 450+100) {
// You're un the help menu and Back was clicked
}
}
}
As you can see, I just used the coordinates and size of your buttons to check if the click was located inside one. That's kind of ninja-ing my way out of this issue. I don't know how far into programming you are, or else I would recommand to build a class to handle user inputs, but this way is easy to manage for small exercises like homework.
2. Designing controlP5 buttons
I'm not a ControlP5 expert, so we'll keep close to the basics.
I'll be blunt, the code you provided is ripe with problems, and it's not so many lines, so instead of pointing where it goes wrong I'll give you some skeleton code which will work and on which you can build some understanding. I'll give you the tools and then you can make your project work.
When you design your buttons, if you design them all in the same object, they'll share some properties. For an example, all your buttons will be visible or invisible at the same time. You don't need to redraw them all the time, because they already handle this, so you need to manage them with another method.
You should design your buttons as global objects (as you did), and add them to the ControlP5 object which makes the most sense. You can have one button per object if you want, or many if they are linked together, for an example all the "menu" buttons which appears at the same time could be owned by the same object. Design your buttons in the setup() method if you design them only one time for the whole program. Of course, if this was more than an homework, you may want to avoid the buttons being globals, but it'll be much easier to keep them in memory for a short project.
The "name" of the button is also the name of the method that it'll try to call if you click on it. Two buttons cannot share the same "name". Buttons can have a set value which will be sent to the method that they call.
You don't need to use Processing's mouse events for the buttons to work. They are self-contained: they have their own events, like being clicked on or detecting when the mouse is over them. Here's the documentation for the full list of the methods included in the ControlP5 buttons.
You don't need to manage the buttons in the draw() loop. They manage themselves.
Here's some skeleton code to demonstrate what I just said. You can copy and paste it in a new Processing project and run it to see what's going on.
ControlP5 cp5;
ControlP5 flipVisibilityButton;
int Page = 0;
void setup() {
size(1920, 800);
textAlign(CENTER, CENTER);
textSize(60);
fill(255);
cp5 = new ControlP5(this); // this is ONE object, which will own buttons.
cp5.addButton("MenuButton0") // this is the name of the button, but also the name of the method it will call
.setValue(0) // this value will be sent to the method it calls
.setPosition(1420, 250)
.setSize(400, 100);
cp5.addButton("MenuButton1")
.setValue(1)
.setPosition(1420, 450)
.setSize(400, 100);
cp5.addButton("MenuButton2")
.setValue(2)
.setPosition(1420, 650)
.setSize(400, 100);
flipVisibilityButton = new ControlP5(this); // this is a different object which own it's own controls (a button in this case)
flipVisibilityButton.addButton("flipVisibility")
.setValue(2)
.setPosition(200, height/2)
.setSize(200, 100);
}
void draw() {
// No button management to see here
background(0);
// showing which button has been pressed while also keeping watch to see if the mouse is over one of the cp5 buttons
text(Page + "\n" + cp5.isMouseOver(), width/2, height/2);
}
void MenuButton0(int value) {
ChangePage(value);
}
void MenuButton1(int value) {
ChangePage(value);
}
void MenuButton2(int value) {
ChangePage(value);
}
void ChangePage(int value) {
Page = value;
}
void flipVisibility(int value) {
// When the buttons are invisible, they are also unclickable
cp5.setVisible(!cp5.isVisible());
}
You should be able to expand on this example to do your project, but if you have difficulties don't hesitate to comment here and ask further questions. Have fun!
i have a problem with my code. I think that my problem is easy,but i have compiled for 3 days without good results. I have three images. They are put on screen one-one each time. User choose from 4 button if image's side is up, down, right or left. Also, i want to understand if user was wrong and then i will count errors. When user make 3 errors then the game will stop. I have shown code below. Please help me if you have any good idea.
The problem is that at the first loop,run right.It goes at the first if. After that it do the loop and then it does not go to second if.
if it is more helpful,some details:
i want to make a programma that it will show to user an image.This image has 4 sides (up,down,right,left).When the image is at "up side",user has to click on up button,when the image is at "down side",user has to click on down button etc. User can do 3 errors max. At first,program show the image at right side,if user clicks on right button then i want to show the "second image" at left side.If user does not at left side,then i want to add an error(error++) and after it shows the third image at up side etc. I hope it is more helpful to understand. If you can't please let me know.
My program is at Netbeans,java.
Thank you
public void actionPerformed(ActionEvent e)
{
while(errors<3)
{
image.setIcon(createImageIcon("visual1" + e.getActionCommand() + ".PNG"));
if (k==1)
{
if(e.getSource() == right_button)
{
image.setIcon(createImageIcon("visual2" + e.getActionCommand() + ".PNG"));
}
}
else if ( k==2 )
{
if(e.getSource() == left_button )
{
image.setIcon(createImageIcon("visual3" + e.getActionCommand() + ".PNG"));
}
}
else if (k==3 )
{
if(e.getSource() == up_button)
{
System.out.print("if3");
}
}
else
{
errors++;
}
k=k+1;
}
}
You should consider calling Repaint and Invalidate, right after you update your GUI like this -
mainframe.repaint();
mainframe.invalidate();
here mainframe is your JFrame object.
A problem I see with your while loop is that it is at risk of getting stuck in an infinite loop, since the variable used as an exit criterion is only updated some of the time, in an else block. I think you should re-arrange your logic:
Get rid of that while loop as it will only cause trouble. It is useful for a linear command line program but not for an event-driven GUI program like yours.
Read in all images and create all ImageIcons in the class constructor, and store them in variables. There's no need to re-read the images multiple times (unless they're huge).
Instead of using a while loop, increment the error variable in your method above, and then write the method so that it will change behaviors depending on the value of error (depending on the state of the class).
e.g.,
// somewhere in your code create your icons
Icon rightIcon = ......;
Icon leftIcon = .....;
Icon upIcon = .....;
Icon downIcon = .....;
// elsewhere in your code
public void actionPerformed(ActionEvent e) {
if (errors >= 3) {
// notify user of error
return; // end this method
}
// check if current icon matches image
// if so, change icon
// if not increment error
}
Note that an enum Direction {UP, DOWN, LEFT, RIGHT} and a Map<Direction, Icon> could be helpful here.
I'm programming Android for the first time and I'm having some difficulties. The idea is to make a guessing game app in which the user takes a number in his/her head and the app tries to guess it. The user will give hints like higher and lower to the app. For some reason the app crashes after I press the start button. Because of this, I know that there is an error in the onClick method but since it shuts down immediately after I press the start button, I can't use something like a println to debug.
So actually I have 2 questions:
Where does my reasoning fail? (or show me how to figure out my mistakes)
How can I debug things like this?
The start, higher and lower are all buttons in the program.
#Override
public void onClick(View arg0) {
int min = 0;
int max = 100;
Random random = new Random(100);
int answer = 0;
if (arg0 == start) {
answer = random.nextInt(100);
buttonTextView.setText(answer);
}
else if (arg0 == higher){
min = answer;
answer = random.nextInt((max - min) + min);
buttonTextView.setText(answer);
}
else if (arg0 == lower) {
max = answer;
answer = random.nextInt((max-1) - min);
buttonTextView.setText(answer);
}
}
where does my reasoning fail?
You are using the wrong setText() method. In the TextView Docs you will see that there is one which takes an int, this is for retrieving a String resource that you have in your strings.xml so you would pass it a resource id. So your setText() is looking for a resource with the id of whatever your answer variable is. You will want to convert this to a String with something like
buttonTextView.setText(String.valueof(answer));
or one of several different ways.
How can I debug things like this?
When your app crashes there will be an exception in your logcat. This answer can help you to read your logcat. To open your logcat window in Eclipse, if it isn't already, you can do this
Window --> Show View --> Other --> Android --> LogCat
A couple side notes
You should change your params like in onClick() to something meaningful so I would change
public void onClick(View arg0)
to something like
public void onClick(View v) // v for view, could also be view, btn
// whatever makes sense to you and others who may read it
You also should compare the id of your View clicked instead of the View itself. So you would compare it with something like the following (assuming you changed arg0 to v)
if (v.getId() == R.id.start) // Assuming start is the id in your xml of your Button
// this will also allow you to use a switch statement
Your variables in onClick() (min, max, and answer) should be initialized outside of onClick() or they will be reset to the default values with each click which I'm pretty sure you don't want (thanks to 323go for pointing that out).
[UPDATE] i changed the order a bit so i call the super.act(delta) at the end of the method and it seems to help a bit! But not that sure about it yet.
I got a square system for my map. So its an 2D array and i i make one move the figure does move from one square to the next. While that it's not possible to "stop" the figure between 2 squares. When my characters made one move i check if the Touchpad is touched and if yes i start the next move. While that it seems to lag sometimes and i dont know why!? I really hope you may find the "lag". Here is how i calculate the next move inside the act()of my Actor Character:
#Override
public void act(float delta) {
super.act(delta); // so the actions work
if (moveDone) {
if (screen.gameHud.pad.isTouched()) {
// check in which direction is the touchcontroller
if (screen.gameHud.pad.getKnobPercentX() < 0
&& Math.abs(screen.gameHud.pad.getKnobPercentY()) < Math
.abs(screen.gameHud.pad.getKnobPercentX())) {
// checkt if the |x|>|y|
if (checkNextMove(Status.LEFT)) {
this.status = Status.LEFT;
move(Status.LEFT);
this.screen.map.mapArray[(int) (this.mapPos.x)][(int) this.mapPos.y] = Config.EMPTYPOSITION;
this.screen.map.mapArray[(int) (this.mapPos.x - 1)][(int) this.mapPos.y] = Config.CHARSTATE;
this.mapPos.x--;
moveDone = false;
}
} else if //.... rest is the same just with other directions
else{ //if touchpad isnt touched!
setIdle();
}
updateSprite(delta); //just change the textureRegion if its time for that
} //methode end
Okay so you need some more informations i am sure. Checkmoves like this:
case LEFT:
if (this.mapPos.x - 1 >= 0)
if (this.screen.map.mapArray[(int) (this.mapPos.x - 1)][(int) this.mapPos.y] == Config.EMPTYPOSITION)
return true;
break; //same for all other just direction changin
And the last you need to know is the move(_) i guess. It does add an moveTo Action to my figures.
public void move(Status direction) {
switch (direction) {
case LEFT:
this.addAction(Actions.sequence(
Actions.moveTo((getX() - Config.BLOCK_SIZE), getY(), speed),
moveDoneAction));
break;
moveDoneAction is a simple RunnableAction that set the boolean moveDone to true if its done moving.
i really hope you can help. If you need some more informations please let me know as comment!
There are better tools than StackOverflow for optimizing Android code. Use a profiler and see what is actually happening. Specifically, the traceview profiler: how to use traceview in eclipse for android development? (If you're not using Eclipse, you can use traceview directly via the ADT.)
I'm having a really weird problem while following the Gestures tutorial here: http://developer.android.com/resources/articles/gestures.html.
4 unique gestures are created in Gesture Builder: + - × /
Add and multiply are multi-stroke. Subtract and divide are single stroke.
The Activity loads the pre-built GestureLibrary (R.raw.gestures), adds an OnGesturePerformedListener to the GestureOverlayView, and ends with onGesturePerformed() when a gesture is detected & performed.
Activity layout in XML
<android.gesture.GestureOverlayView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/gestures"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gestureStrokeType="multiple"
android:eventsInterceptionEnabled="true"
android:orientation="vertical"
/>
Located in onCreate()
mLibrary = GestureLibraries.fromRawResource(this, R.raw.gestures);
if (!mLibrary.load()) {
finish();
}
GestureOverlayView gestures = (GestureOverlayView) findViewById(R.id.gestures);
gestures.addOnGesturePerformedListener(this);
Located in onGesturePerformed()
ArrayList<Prediction> predictions = mLibrary.recognize(gesture);
// We want at least one prediction
if (predictions.size() > 0) {
Prediction prediction = predictions.get(0);
// We want at least some confidence in the result
if (prediction.score > 1.0) {
// Show the spell
Toast.makeText(this, prediction.name, Toast.LENGTH_SHORT).show();
}
}
The main problem is the pre-built gestures are not being recognized correctly. For example, onGesturePerformed() is never performed if a horizontal gesture is followed by a vertical (addition). The method is called if a vertical gesture is followed by a horizontal. This is how GesturesListDemo behaves too (GesturesDemos.zip # code.google.com).
Furthermore, the predicted gesture ends up being the incorrect gesture. Add is recognized as subtract; multiply as divide; Subtract as add. It's completely inconsistent.
Finally, add and subtract gestures typically share similar Prediction.score's, which is weird since they differ by an entire stroke.
Sorry about the long post -- wanted to be thorough. Any advice would be greatly appreciated, thanks all.
I realize this is a really old question, but it hasn't been answered yet and this might help someone. I just came across a similar problem and my solution was to use gesture.getStrokesCount() to differentiate between single- and multi-stroke gestures.
Example:
ArrayList<Prediction> predictions = mLibrary.recognize(gesture);
// We want at least one prediction
if (predictions.size() > 0) {
Prediction prediction = predictions.get(0);
// We want at least some confidence in the result
if (prediction.score > 1.0) {
if (gesture.getStrokesCount() > 1) {
// This is either add or multiply
}
else {
// This is either subtract or divide
}
}
}
Building on Drew Lederman his answer, you can use this implementation of onGesturePerformed to always get the best result:
public void onGesturePerformed(GestureOverlayView overlay, Gesture gesture) {
ArrayList<Prediction> predictions = store.recognize(gesture);
double highScore = 0;
String gestureName = "";
for (Prediction prediction : predictions) {
if (prediction.score > SCORE && prediction.score > highScore &&
store.getGestures(prediction.name).get(0).getStrokesCount() == gesture.getStrokesCount()) {
highScore = prediction.score;
gestureName = prediction.name;
}
}
// Do something with gestureName
}
Yes, are supported, at least from Android 2.3.3. But it is heavily imprecise. Check the second example.