I don't know what to do for this. Print a box with a hole in its center. That is, print a box as in normally but with the single # in the center (or one close to the center for boxes with an even width) replaced with a space.
I have the box. How do I calculate the center of the box?
import java.util.Scanner;
public class square {
public square(){
Scanner H=new Scanner(System.in);
int y=H.nextInt();//int for width
int x=H.nextInt();//int for height
int [][]shape=new int[x][y];//2d array stores the above
for(int i=0; i<shape.length; i++){//loops through height and width below
for(int j=0; j<shape[i].length; j++){
System.out.print("#");//prints box of #
}
System.out.println();
}
}
public static void main(String[]args){
new square();
}
}
First of all, not sure why you are making an array (shape) at all, unless that is part of your assignment?
If you use a for loop that steps from 0 to y inside one that steps from 0 to x instead of using the lengths of the array, you will get the same results without needing the array.
As for the center, its location is x/2, y/2. If you change your inner loop to check your variables i and j to see if the current position is x/2, y/2 and print a space instead of an # in that case, I think you will have the results you're looking for.
Related
I have a problem regarding drawing multiple of the same objects. They end on top of each other, and their "Object values" even get added together e.g. if a zombie has "2" movement value and there is added 2 into the current level. Then when zombies are moved, they move "4" each. This does not happen if two different objects are moved e.g. Zombie and Dragon. I have created the following code based on my project - for a simpler overview. However, the behavior is the same.
It should be mentioned the objects of the same type have the same "HashCode". I have also made comments and println to help figure out the problem. Each of the 5 objects have different position (When set). However, they are rendered on top of each other and merged (Movement).
EnemyDatabase enemyDatabase;
ArrayList<Enemy> enemiesInlevel = new ArrayList<Enemy>();
void setup()
{
size(600, 600);
enemyDatabase = new EnemyDatabase();
enemyDatabase.enemies.add(new Enemy("Zombie", 3));
//If dragon is added - Then it can draw both - But only once
//enemyDatabase.enemies.add(new Enemy("Dragon", 10));
//Add 10 zombies to the level
for(int i=0; i< 5;i++)
{
//5 Zombies are created and succesfully added to the database
enemiesInlevel.add(enemyDatabase.enemies.get((int)random(0, enemyDatabase.enemies.size())));;
}
for(int i=0; i<enemiesInlevel.size();i++)
{
//Sets the position of all 5 - Gives random position
Enemy enemy = enemiesInlevel.get(i);
enemy.SetPosition();
}
}
void draw()
{
background(255, 200, 0);
//Draw 5 enemies - Of index 0 (Zombie)
for(int i=0; i<enemiesInlevel.size();i++)
{
Enemy tempEnemy = enemiesInlevel.get(i);
tempEnemy.draw();
//It runs 5 times - print returns 5 total objects in enemiesInlevel
}
}
class EnemyDatabase
{
ArrayList<Enemy> enemies = new ArrayList<Enemy>();
}
class Enemy
{
String enemyName;
int enemyHealth;
PVector enemyPosition;
public Enemy(String name, int hp)
{
enemyName = name;
enemyHealth = hp;
}
public void SetPosition()
{
enemyPosition = new PVector(random(0, width), random(0, height));
//Each of the objects has a random position
println(enemyPosition);
}
public void draw()
{
rect(enemyPosition.x, enemyPosition.y, 25, 25);
}
}
UPDATE
Here is an image of the problem
As the image shows from the output in the image line: The enemies have different positions when added to the array (5 different enemies) However, as the image shows, it still only displays one - And this happens because all of the sudden the positions is the same. I even tried to give a "Random position" in the "DrawImage" all of the enemies still end up having the same position
Hope you guys can figure it out. I certainly have a hard time - I usually don't work in processing Thank you
DrSatan's comment is correct. You're only ever adding a single Enemy to your EnemiesDatabase. So when you select 5 random enemies, you're really just selecting the same enemy 5 times.
It might look like they have different positions in your print statements, but that's because you're printing out the position every time you set it. You're setting it five times, but only the last position really counts for anything.
In other words, you're taking a single instance of Enemy, moving it around the screen 5 times, and printing out the position each time. But then when you draw it, only the last position you moved it to is what you see.
You need to refactor your code so you add more enemies to your EnemyDatabase, but please note that you're going to have similar problems no matter how many enemies are in your EnemyDatabsae, because you don't have any logic that makes sure you don't select the same instance twice. Even if you had 100 enemies in your database, nothing is stopping your random function from selecting the same enemy 5 times.
If I were you, I'd rethink my design. I don't really see the reason to have a separate EnemyDatabase class at all. Maybe just create a function that adds X random enemies to the level, where X is a parameter? That's up to you, but your fundamental problem here is that you only have a single instance of Enemy.
The movie quotes are just appearing randomly in quick succession rather than the desired effect of it pulling one random movie quote from the text document.
Ideally I want a new quote to appear by the click of the mouse.
Tried to make the array and index a global variable but then the text wouldn't display for some reason.
PImage wallpaper;
void setup() {
size(600, 600);
wallpaper = loadImage("Theatrescreen.png");
}
void draw() {
background(wallpaper);
String[] moviequotes = loadStrings("moviequotes.txt");
int index = int(random(moviequotes.length));
text(moviequotes[index], mouseX, mouseY);
}
void mousePressed() {
}
Code within draw() is executed in an infinite loop. I think that is your problem. See Processing Reference - draw(). To take care of the problem, consider using noloop(). See Processing Reference - noloop().
Your implementation of Random isn't correct. Try something like this:
void draw() {
background(wallpaper);
String[] moviequotes = loadStrings("moviequotes.txt");
Random randIndex = new Random();
int index = randIndex.nextInt(moviequotes.length); // generate a random index from 0 to movieqoutes.length
text(moviequotes[index], mouseX, mouseY);
}
You are generating a new random movie quote each draw cycle. That means a lot (more than 25 dependeing on framerate) each second.
You can set the framerate like this:
void setup() {
frameRate(1);
}
or add a counter to your draw loop, so that you generate a new quote only once in a while
A quick overview of my program: I am making the game War. So when the play button is clicked, two new cards show up with random values. Which ever card has the higher value wins, and a rectangle appears in the middle of the window. As the game goes on, who ever wins has more rectangles pushed to their side (either to the left or right depending on which card wins), but the trick is that if for example the card on the left wins the first three, then the card on the right wins 1, a rectangle is removed, meaning only 2 are going to the left. If the right wins again, another is removed, etc.
The rectangle is created in a separate class called Bar, and here is what I have to create an array with a rectangle that goes to the left.
Bar newBar = new Bar(300,250);
counter = d++;
newBar = new Bar(300-(counter*30), 250);
if(numDi >= bars.length){ //You want it to always be higher
Bar[] temp = new Bar[bars.length +1];
for(int i = 0; i < bars.length; i++){
temp[i] = bars[i];
}
bars = temp; //increments bars by 1
}
bars[numDi++] = newBar;
The idea I have is that I could create an if statement which checks who won and also who won the last game. And if the opposing player won the last game, I would need to subtract a rectangle.
But how would I go about subtracting the rectangle?
And as a side note, I can not use any sort of lists.
You can use a single integer counter. When the right side wins increment it by 1 and when the left side wins decrement it by 1. This way you can easily test with an if statement who has been winning lately and control what happens depending on who wins.
If you can't use a list or queue then I would suggest using two separate arrays, one for the left side and one for the right side. You can increment and decrement them according to the overall score counter.
I am trying to make a very simple grid in which a user can move through. Through my research i have concluded that the best way to achieve this would be using a two-dimensional array to represent the grid. However i am unsure of how to draw this array to a Jframe or Jpanel if i were to make an array of rectangles.
Many Stackoverflow questions seem to ask simmilar queries but unforunately i have found non that entirely explains how to draw a simple grid of rectangles.
You can make arrays out of everything. Notice how the way to implement an array is
*datatype* [] *arrayname* = new *datatype* [*lengthOfArray*];
Lets say the name of the class that contains the rectangles is RECTANGLE. So if you want an Array, that contains, lets say, 5 rectangles, it would look somewhat like that:
RECTANGLE [] rectangelArray = new RECTANGLE [5];
If you want to take that to a 2 dimensional Level, just add another bracket:
RECTANGLE [][] rectangelMatrix = new RECTANGLE [4][5];
Assuming that by "drawing to the JPanel" you mean that you want to put the rectangles onto the screen, you would then have a for-loop in a for-loop, that would for example call each rectangle to draw itself:
for(int i = 0; i<rectangleMatrix.length; i++){
for(int j = 0; j<rectangleMatrix[i].length; j++){
rectangleMatrix[i][j].draw();
}
}
rectangleMatrix.draw() calls a method that will draw the rectangle based on its coordinates and size. you could also in a similar fashion call a method that will read the information of each rectangle and then draw it based on that information. This will help you seperate between information and drawing purposes in your classes, which is always a good thing to do:
for(int i = 0; i<rectangleMatrix.length; i++){
for(int j = 0; j<rectangleMatrix[i].length; j++){
drawRectangle(rectangleMatrix[i][j]);
}
}
drawRectangle(RECTANGLE toDraw) is in the same class that you have the method with the for-loop in.
In your parent component of grid set layout like
gamePanel.setLayout(new GridLayout(ix, iy));
where ix and iy is dimension size
you also need array of cells private Cell[][] cells; in this case cell is simply
public class Cell extends JPanel{
//some game specific code, fields, constructors
}
now use it
for (int i = 0; i < ix; i++) {
for (int j = 0; j < iy; j++) {
progres.setValue(progres.getValue() + 1);
cells[i][j] = new Cell(i, j, passer);
gamePanel.add(cells[i][j]);
}
}
now if in constructor of cell you will set a border this.setBorder(new LineBorder(Color.GRAY)); grid will appear. in cell constructor or setter method you can also pass whole cells so each cell will be aware of another, and be able to interact with them. but be aware- if you pass it in loop that also create cells, you might encounter a null values.
this way you can use swing components so each cell can be clickable etc.
You can extend a JComponent and overriding its paint(Graphics) method to draw the grid using Graphics.drawLine.
If you need the grid cells to be interactive in some way, then you should probably just create components with rectangular borders and position them using a grid layout.
// A program for drawing simple graphs
public class Graphpane extends JPanel {
int node,i,j,flag; // node is for storing no. of nodes... i,j are counters.. flag is for storing option yes or no
ArrayList<Integer> xaxis= new ArrayList<Integer>(); // arraylist for storing x-cordinates
ArrayList<Integer> yaxis= new ArrayList<Integer>(); //arraylist for storing y ordinates
Scanner in= new Scanner(System.in);
public Graphpane(){
super();
System.out.println("Create your own graph!!! :)");
System.out.println("Enter the number of nodes in your graph:");
node= in.nextInt();
System.out.println("Enter the x and the y vertices respectively");
System.out.println("<<<x cordinate shouldn't exceed 600 and y ordinate shouldn't exceed 400>>>");
for(i=0;i<node;i++)
{
System.out.println("Enter the x co-ordinate for"+ i+ "node");
xaxis.add(in.nextInt());
System.out.println("Enter the y ordinate for"+ i+ "node");
yaxis.add(in.nextInt());
}
repaint();
}
public void paint(Graphics g) // paint method
{
for(i=0;i<node;i++)
{
g.fillArc(xaxis.get(i)- 3, yaxis.get(i)-3,6,6,0,360);// drawing points on panel
}
for(i=0;i<node;i++){
for(j=0;j<node;j++) // asking whether the two points are connected or not.. if connected then drawing a line between the two
{
if(i==j) // would skip for the same points as simple graph.. no loops
{
continue;
}
else{
System.out.println("Are the points of index "+i+ " and "+j+" connected?? Say 1 for yes or else for no");
flag=in.nextInt(); // flag for recording whether connected or not
if(flag==1)
{
g.drawLine(xaxis.get(i),yaxis.get(i),xaxis.get(j),yaxis.get(j));
}
//xaxis is arraylist containing x cordinates and yaxis for containing y ordinates.. i and j are indices
//drawing lines between the two points if connected
}
//**Here I am asked whether my two points are connected question multiple times but I want it just once**
}
}
}
}
the paint method is called multiple times… how to restrict that?
You can't. A component will repaint itslef whenthe program invokes repaint on itself or the Swing RepaintManager determines when a component need to be repainted.
//**Here I am asked whether my two points are connected
//question multiple times but I want it just once**
A painting method is for painting only. There should be no user interaction. That is you should not be displaying an option pane or any other kind of message for the user to respond to.
So the code that interacts with the user need so be coded outside of the paintComponent() method.
Also, custom painting should be done in the paintComponent() method, not the paint() method.