iam newbie in this so i will ask straightly and if smb can help me that would be appreciated. Iam trying to make a Sudoku Game in BlueJ and until now i havent got any help from google searches and staff so iam posting here.
I need my sudoku firstly to be a random puzzle when pressing a button to start new.
Then the main concept and correct me if iam wrong is to built one random table which will be the solution for the user and one table where user can see 3 numbers only from the table and pick the other. With Comparing of 2 tables, users and solution the programm can see if the user has it correct.
Until now i have this code.
import java.awt.*;
import javax.swing.*;
import java.util.*;
public class MyFrame extends Frame
{
private double[] data;
private Button avgButton,minButton,maxButton,rndomButton;
private Button quit;
public MyFrame(String title)
{
super(title);
resize(200,200);
setResizable(false);
setLayout(new GridLayout(3,2));
quit=new Button("QUIT");
rndomButton=new Button("RANDOM");
add(rndomButton);
add(quit);
}
public int Array()
{
Random rand = new Random();
int n = rand.nextInt(3) + 1;
int y = rand.nextInt(2) + 1;
int i=0;
int j=0;
int value;
int[][] board = new int[3][3];
value=board[0][0];
int z=board[0][0];
for(i=0;i<3;i++)
{
do{
board[i][0]=n;
}while (board[i][0]!=board[i-1][0]&&board[i][0]!=board[i-2][0]);
}
for(j=0;j<3;j++)
{
do{
board[0][j]=n;
}while (board[0][j]!=board[0][j-1]&&board[0][j]!=board[0][j-2]);
}
for(i=1;i<3;i++)
{
for(j=1;j<3;j++)
{
do{
board[i][j]=n;
}while (board[i][j]!=board[i-1][j]&&board[i][j]!=board[i-2][j]&&board[i][j]!=board[i][j-1]&&board[i][j]!=board[i][j-2]);
}
}
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
z=board[i][j];
}
}
return z;
}
public boolean action(Event evt,Object arg)
{
if(evt.target.equals(rndomButton))
message("Array: "+Array());
else
if(evt.target.equals(quit))
System.exit(0);
return true;
}
}
I dont know if it is correct because when i try to return z value its just a window pops up with nothing in there.
Note if i get return z in lasts for i get an error on bluej.
Sorry for my programming skills.
I hope u can help me or at least recommend me some links to look at.
Thanks in advance.
It's possible you've jumped into your coding a little too soon. It appears that you need to better define your approach to the problem. First, think about how you would solve it by hand. Break that down into steps, and write those steps down. Then, make your code model your solution step by step.
For example, if you think about building your board one row at a time, then you would write down something like, "For the first row, take 1, 2, 3, and rearrange them in random order..." If you think. instead, about building your board one digit at a time, you might write, "Place a 1 in a random location in the first row. Place a 1 in a random location in the second row, but avoid a conflict with the first row. Place a 1 in the only remaining column in the third row.
With your second digit, you'll encounter more constraints-- instead of just selecting any column at random from the first row, you'll need to select randomly from an available column.
1 2 .
. 1 .
. . 1
In the example above, when placing a 2 in your second row, how do you determine which is available? (One choice leads to a solution, the other to a dead-end). Once you're able to articulate the steps you would take to solve the problem by hand, writing the code becomes much easier and the small pieces you may get stuck on become easier to address.
Related
So well I tried creating a simpler Minesweeper game and I encountered one main problem..
I am not able to count the number of bombs and print it in a JTextField
Any ideas as to how to count these as I'm setting a random value to check whether they are a bomb
Tried counting it in the ActionListener but the bombs were counted only after the button was clicked.
if(e.getSource()==b[i][j])
{
b[i][j].setVisible(false);
tf[i][j].setVisible(true);
int r1 = rand.nextInt(6);
if(r1>1)
{
tf[i][j].setText("Safe");
tf[i][j].setBackground(Color.green);
}
else
{ count++;
tf[i][j].setText("Bomb");
tf[i][j].setBackground(Color.red);
f.setVisible(false);
restart.setVisible(true);
}
}
As I understand you decide if the the tile will be a bomb in the run-time using a random generator. Doing this you can't really know how many mines are in your game. I think you should decide the number of mines at the beginning of the game and randomly place them to your game board (you can choose the number according to a difficulty level).
EDIT
You can create a list with some random points that contain the mines
int numOfMines = 10;
int rows=5,columns=5;
ArrayList listWithMines = new ArrayList();
while(listWithMines.size()<numOfMines) {
int randRow = random.nextInt(rows);
int randCol = random.nextInt(columns);
Point point = new Point(randRow, randCol);
if(listWithMines.contains(point))
continue;
else
listWithMines.add(point);
}
This list now contains the Points that have the mines.
You can check if Point(x,y) has a mine like this:
if(listWithMines.contains(new Point(1, 2))) {...}
Instead of a list you can use a 2D array, store a boolean value (or int if you store more states) and make a loop until you place 10 mines. You should keep a counter(placedMines like the list.size()) of the mines you placed and make sure you don't add a mine to a tile that has already a mine and you increase the counter(placedMines) until it reaches the numOfMines.
I currently have java homework that I would appreciate some help with. We are to calculate a team record scenario.
We are given the following numbers:
Team1 Points
{23,45,65,20}
Opponent Points
{20,30,20,18}
I threw these into an array. I also created a public boolean. Basically, you are to pull these points from the array to the boolean? And let the boolean decide which team won? Obviously team1 has won, but we are supposed to let the computer decide, not the human.
Here is my code:
public class TeamScore {
public static boolean Winner(int team1Points, int opponentPoints) {
if (team1Points > opponentPoints) {
return true;
} else {
return false;
}
}
public static void main(String[] args) {
// Scanner in = new Scanner(System.in);
int[] team1Points = { 23, 45, 65, 20 };
int[] opponentPoints = { 20, 30, 20, 18 };
int team1 = 1;
int opponent = 1;
for (int i = 0; i < 5; i++) {
if (Winner(team1Points[i], opponentPoints[1])) {
team1 += 1;
} else {
opponent += 1;
}
}
for (int i = 0; i < 5; i++) {
if (team1 > 0 && opponent == 0) {
System.out.println("Team 1 has the perfect record!");
} else {
System.out.println("Win" + Arrays.toString(team1Points));
System.out.println("Loss" + Arrays.toString(opponentPoints));
}
}
}
Could anyone possibly help me? I am currently in programming II, but I did not have the best teacher in programming I. Any help would be appreciated!
EDIT:
I do not think this is a duplicate question because I already can fix it by changing the variable i-->1. My problem is that the computer thinks that team1 has already won regardless of the score.
When I run the code I am getting an java.lang.ArrayIndexOutOfBoundsException error. However when I change team1Points[i] to team1Points[1] then it goes okay and tells me that "Team 1 has the perfect record!". However, if I change some of the array values for team1Points to be less than opponentPoints then it still says "Team 1 has the perfect record!".
Not sure why you have a method Winner (also as Kevin said, it should be winner because of naming conventions) which turns ´(a > b)´ into a large if-statement. Similar stuff appear elsewhere in your code.
Your variables ´team1, opponent = 1´ inexplicably start with the value 1, am I to understand this as a way for your code to imply to a reader that both teams initialize at a win? Using 0 would probably make more sense.
Your game ought to crash from an indexoutofboundsexception at ´team1Points[i]´, as you have arrays of length 4, but your loops runs 5 times (the currently used range is [0-4], inclusive). Changing your loops to i=1 won't help, as the issue is that you eventually encounter team1Points[4] due to the i < 5 statement.
I don't know what game you are modelling or how it works, but the comparison ´Winner(team1Points[i],opponentPoints[1])´ looks like a blatant error to me (you always look at the opponents score for their second round).
Why are you printing your results 5 times? If you want to print the first message only when team1 won all rounds and the point for each round otherwise, you would need to use the loops counter as an index to the arrays in second case. First case should break loop so its not written five times, in addition you don't need to check team1>0 && opponent==0 as it's enough to only check if ´opponent==0´ (speaking of this conditional, it only works if you initialize the variables at 0 as I mentioned before). You could have checked if team1 equals size of the array instead, but imo thats more of a hassle than opponent==0.
Lastly, please fix your indenting. use the preview system so you can make double sure before posting.
Edit: Kevin also brings up a good point that you should be using the length of the array in your loops second statement.
I have a simple educational kids game with 7 questions. One imageView and four buttons for each question, the user must match the correct answer(button) with what is shown in the image view. I want the images(questions) to be random every game but never repeat a question during a game until all 7 have been asked. I am only using 3 images as of now just to get it working.
Option 1
int[] res = {R.drawable.img1, R.drawable.img2, R.drawable.img3};
Method
private void randomImage() {
Random rand = new Random();
int rndInt = rand.nextInt(res .length);
imgView.setImageDrawable(getResources().getDrawable(res[rndInt]));
}
Option 2
private ArrayList<Integer> res1 = new ArrayList<Integer>();
res1.add(R.drawable.img1);
res1.add(R.drawable.img2);
res1.add(R.drawable.img3);
Method
private void randomImage1() {
Collections.shuffle(res1);
for(int i=0;i<res1.size();i++){
imgView.setImageResource(res1.get(i));
}
}
Both of these work for randomizing, but I am having a little trouble figuring out how to check if an image has already appeared and to correct it if it had.
In fact I'm not really quite sure where to start. Any help would be appreciated.
If you dont want to see repeated items from array then use shuffleArray() like this example and for a list use shuffle(list) like this example2
I received the task of simulating a lottery draw in java. The program skeleton yields the method generateOneDraw, which creates 6 random numbers between 1 and 49
static int[] generateOneDraw() {
int numbers[] = new int[NUMBER_OF_ELEMENT_PER_DRAW];
for(int i=0; i<numbers.length; ++i) {
int nextNumber;
do {
nextNumber = generateNextRandomNumber();
} while(numberIsInArray(nextNumber, numbers));
numbers[i] = nextNumber;
}
return numbers;
}
We are then required to implement a function that simulates the lottery draw over 5 weeks and stores them in the variable draws. I believe this should be done over a two-dimensional array. Am I right in this way of thinking? Any pointers on implementing it would be greatly appreciated.
static void generateAllDraws()
Thanks in advance.
EDIT: Nevermind, I did it with a simple two dimensional array and it worked.
Since this seems like home work, I will not go into much detail but you can either:
Create a 2 dimensional list, as per your initial reasoning;
Create a Draw class which represents a lotto draw, and create multiple instances of this class. Each Draw class could have a Date which would denote when did the draw take place.
Both approaches should work, the second approach is a little more object oriented.
I created two methods for my Bingo Game in Java. One method creates a new board which populates the Bingo Board with integers according to the Bingo rule (1-75). My second method generates random numbers with a range of 1 - 75.
public static int drawNum(){
Random rand = new Random();
int num = rand.nextInt(75)+1;
return num;
}
public static void bingoCard(){
int [][]card=new int [5][5];
ArrayList<Integer> alreadyUsed = new ArrayList<Integer>();
boolean valid = false;
int tmp = 0;
for(int i = 0; i <= 4; i++){
for(int row = 0; row < card.length; row++){
while(!valid){
tmp = (int)(Math.random() * 15) + 1 + 15 * i;
if(!alreadyUsed.contains(tmp)){
valid = true;
alreadyUsed.add(tmp);
}
}
card[row][i] = tmp;
valid = false;
}
}
card[2][2] = 0;
//create array to make title.
String title []={"B","I","N","G","O"};
for(int i=0;i<title.length;i++){
System.out.print(title[i]+ "\t");
}
System.out.println();
for(int row=0;row<card.length;row++){
for(int col=0;col<card[row].length;col++){
System.out.print(card[row][col]+ "\t");
}
System.out.println();
}
}
What I need help with is, how do I check whether or not the drawNum() method corresponds to any values stored inside my bingoCard() array? If so, print out a new array with the integers filled in. If the condition is met for a bingo, then you win.
I hope I don't make it sound like I want you to do it for me, but I am confused as to how to start coding that part. Thank you.
This my recommendation - Learn Object Oriented Programming immediately
I see you are using objects provided in the JDK, so why not learn to make your own?
Make two classes with the following methods (-) and members (+) (PS. This is not a formal way to document code)
BingoCard
+list of numbers on card
-reset() : gets new numbers for this card
-test(BingoDrawer) : Tests to see if this card won on this drawing
-toString() : returns a String representation of this card
BingoDrawer
+list of numbers drawn
-reset() : draws new numbers
-hasNumber(int number) : tests if this number was drawn
-toString() : returns a String representation of this drawing
One more suggestions
Instead of keeping track of what you used, keep track of what you have not used, it will make things much easier because you can just choose stuff from that list randomly. Unlike your current action which is choosing (a logical number) from thin air and hoping (which causes issues) it is not a collision
If you follow my recommendation you can write code like this
public static void main(String[] args) {
BingoCard bc = new BingoCard();
BingoDrawer bd = new BingoDrawer();
while(thePlayerWantsToPlay()) { //function to be defined by you
bc.reset();
bd.reset();
System.out.println(bc);
System.out.println(bd);
System.out.println(bc.test(bd));
}
}
You can take it a step further and make a BingoGame class and do what I did in main there and just create an instance of BingoGame and call some start method on the object.
For checking if you have the number in your board, read through the board in a similar manner as you do for the already_used numbers, except with the number the user just entered.
The conditions for the user to win should be checked after the board has another number guessed.
There are a few ways to do this, a simple one would be to iterate over every possible pattern that could win, checking to see if there are tokens there.
All of this would be in a loop, that goes a little like this:
Set up board via user entering numbers.
Start loop
set either a timer to wait for, or wait for a keypress (so the game doesn't just play really fast)
Get random number
Possibly add to board
Check if winner
if winner, break the loop and do something else.
Print the new board out.
(end of loop)
If they got here, that could mean they won!
Wait to exit
You can just write it out as pseudo-code and fill in the methods after that. It usually helps to work on these things in a top-down fashion. So, for bingo you might have:
board = generateBoard();
while (!bingoFound(board)) {
number = drawNumber();
board = stampNumbers(board, number);
}
If that makes sense, you can go a step deeper and define each method. For example, bingoFound might look like:
public boolean bingoFound(int[][] board) {
boolean wasFound = bingoRowFound(board)
|| bingoColFound(board)
|| bingoDiagonalFound(board);
return wasFound;
}
Again, I've defined everything in (mostly) pseudo-code. If this looks ok, you can move a step deeper. Let's define the bingoRowFound method.
public boolean bingoRowFound(int[][] board) {
for (int row = 0; row < NUM_ROWS; row++) {
boolean rowIsABingo = true;
for (int col = 0; col < NUM_COLS; col++) {
// We have to check that everything up until this point has
// been marked off. I am using -1 to indicate that a spot has
// been marked.
rowIsABingo = rowIsABingo && board[row][col] == -1;
}
if (rowIsABingo) { return rowIsABingo; }
}
return false; // If we didn't find a bingo, return false.
}
Some of the methods (like drawNumber) will be really easy to implement. Others, like looking for a diagonal bingo might be a bit more difficult.
Feb 12 2014 Update:
Retracted code, since this was a college course assignment, and I want to prevent people just copying the code. I almost got in trouble for being accused of sharing code (which is a nono in assignments) when another student lifted my code from my Github repo and sent it in as their own.
There were two classes, one main class and a class to hold my methods and constructors.
BINGOFINAL.java was my main class.
Bingo_Card.java held my constructor and methods.
If you want to run this, make sure you create a new project called BINGOFINAL, and put Bingo_Card.java into that same */src/ extension.