I am trying to create a game in Android Studio that is similar to flappy bird. I'm following a YouTube tutorial as I am new to java and i believe I've followed it very closely.
My problem is that sometimes the game will terminate early, despite the gameOver conditions not being met. I have a function "updateAndDrawTubes" that draws the pipes to the canvas and also checks whether the player is touching the pipes. When the player does touch the pipe, the game finishes and goes to the gameOver screen, displaying the score. However, I am finding that even if there is no collision, sometimes the game will finish and go to the gameOver screen early.
My code is a mess, so apologies for that but any help would really be appreciated as I've exhausted all other options.
GameEngine.java
package com.example.mymainuniproj;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.Log;
import java.util.ArrayList;
import java.util.Random;
public class GameEngine {
BackgroundImage backgroundImage;
Player player;
static int gameState;
ArrayList<Tube> tubes;
Random random;
int score;
int scoringTube;
Paint scorePaint;
public GameEngine() {
backgroundImage = new BackgroundImage();
player = new Player();
//0-not started, 1-playing, 2-gameover
gameState = 0;
tubes = new ArrayList<>();
random = new Random();
for (int i = 0; i < AppConstants.numberOfTubes; i++) {
int tubeX = AppConstants.SCREEN_WIDTH + i * AppConstants.distanceBetweenTubes;
int topTubeOffsetY = AppConstants.minTubeOffsetY + random.nextInt(AppConstants.maxTubeOffsetY - AppConstants.minTubeOffsetY + 1);
Tube tube = new Tube(tubeX, topTubeOffsetY);
tubes.add(tube);
}
score = 0;
scoringTube = 0;
scorePaint = new Paint();
scorePaint.setColor(Color.RED);
scorePaint.setTextSize(100);
scorePaint.setTextAlign(Paint.Align.LEFT);
}
// this function is responsible for telling coins and enemies where to spawn
public void updateAndDrawTubes(Canvas canvas) {
if (gameState == 1) {
if ((tubes.get(scoringTube).getTubeX() < player.getPlayerX() + AppConstants.getBitmapBank().getPlayerWidth())
//if current tubes X value is < player X value
&& (tubes.get(scoringTube).getTopTubeOffsetY() > player.getPlayerY())
|| (tubes.get(scoringTube).getBottomTubeY() < (player.getPlayerY() + AppConstants.getBitmapBank().getPlayerHeight()))) {
//game over
gameState = 2;
Context context = AppConstants.gameActivityContext;
Intent intent = new Intent(context, GameOver.class);
intent.putExtra("score",score);
context.startActivity(intent);
((Activity)context).finish();
} else if (tubes.get(scoringTube).getTubeX() < player.getPlayerX() - AppConstants.getBitmapBank().getTubeWidth()) {
score++;
scoringTube++;
if (scoringTube > AppConstants.numberOfTubes - 1) {
scoringTube = 0;
}
}
// repeats twice, once for the enemy, once for the coin at each X coord
for (int i = 0; i < AppConstants.numberOfTubes; i++) {
//if tube(x) in the array's X value is less than tube width (which is 90px)
if (tubes.get(i).getTubeX() < -AppConstants.getBitmapBank().getTubeWidth()) {
tubes.get(i).setTubeX(tubes.get(i).getTubeX() + AppConstants.numberOfTubes * AppConstants.distanceBetweenTubes);
int topTubeOffsetY = AppConstants.minTubeOffsetY + random.nextInt(AppConstants.maxTubeOffsetY - AppConstants.minTubeOffsetY + 1);
tubes.get(i).setTopTubeOffsetY(topTubeOffsetY);
}
tubes.get(i).setTubeX(tubes.get(i).getTubeX() - AppConstants.tubeVelocity);
canvas.drawBitmap(AppConstants.getBitmapBank().getTubeTop(), tubes.get(i).getTubeX(), tubes.get(i).getTopTubeY(), null);
canvas.drawBitmap(AppConstants.getBitmapBank().getTubeBottom(), tubes.get(i).getTubeX(), tubes.get(i).getBottomTubeY(), null);
}
canvas.drawText("Score: " + score, 0, 110, scorePaint);
}
}
public void updateAndDrawBackgroundImage(Canvas canvas) {
backgroundImage.setX(backgroundImage.getX() - backgroundImage.getVelocity());
if (backgroundImage.getX() < -AppConstants.getBitmapBank().getBackgroundWidth()) {
backgroundImage.setX(0);
}
canvas.drawBitmap(AppConstants.getBitmapBank().getBackground(), backgroundImage.getX(), backgroundImage.getY(), null);
if (backgroundImage.getX() < -(AppConstants.getBitmapBank().getBackgroundWidth() - AppConstants.SCREEN_WIDTH)) {
canvas.drawBitmap(AppConstants.getBitmapBank().getBackground(), backgroundImage.getX() + AppConstants.getBitmapBank().getBackgroundWidth(), backgroundImage.getY(), null);
}
}
public void updateAndDrawPlayer(Canvas canvas) {
if (gameState == 1) {
if (player.getPlayerY() < (AppConstants.SCREEN_HEIGHT - AppConstants.getBitmapBank().getPlayerHeight()) || player.getVelocity() < 0) {
player.setVelocity(player.getVelocity() + AppConstants.gravity);
player.setPlayerY(player.getPlayerY() + player.getVelocity());
}
}
int currentFrame = player.getCurrentFrame();
canvas.drawBitmap(AppConstants.getBitmapBank().getPlayer(currentFrame), player.getPlayerX(), player.getPlayerY(), null);
currentFrame++;
if (currentFrame > player.maxFrame) {
currentFrame = 0;
}
player.setCurrentFrame(currentFrame);
}
}
GameOver.java
package com.example.mymainuniproj;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
public class GameOver extends AppCompatActivity {
TextView tvScore, tvPersonalBest;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.game_over);
int score = getIntent().getExtras().getInt("score");
SharedPreferences pref = getSharedPreferences("MyPref",0);
int scoreSP = pref.getInt("scoreSP",0);
SharedPreferences.Editor editor = pref.edit();
//update high score
if(score > scoreSP){
scoreSP = score;
editor.putInt("scoreSP",scoreSP);
editor.commit();
}
tvScore = findViewById(R.id.tvScore);
//tvPersonalBest = findViewById(R.id.tvPersonalScore);
tvScore.setText(""+score);
//tvPersonalBest.setText(""+scoreSP);*/
}
public void showToastOnClick(View view){
String text = "";
switch (view.getId()){
case R.id.buttonRestart: restart(); break;
}
Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
}
public void restart(){
Intent intent = new Intent(GameOver.this , GameActivity.class);
startActivity(intent);
finish();
}
public void exit(View view){
finish();
}
}
AppConstants.java
package com.example.mymainuniproj;
import android.content.Context;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.WindowManager;
public class AppConstants {
static BitmapBank bitmapBank; //bitmap object ref
static GameEngine gameEngine; //game engine object ref
static int SCREEN_WIDTH, SCREEN_HEIGHT;
static int gravity;
static int VELOCITY_WHEN_JUMPED;
static int gapBetweenTopAndBottomTubes;
static int numberOfTubes;
static int tubeVelocity;
static int minTubeOffsetY;
static int maxTubeOffsetY;
static int distanceBetweenTubes;
static Context gameActivityContext;
public static void initialization(Context context){
setScreenSize(context);
bitmapBank = new BitmapBank(context.getResources() );
setGameConstants();
gameEngine = new GameEngine();
}
public static void setGameConstants(){
AppConstants.gravity = 3;
AppConstants.VELOCITY_WHEN_JUMPED = -40;
gapBetweenTopAndBottomTubes = 800;
AppConstants.numberOfTubes = 2;
AppConstants.tubeVelocity = 12;
AppConstants.minTubeOffsetY = (int)(AppConstants.gapBetweenTopAndBottomTubes / 2.0);
AppConstants.maxTubeOffsetY = AppConstants.SCREEN_HEIGHT - AppConstants.minTubeOffsetY - AppConstants.gapBetweenTopAndBottomTubes;
AppConstants.distanceBetweenTubes = AppConstants.SCREEN_WIDTH * 3 / 4;
}
//return bitmapBank instance
public static BitmapBank getBitmapBank(){
return bitmapBank;
}
//return gameEngine instance
public static GameEngine getGameEngine(){
return gameEngine;
}
// get screen height and widtch
private static void setScreenSize(Context context) {
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
DisplayMetrics metrics = new DisplayMetrics();
display.getMetrics(metrics);
int width = metrics.widthPixels;
int height = metrics.heightPixels;
AppConstants.SCREEN_WIDTH = width;
AppConstants.SCREEN_HEIGHT = height;
}
}
This is my first time posting anywhere like this so please go easy on me if the format is bad or if I'm missing anything important!
If there is any other parts of the code that would help please just let me know and I'll try to be quick!
Thank you!
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I try to add a method that let a cell get alive if it's clicked by the left mouse button but I don't know how. I tried to add a MouseClickListener but I couldn't connect it to my code. I'm new to JavaFx so it's pretty hard to overview all the functions and how to use them. Every other function of my code works perfectly so far. I hope that anyone of you know how to implement this method. Here is my code:
import com.google.gson.reflect.TypeToken;
import javafx.application.Application;
import javafx.animation.AnimationTimer;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.control.Button;
import javafx.scene.input.MouseButton;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import com.google.gson.Gson;
import javax.swing.*;
public class conway extends Application {
private static final int width = 500;
private static final int height = 500;
private static final int cellsize = 10;
private static Gson gson = new Gson();
private static class Life{
private final int reihe;
private final int zeile;
private Boolean[][] rules;
private int[][] grid;
private Random random=new Random();
private final GraphicsContext graphics;
public Life(int reihe, int zeile, GraphicsContext graphics){
this.reihe =reihe;
this.zeile =zeile;
this.graphics=graphics;
grid=new int[reihe][zeile];
this.rules = new Boolean[][]{{false, false, false, true, false, false, false, false, false, false},
{false, false, true, true, false, false, false, false, false, false}};
}
public void init(){
for(int i = 0; i< reihe; i++){
for(int j = 0; j< zeile; j++){
grid[i][j]=random.nextInt(2);
}
}
draw();
}
private void draw(){
graphics.setFill(Color.LAVENDER);
graphics.fillRect(0,0,width,height);
for(int i=0; i<grid.length;i++){
for(int j=0; j<grid[i].length; j++){
if(grid[i][j]==1){
graphics.setFill(Color.gray(0.5,0.5));
graphics.fillRect(i*cellsize, j*cellsize,cellsize,cellsize);
graphics.setFill(Color.PURPLE);
graphics.fillRect((i*cellsize)+1, (j*cellsize)+1, cellsize-2, cellsize-2);
}
else{
graphics.setFill(Color.gray(0.5,0.5));
graphics.fillRect(i*cellsize,j*cellsize,cellsize, cellsize);
graphics.setFill(Color.WHITE);
graphics.fillRect((i*cellsize)+1,(j*cellsize)+1,cellsize-2,cellsize-2);
}
}
}
}
private int countNeighbors(int i, int j){
int sum=0;
int iStart=i==0?0:-1;
int iEnd=i==grid.length - 1 ? 0:1;
int jStart=j==0?0:-1;
int jEnd=j==grid[0].length - 1 ? 0:1;
for (int k=iStart; k<=iEnd;k++){
for(int l=jStart;l<=jEnd;l++){
sum+=grid[i+k][l+j];
}
}
sum-=grid[i][j];
return sum;
}
public void tick(){
int[][] next=new int[reihe][zeile];
for(int i = 0; i< reihe; i++){
for(int j = 0; j< zeile; j++){
int nachbar= countNeighbors(i,j);
if(rules[grid[i][j]][nachbar] == true){
next[i][j] = 1;
}
}
}
grid=next;
draw();
}
public void safe() throws IOException {
JsonArray to_safe = new JsonArray();
Path pfad = Paths.get("C:\\Users\\Frodo\\IdeaProjects\\gameoflife\\only_safe_file_for_now.json");
if(Files.exists(pfad) == false) {
Files.createFile(pfad);
}
for(int i = 0; i<grid.length; i++){
JsonArray helper = new JsonArray();
for (int j = 0; j<grid[0].length; j++){
helper.add(grid[i][j]);
}
to_safe.add(helper);
}
Files.writeString(pfad, gson.toJson(to_safe));
}
public void load() throws IOException{
int saved_grid[][];
Path pfad = Paths.get("C:\\Users\\Frodo\\IdeaProjects\\gameoflife\\only_safe_file_for_now.json");
if(Files.exists(pfad) == false) {
return;
}
else {
String array_string = Files.readString(pfad);
saved_grid = gson.fromJson(array_string, new TypeToken<int[][]>(){}.getType());
if (saved_grid.length == 0) {
return;
}
}
grid = saved_grid;
draw();
}
}
public static void main(String[] args) {
launch();
}
public void start(Stage primaryStage) {
VBox root = new VBox(10);
Scene scene = new Scene(root, width, height + 100);
final Canvas canvas = new Canvas(width, height);
final boolean[] leftclick = new boolean[1];
leftclick[0] =false;
scene.setOnMouseClicked(e->{
if(e.getButton().equals(MouseButton.PRIMARY)){
if(leftclick[0]){
leftclick[0] =false;
}
else leftclick[0] =true;
}
});
Button reset = new Button("Reset");
Button step = new Button("Step");
Button run = new Button("Run");
Button stop = new Button("Stop");
Button safe_state = new Button("Safe");
Button load_button = new Button("Load");
Button terminate = new Button("Terminate");
root.getChildren().addAll(canvas, new HBox(10, reset, step, run, stop, safe_state, load_button, terminate));
primaryStage.setScene(scene);
primaryStage.show();
int rows = (int) Math.floor(height / cellsize);
int cols = (int) Math.floor(width / cellsize);
GraphicsContext graphics = canvas.getGraphicsContext2D();
Life life = new Life(rows, cols, graphics);
life.init();
AnimationTimer Animation = new AnimationTimer() {
private long lastUpdate=0;
#Override
public void handle(long now) {
if ((now - lastUpdate) >= TimeUnit.MILLISECONDS.toNanos(100)) {
life.tick();
lastUpdate = now;
}
}
};
reset.setOnAction(l -> life.init());
run.setOnAction(l -> Animation.start());
step.setOnAction(l -> life.tick());
stop.setOnAction(l -> Animation.stop());
safe_state.setOnAction(l-> {
try {
life.safe();
} catch (IOException e) {
e.printStackTrace();
}
});
load_button.setOnAction(l -> {
try {
life.load();
} catch (IOException e) {
e.printStackTrace();
}
});
terminate.setOnAction(l -> {
Stage stage = (Stage) terminate.getScene().getWindow();
stage.close();
});
}
}
Something in this direction should do the trick:
canvas.addEventHandler(MouseEvent.MOUSE_CLICKED,
new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent t) {
// is left click
if (t == MouseEvent.BUTTON1) {
grid[rows][cols] = 1;
draw();
}
}
});
How to make the word cloud image of the image.
Like this original Above to output
I am trying with the image to Ascii using https://github.com/bachors/Android-Img2Ascii
TextView textAsc=(TextView)findViewById(R.id.textAsc);
Bitmap image = BitmapFactory.decodeResource(getResources(), R.drawable.step0001);
// Bitmap image = BitmapFactory.decodeFile(filename);
new Img2Ascii()
.bitmap(image)
.quality(4) // 1 - 5
.color(true)
.convert(new Img2Ascii.Listener() {
#Override
public void onProgress(int percentage) {
textAsc.setText(String.valueOf(percentage) + " %");
}
#Override
public void onResponse(Spannable text) {
textAsc.setText(text);
}
});
img2ascii.java
package com.bachors.img2ascii;
import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.AsyncTask;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import static java.lang.Math.round;
/**
* Created by Bachors on 10/31/2017.
* https://github.com/bachors/Android-Img2Ascii
*/
public class Img2Ascii {
private String[] chars = {"#", "#", "+", "\\", ";", ":", ",", ".", "`", " "};
private Bitmap rgbImage;
private Boolean color = false;
private int quality = 3;
private int qualityColor = 6;
private Spannable response;
private Listener listener;
List<String> list = new ArrayList<String>();
public Img2Ascii(){
}
public Img2Ascii bitmap(Bitmap rgbImage){
this.rgbImage = rgbImage;
return this;
}
public Img2Ascii quality(int quality){
this.quality = quality;
return this;
}
public Img2Ascii color(Boolean color){
this.color = color;
return this;
}
public void convert(Listener listener) {
this.listener = listener;
new InstaApi().execute();
}
#SuppressLint("StaticFieldLeak")
private class InstaApi extends AsyncTask<String, Integer, Void> {
private InstaApi(){
}
#Override
protected void onPreExecute() {
super.onPreExecute();
list.add("Cool");
list.add("G");
list.add("S");
list.add("L");
}
#Override
protected Void doInBackground(String... arg0) {
if(color) {
quality = quality + qualityColor;
if (quality > 5 + qualityColor || quality < 1 + qualityColor)
quality = 3 + qualityColor;
}else{
if (quality > 5 || quality < 1)
quality = 3;
}
String tx;
SpannableStringBuilder span = new SpannableStringBuilder();
int width = rgbImage.getWidth();
int height = rgbImage.getHeight();
int i = 0;
for (int y = 0; y < height; y = y + quality) {
for (int x = 0; x < width; x = x + quality) {
int pixel = rgbImage.getPixel(x, y);
int red = Color.red(pixel);
int green = Color.green(pixel);
int blue = Color.blue(pixel);
if(color) {
Random randomizer = new Random();
String random =list.get(randomizer.nextInt(list.size()));
tx = random;
span.append(tx);
span.setSpan(new ForegroundColorSpan(Color.rgb(red, green, blue)), i, i + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}else {
int brightness = red + green + blue;
brightness = round(brightness / (765 / (chars.length - 1)));
tx = chars[brightness];
span.append(tx);
}
i++;
}
tx = "\n";
span.append(tx);
publishProgress(y, height);
i++;
if(isCancelled()) break;
}
response = span;
return null;
}
protected void onProgressUpdate(Integer... progress) {
int current = progress[0];
int total = progress[1];
int percentage = 100 * current / total;
listener.onProgress(percentage);
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
listener.onResponse(response);
}
}
public interface Listener {
void onProgress(int percentage);
void onResponse(Spannable response);
}
}
I made a minesweeper game in Java using Swing, but when i run it, JFrame doesn't pop up? (No errors)
It runs, but no window shows up. Tried to debug with no success.
I really appreciate your help :)
Note that in class GameBoard:
imgs = new Image[13]; //Number of images used
//Loading images, used later
for (int i = 0; i < 13; i++) {
imgs[i] = (new ImageIcon(i + ".png")).getImage();
}
These lines load numbers representing images (13 images), created by me, and these imgs are loadid depending on the mouseadapter.
This is the MineSweeper class with the main method:
package minesweeper;
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
public class MineSweeper extends JFrame {
public JLabel label;
public MineSweeper(){
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(600, 600);
this.setLocationRelativeTo(null);
this.setTitle("Minesweeper");
label = new JLabel("");
this.add(label, BorderLayout.SOUTH);
GameBoard game = new GameBoard(label);
this.add(game);
setResizable(false);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
MineSweeper jf = new MineSweeper();
jf.setVisible(true);
}
});
}
}
An this is the GameBoard class:
package minesweeper;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Random;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class GameBoard extends JPanel {
//Adding constant variables
private final int SIZE_OF_CELL = 20;
private static final int NUM_OF_ROWS = 20;
private static final int NUM_OF_CL = 20;
private final int SIZE_OF_FIELD = NUM_OF_ROWS * NUM_OF_CL;
//Adding other variables
private int NUM_OF_MINES_LEFT;
private Image[] imgs;
private static int[][] gameboard;
public static int mines = 40;
private int all_cells;
private static JLabel label;
boolean gamestarted = true; // Game is in progress, already started
//Constructor 1 parameter
public GameBoard(JLabel inputlabel) {
this.label = inputlabel;
imgs = new Image[13]; //Number of images used
//Loading images, used later
for (int i = 0; i < 13; i++) {
imgs[i] = (new ImageIcon(i + ".png")).getImage();
}
setDoubleBuffered(true);
addMouseListener(new Manager());
StartNewGame();
}
//Find mines around cell[i][j]
public static int FindMines(int ro, int co){
int cnt=0;
for(int y=-1;y<=1;y++){
for(int x = -1; x<=1;x++){
if(x==0 && y ==0) continue;
if(ro+y<0) continue;
if(co+x<0) continue;
if(gameboard[ro+y][co+x]==19) cnt++;
}
}
return cnt;
}
public static void StartNewGame(){
//NUM_OF_MINES_LEFT = 40; // Default value for number of mines is 30
gameboard = new int[20][20];
int minesleft=mines;
int row,col;
// int mines = NUM_OF_MINES_LEFT;
Random rng=new Random();
label.setText(Integer.toString(minesleft));
//initialize mine field
for(int i=0;i<20;i++){
for (int j=0;j<20;j++){
gameboard[i][j]=10;//default value is 10 -> its covered
}
}
//Set mines in random positions
while (mines>0){
row=rng.nextInt(NUM_OF_ROWS);
col=rng.nextInt(NUM_OF_CL);
if ((gameboard[row][col])!=19){
gameboard[row][col]+=9;;
minesleft--;
}
}
//Set numbers
for(int i=0;i<20;i++){
for (int j=0;j<20;j++){
if(gameboard[i][j]==19) gameboard[i][j]=19;
if(gameboard[i][j]==10){
gameboard[i][j]+= FindMines(i,j);
}
}
}
}
//public int FindEmptyCells(){
//}
#Override
public void paintComponent(Graphics grap){
int gamewon=0;
int[][] temp = new int[20][20];
for(int i=0;i<20;i++){
for(int j=0;j<20;j++){
temp[i][j]=gameboard[i][j];
if(gamestarted && temp[i][j]==9) gamestarted=false;
if(gamestarted == false){
if(temp[i][j]==19){
temp[i][j]= 9;
}else if(temp[i][j]==29){//10+11 for mark
temp[i][j]=11;
}else if(temp[i][j]>9){
temp[i][j]=10;
}
}else{
if (temp[i][j] > 19)
temp[i][j] = 11;
else if (temp[i][j] > 9) {
temp[i][j] = 10;
gamewon=1;
}
}
int toload= temp[i][j];
grap.drawImage(imgs[toload],j*15,i*15,this);
}
}
if(gamestarted==true && gamewon==0){
gamestarted=false;
label.setText("You won!");
}else if(gamestarted==false){
label.setText("You Lost!");
}
}
class Manager extends MouseAdapter{
#Override
public void mousePressed(MouseEvent ev){
boolean newpaint = false;
//Get event coordinates
int x= ev.getX();
int y= ev.getY();
int hit_cl= x / 15;
int hit_row= y/ 15;
if(gamestarted==false){
StartNewGame();
repaint();
}
if( (x < 20 * 15) && (y < 20 * 15) ){
if(ev.getButton() == MouseEvent.BUTTON3){
if(gameboard[hit_cl][hit_row] > 9){
newpaint=true;
if(gameboard[hit_cl][hit_row] <= 19){
if(mines > 0){
mines--;
String show=Integer.toString(mines);
gameboard[hit_cl][hit_row]+=11;
label.setText(show);
}else{
label.setText("Marks: 0");
}
}else{
mines++;
String show=Integer.toString(mines);
label.setText(show);
gameboard[hit_cl][hit_row]-=11;
}
}
}else{
if(gameboard[hit_cl][hit_row] > 19){
return;
}
if((gameboard[hit_cl][hit_row] > 9) && (gameboard[hit_cl]
[hit_row] <29)){
newpaint=true;
gameboard[hit_cl][hit_row]-=10;
if(gameboard[hit_cl][hit_row] == 9) gamestarted=false;
//if(gameboard[hit_cl][hit_row] == 10); //find_empty();
}
}
if(newpaint==true) repaint();
}
}
}
}
What did you do to debug? :)
The most obvious reason for the program to run forever is that it never leaves a loop.
while (mines>0){
row=rng.nextInt(NUM_OF_ROWS);
col=rng.nextInt(NUM_OF_CL);
if ((gameboard[row][col])!=19){
gameboard[row][col]+=9;;
minesleft--;
}
}
This part of your StartNewGame() method (GameBoard class) is causing an endless loop, mines variable is never updated inside the loop.
Giving a fast look to your code i can note some bad practices, for example :
You should not control the game state or setting labels text inside
paintComponent() method. This method is called automatically, and it
should only paint all the components. All the "logic" inside it
could slow down your program, because you can not control how many
times the method gets called (of course you can force the method to
be called with repaint() method, for example).
You should follow java naming conventions
Hope this helps :)
I've made an android apps about visualize spectrum frequency from recording sound. I'm using package from www.netlib.org/fftpack/jfftpack.tgz to perform FFT. We know that Each line of spectrum handle frequency from this formula : "((frequency_sample/2)/samples)". Its easy to see the first, second, and third spectrum that occurs. But, above fifth spectrum its hard to determine which spectrum it is.
I want to know the specific frequency (for example freq 200Hz) is occur or not and show it as toast or something like that. Is there any good source library I could refer to do this?
Thanks :)
package com.example.agita.stethoscopeandroid;
/**
* Created by Agita on 5/21/2015.
*/
import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import ca.uol.aig.fftpack.RealDoubleFFT;
public class RekamActivity extends Activity implements OnClickListener {
Button startRecordingButton, stopRecordingButton;
TextView statusText;
File recordingFile;
boolean isRecording = false;
int frequency = 8000;
int channelConfiguration = AudioFormat.CHANNEL_CONFIGURATION_MONO;
int audioEncoding = AudioFormat.ENCODING_PCM_16BIT;
private RealDoubleFFT transformer;
int blockSize = 256;
RecordAudio recordTask;
ImageView imageView;
Bitmap bitmap;
Canvas canvas;
Paint paint;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.rekam);
statusText = (TextView) this.findViewById(R.id.StatusTextView);
startRecordingButton = (Button) this .findViewById(R.id.StartRecordingButton);
stopRecordingButton = (Button) this .findViewById(R.id.StopRecordingButton);
startRecordingButton.setOnClickListener(this);
stopRecordingButton.setOnClickListener(this);
stopRecordingButton.setEnabled(false);
transformer = new RealDoubleFFT(blockSize);
imageView = (ImageView) this.findViewById(R.id.ImageView01);
bitmap = Bitmap.createBitmap(256, 100, Bitmap.Config.ARGB_8888);
canvas = new Canvas(bitmap);
paint = new Paint();
paint.setColor(Color.GREEN);
imageView.setImageBitmap(bitmap);
String recordedAudioFile = getRecoredAudioFile();
File path = new File(Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/Datarekaman/");
path.mkdirs();
try {
recordingFile = File.createTempFile("recording"+recordedAudioFile, ".wav", path);
} catch (IOException e) {
throw new RuntimeException("Couldn't create file on SD card", e);
}
}
private String getRecoredAudioFile() {
String returnAudio;
java.util.Date date= new java.util.Date();
returnAudio = new SimpleDateFormat("yyyyMMdd_HHmmss").format(date.getTime());
return returnAudio;
}
public void onClick(View v) {
if (v == startRecordingButton) {
record();
} else if (v == stopRecordingButton) {
stopRecording();
}
}
public void record() {
startRecordingButton.setEnabled(false);
stopRecordingButton.setEnabled(true);
recordTask = new RecordAudio();
recordTask.execute();
}
public void stopRecording() {
isRecording = false;
}
private class RecordAudio extends AsyncTask<Void, double[], Void> {
#Override
protected Void doInBackground(Void... params) {
isRecording = true;
try {
DataOutputStream dos = new DataOutputStream(
new BufferedOutputStream(new FileOutputStream(
recordingFile)));
int bufferSize = AudioRecord.getMinBufferSize(frequency,
channelConfiguration, audioEncoding);
AudioRecord audioRecord = new AudioRecord(
MediaRecorder.AudioSource.MIC, frequency,
channelConfiguration, audioEncoding, bufferSize);
short[] buffer = new short[blockSize];
double[] toTransform = new double[blockSize];
audioRecord.startRecording();
while (isRecording) {
int bufferReadResult = audioRecord.read(buffer, 0,
blockSize);
for (int i = 0; i < blockSize && i < bufferReadResult; i++) {
dos.writeShort(buffer[i]);
toTransform[i] = (double) buffer[i]/32768.0;
}
transformer.ft(toTransform);
publishProgress(toTransform);
}
audioRecord.stop();
dos.close();
} catch (Throwable t) {
Log.e("AudioRecord", "Recording Failed");
}
return null;
}
/*protected void onProgressUpdate(Integer... progress) {
statusText.setText(progress[0].toString());
}*/
protected void onProgressUpdate (double[]... toTransform) {
canvas.drawColor(Color.BLACK);
for (int i = 0; i < toTransform[0].length; i++) {
int x;
x = i;
int downy = (int) (100 - (toTransform[0][i] * 10));
int upy = 100;
//canvas.drawRect(x * 3, downy, x * 3 + 4, upy, paint);
canvas.drawLine(x, downy, x, upy, paint);
imageView.invalidate();
}
}
protected void onPostExecute(Void result) {
startRecordingButton.setEnabled(true);
stopRecordingButton.setEnabled(false);
}
}
}
In mainActivity I made timer,which you click in button each 3 seconds show value of available memory and write in array.And after writting finished, the second button "see chart" stay clickable,we click and transwer to the next activity(second class).
In second class creates canvas with lines, and must be create chart which can show available memory in time. But I can't carry array in first class to second class.
I need carry array "Masiv " at method run() to my second class.
First class
package foxstrot.p3;
import android.annotation.TargetApi;
import android.app.ActivityManager;
import android.content.Intent;
import android.graphics.Canvas;
import android.os.Build;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;
public class MainActivity extends ActionBarActivity {
private Timer timer;
private MyTimerTask myTimerTask;
private Intent i;
long[] Masiv = new long[50];
int k;
private long freeMemory;
private Canvas canvas;
private G.DrawView d;
private int t = 0;
private long j;
private TextView tv;
private long r;
private Button b2;
MyTimerTask myTimerTask1 = new MyTimerTask();
int ii = 0;
ArrayList <Integer> AL = new ArrayList<Integer>() ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.textView);
b2 = (Button)findViewById(R.id.b2);
b2.setClickable(false);
//myTimerTask1.getMas();
//actManager.getMemoryInfo(memInfo);
//freeMemory = memInfo.availMem;
//tv.setText("freeMemory: " + freeMemory);
//Canvas canvas = new Canvas();
/*G g = new G();
G.DrawView d = g.new DrawView(this);*/
}
public void start(View v) {
timer = new Timer();
myTimerTask = new MyTimerTask();
timer.schedule(myTimerTask, 3000, 3000);
}
public void chart(View v){
i = new Intent(this,G.class);
startActivity(i);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
class MyTimerTask extends TimerTask {
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
long getFreeMemory(){
ActivityManager actManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
ActivityManager.MemoryInfo memInfo = new ActivityManager.MemoryInfo();
actManager.getMemoryInfo(memInfo);
freeMemory = memInfo.availMem;
return freeMemory;
}
runOnUiThread(new Runnable() {
#Override
public void run() {
r = getFreeMemory();
k = (int)r/100000;
//setMas(k)
AL.add(k);
tv.setText("Free memory : " + k);
t++;
if(t == 5){
cancel();
b2.setClickable(true);
}
}
});
}
public void setMas(long p){
//if(ii==5){}
//Log.d("LOG_TAG", "SetMy_Array[0]: " + k + "SetMy_Array[1]: " + k);
ii++;
}
/*public long getMas(){
Log.d("LOG_TAG", "GetMy_Array[0]: " + k + "GetMy_Array[1]: " + k);
return k;
}*/
}
}
Second class
package foxstrot.p3;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;
/**
* Created by Admin on 14.04.2015.
*/
public class G extends Activity {
int ii;
private long[] My_Array ;
private MainActivity mainActivity = new MainActivity();
//private MainActivity.MyTimerTask myTimerTask = mainActivity.new MyTimerTask();
//private long[] G_mas = myTimerTask.getMas();
ArrayList<Integer> AL = new ArrayList<Integer>() ;
Intent intent;
private boolean drawGraph = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new DrawView(this));
intent = getIntent();
//AL = intent.getIntegerArrayListExtra("Joker");
//Log.d("LOG_TAG","Al: " + AL.get(0) + "AL: " + AL.get(0));
//My_Array = myTimerTask.getMas();
//Log.d("LOG_TAG","My_Array[0]: " + myTimerTask.getMas() + "My_Array[1]: " + myTimerTask.getMas());
/*for(int i=0;i<G_mas.length;i++){
max = Math.max(max,G_mas[i]);
min = G_mas[i];
min = Math.min(min, G_mas[i]);
}*/
}
public class DrawView extends View{
Paint p;
Rect rect;
int uN = 0;
int uT = 0;
int y1 = 0;
int x1 = 0;
int n = 2000;
int t = 0;
public DrawView(Context context){
super(context);
p = new Paint();
rect = new Rect();
}
#Override
public void onDraw(Canvas canvas) {
final int cHeight = canvas.getHeight();
final int cWidth = canvas.getWidth();
Paint paint = new Paint();
paint.setColor(Color.WHITE);
canvas.drawPaint(paint);
paint.setColor(Color.BLACK);
paint.setTextSize(30);
canvas.drawLine(80,0,80,cHeight-60,paint);
canvas.drawLine(80,cHeight-60,cWidth,cHeight-60,paint);
for(int i=0;i<50;i++){
canvas.drawText(uT + "" , 10 , 25 + y1, paint);
uT = uT + 3;
y1 = y1 + (cHeight/50);
}
for(int i=0;i<9;i++){
canvas.drawText("|"+ uN, 75 + x1, cHeight - 25 , paint);
uN = uN + 1000;
x1 = x1 + (cWidth/9)-25;
/*int joker = 10;
canvas.drawPoint(20+ joker,20,paint);
joker = joker + 40;*/
}
paint.setStrokeWidth(10);
/*for(int i=0;i<My_Array.length;i++){
long xc = (My_Array[i] * (cWidth-80)) / 8000 ;
int yc = (t * (cHeight-60))/147;
t = t + 3;
canvas.drawPoint(xc, yc, paint);
Log.d("LOG_TAG","xc: " + xc + "yc: " + yc);
}*/
/*Paint paint2 = new Paint();
paint2.setColor(Color.RED);
canvas.drawPoint(cWidth, cHeight, paint2);*/
}
}
}
Just use putExtra() and getLongArrayExtra().
Documentation: putExtra(String name, long[] value) and getLongArrayExtra(String name)
In MainActivity.java:
public void chart(View v){
i = new Intent(this,G.class);
i.putExtra("foxstrot.p3.masiv", Masiv);
startActivity(i);
}
In G.java:
private boolean drawGraph = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new DrawView(this));
intent = getIntent();
My_Array = intent.getLongArrayExtra("foxstrot.p3.masiv");
//...................