*Author

Offline nerd1Topic starter

  • Hero Member
  • *****
  • Posts: 1137
  • Country: us
  • Reputation Power: 15
  • nerd1 is a Blue Crawler starting to think about his first run.nerd1 is a Blue Crawler starting to think about his first run.nerd1 is a Blue Crawler starting to think about his first run.
  • kind of active
Java https://elementscommunity.org/forum/index.php?topic=29000.msg370243#msg370243
« on: July 23, 2011, 02:09:45 pm »
if there are are any java programmers on the forum, feel free to share your programs here, although i may ask you lots of question, because i am only on week 2 of my three week java course, but here is one of my programs anyways.
Code: [Select]
//author: Gabriel B.
//quizzes the user on mental math aptitude.

import javax.swing.*;
import java.util.*;

public class calculate_this_gui
//author: Gabriel B.
//quizzes the user on mental math aptitude.

import javax.swing.*;
import java.util.*;

public class calculate_this_gui
{
static int computeAnswer(int x, int y, char operator)
{
switch(operator)
{
case '+': return x + y;
case '-': return x - y;
case '*': return x * y;
case '/': return x / y;
case '%': return x % y;
default: return -999999;
}
}

public static void main(String[] args)
{
JFrame frame = new JFrame("calculate this");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
Random rand = new Random();

int rand_int_x = 24;
int rand_int_y = 24;
int correct = 0;
int times_to_play = 0;
int answer = 0;
int right = 0;
int wrong = 0;
int count = 0;
int x;
int y;
int which_operator = 0;
char operators[] = {'*', '/', '+', '-', '%'};
String playTimes;
String yes;
String no;
String finalCount;
String question;


playTimes = JOptionPane.showInputDialog("How many times do you want to play?");
times_to_play = Integer.parseInt(playTimes);

for(; count<times_to_play; count++)
{
x = rand.nextInt(rand_int_x)+1;
y = rand.nextInt(rand_int_y)+1;
which_operator = rand.nextInt(5);

question = JOptionPane.showInputDialog("what is "+x+operators[which_operator]+y+"?");
correct = computeAnswer(x,y,(operators[which_operator]));
answer = Integer.parseInt(question);
if (answer == correct)
{
yes = "you're right!";
JOptionPane.showMessageDialog(null, yes);
right++;
rand_int_x += 2;
rand_int_y += 2;
}
else
{
no = "you're wrong.";
JOptionPane.showMessageDialog(null, no);
wrong++;
rand_int_x--;
rand_int_y--;
}
}
finalCount = "you got it right "+right+" times, "+" and got it wrong "+wrong+" times.";
JOptionPane.showMessageDialog(null, finalCount);
}

}

think like a computer, everything s an integer.
The laziest elements player this side of one thousand posts.

davidy22

  • Guest
Re: Java https://elementscommunity.org/forum/index.php?topic=29000.msg372394#msg372394
« Reply #1 on: July 27, 2011, 10:51:00 pm »
Because you use integer types, decimal results are discarded, leading to answers like 5/2=2. Either remove the division option or change x and y to floating-point variables.

Instead of declaring how many times you want to play at the beginning, prompt the user if they want to play again. If the answer is affirmative, call a new method called question, putting the question segment of the code in it's own method.

Three week java course? That's intensive, do they teach you anything outside the language syntax?

Offline nerd1Topic starter

  • Hero Member
  • *****
  • Posts: 1137
  • Country: us
  • Reputation Power: 15
  • nerd1 is a Blue Crawler starting to think about his first run.nerd1 is a Blue Crawler starting to think about his first run.nerd1 is a Blue Crawler starting to think about his first run.
  • kind of active
Re: Java https://elementscommunity.org/forum/index.php?topic=29000.msg372419#msg372419
« Reply #2 on: July 27, 2011, 11:58:29 pm »
a bit, algorithms, etc... i just finished making a pong-like game, but i am still adding features.
The laziest elements player this side of one thousand posts.

davidy22

  • Guest
Re: Java https://elementscommunity.org/forum/index.php?topic=29000.msg372422#msg372422
« Reply #3 on: July 28, 2011, 12:05:44 am »
a bit, algorithms, etc... i just finished making a pong-like game, but i am still adding features.
Algorithms?

Give a sorting alogrithm for a a regular java array. Not array list. Account for empty values, don't look it up on the internet.

Offline nerd1Topic starter

  • Hero Member
  • *****
  • Posts: 1137
  • Country: us
  • Reputation Power: 15
  • nerd1 is a Blue Crawler starting to think about his first run.nerd1 is a Blue Crawler starting to think about his first run.nerd1 is a Blue Crawler starting to think about his first run.
  • kind of active
Re: Java https://elementscommunity.org/forum/index.php?topic=29000.msg372427#msg372427
« Reply #4 on: July 28, 2011, 12:21:50 am »
a bit, algorithms, etc... i just finished making a pong-like game, but i am still adding features.
Algorithms?

Give a sorting alogrithm for a a regular java array. Not array list. Account for empty values, don't look it up on the internet.
sorry, working on pong, and you didn't give me what kind of array, and what to sort it for.
The laziest elements player this side of one thousand posts.

davidy22

  • Guest
Re: Java https://elementscommunity.org/forum/index.php?topic=29000.msg372434#msg372434
« Reply #5 on: July 28, 2011, 12:45:49 am »
a bit, algorithms, etc... i just finished making a pong-like game, but i am still adding features.
Algorithms?

Give a sorting alogrithm for a a regular java array. Not array list. Account for empty values, don't look it up on the internet.
sorry, working on pong, and you didn't give me what kind of array, and what to sort it for.

Integers. And the normal kind of array, the one with the square brackets and fixed length.
How's the pong going?

Offline nerd1Topic starter

  • Hero Member
  • *****
  • Posts: 1137
  • Country: us
  • Reputation Power: 15
  • nerd1 is a Blue Crawler starting to think about his first run.nerd1 is a Blue Crawler starting to think about his first run.nerd1 is a Blue Crawler starting to think about his first run.
  • kind of active
Re: Java https://elementscommunity.org/forum/index.php?topic=29000.msg372625#msg372625
« Reply #6 on: July 28, 2011, 01:37:20 pm »
a bit, algorithms, etc... i just finished making a pong-like game, but i am still adding features.
Algorithms?

Give a sorting alogrithm for a a regular java array. Not array list. Account for empty values, don't look it up on the internet.
sorry, working on pong, and you didn't give me what kind of array, and what to sort it for.

Integers. And the normal kind of array, the one with the square brackets and fixed length.
How's the pong going?
i meant how to sort it, like highest to lowest, or lowest to highest, but since i am feeling to lazy to make something like that right now, i'll just give you the code so far for pong.
here is the actual code
Code: [Select]
//********************************************************************
//Moving Circle       Author: Gabriel B.
//
//plays a 2d game of ping pong.
//********************************************************************

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Random;

public class MovingCirclePanel extends JPanel
{
   private final int WIDTH = 304, HEIGHT = 300;
   
   static Random rand = new Random();
   
public boolean isFary = false;
public boolean isFarx = false;
public boolean isFarz = false;
public boolean isTrue = true;
public boolean isTrue2 = true;
public boolean coloryellow = true;
public boolean sumoIsTrue = false;
public boolean isImpossible = false;
public boolean isHighStakes = false;

Timer timer;

public static int count;
public static int countGain = 1;

public static int count2;
public static int countGain2 = 1;

public static int sloMo = 0;
public static int speedball = 0;
public static int sumo = 0;
public static int impossible = 0;
public static int highStakes = 0;
public static int obstruction = 0;

public static int z = 0;
public static int z_decay = 5;

public static int x = rand.nextInt(250);
public static int x_decay = 4;
public static int y = rand.nextInt(250);
public static int y_decay = 6;

public static int lengthAI = 50;
public static int lengthYou = 50;

public static int w = 0;
public static int w_decay = 50;

   //-----------------------------------------------------------------
   //  Constructor: Sets up this panel and loads the images.
   //-----------------------------------------------------------------
   public MovingCirclePanel()
   {
      addKeyListener (new DirectionListener());
      timer = new Timer(20, new ReboundListener());
     
      setBackground (Color.black);
      setPreferredSize (new Dimension(WIDTH, HEIGHT));
      setFocusable(true);
     
      timer.start();
   }

   //-----------------------------------------------------------------
   //  Draws the image in the current location.
   //-----------------------------------------------------------------
   public void paintComponent (Graphics page)
   {
      super.paintComponent (page);

page.setColor(Color.gray);//background
page.fillRect(0, 0, 304, 300);
     
page.setColor (Color.yellow);
page.fillOval (x, y, 10, 10);//ball

page.fillRect(277, z, 2, lengthAI);//AI paddle
page.fillRect(23, w, 2, lengthYou);//your paddle

if(coloryellow)
{
page.setColor (Color.yellow);
}
else
{
page.setColor (Color.blue);
}
page.fillRect(0, 0, 2, 300);
page.fillRect(302, 0, 2, 300);

if (sloMo > 149 && sloMo <281)
{
page.drawString("Slow Mo", 135, 145);
}
else
{
}
if(sumoIsTrue)
{
page.drawString("Sumo", 135, 145);
}
else
{
}

if(obstruction > 1449 && obstruction < 1531)
{
page.fillRect(70, 70, 180, 160);//Obstruction

page.setColor(Color.black);
page.drawString("Obstruction", 135, 145);
obstruction++;

page.setColor(Color.yellow);
}
else
{
obstruction++;
}

if(isHighStakes)
{
page.drawString("High Stakes", 135, 145);
}
if(isImpossible)
{
page.drawString("Impossible", 135, 145);
}
else
{
}

if (speedball > 329 && speedball <371)
{
page.drawString("Speedball", 135, 145);
}
else
{
}

if(count >= 12)
{
page.setColor (Color.white);
page.fillRect(0, 0, 310, 310);

page.setColor (Color.black);
page.drawString("You Win", 105, 10);

count2 = 0;
}

else if(count2 >= 12)
{
page.setColor (Color.white);
page.fillRect(0, 0, 310, 310);

page.setColor (Color.black);
page.drawString("Computer Wins", 105, 10);

count = 0;
}
else
{
page.drawString("player points: "+count, 105, 10);
page.drawString("AI points: "+count2, 105, 30);
}
   }


private class ReboundListener implements ActionListener
{
public void actionPerformed (ActionEvent event)
    {
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

if(highStakes > 999 && highStakes < 1161)
{
countGain = 2;
countGain2 = 2;
highStakes++;
isHighStakes = true;
}
else
{
{
countGain = 1;
countGain2 = 1;
highStakes++;
isHighStakes = false;
}
}
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

if(sumo > 529 && sumo < 691)// grows both paddles for a limited number of time
{
lengthAI = 100;
lengthYou = 100;
sumo++;
sumoIsTrue = true;
}
else
{
lengthAI = 50;
lengthYou = 50;
sumo++;
sumoIsTrue = false;
}
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

if (speedball > 329 && speedball < 371)//speeds up ball for limited number of time
{
x_decay = 7;
y_decay = 7;
speedball++;
}
else
{
x_decay = 4;
y_decay = 6;
speedball++;
}

//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

if (sloMo > 149 && sloMo <281)//slows down opponents paddle for a limited number of time
{
z_decay = 3;
sloMo++;
}
else
{
z_decay = 5;
sloMo++;
}
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

if(impossible >749 && impossible < 861)// makes the AI impossible to beat for a limited amount of time
{
lengthAI = 400;
impossible++;
isImpossible = true;
}
else
{
impossible++;
isImpossible = false;
}
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

if (x+10 > 278 && x+10 < 284)//checks if the ball is at the same x coordinate as the AI paddle
{
isTrue = true;
}
else
{
isTrue = false;
}
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

if (x < 26 && x > 8)//checks if the ball is at the same x coordinate as the player paddle
{
isTrue2 = true;
}
else
{
isTrue2 = false;
}

//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

//controls the motion of the AI bar
if ((z + lengthAI/2) > y)
{
z -= z_decay;
}
else
{
z += z_decay;
}

//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

//controls the motion of the ball

if(x > 290)
{
isFarx = true;
coloryellow = false;
x -= x_decay;
count = count+countGain;
}

//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

else if ((z + lengthAI >= y && z - 10 <= y ) && isTrue) //controls how the ball bounces of if it hits the AI bar
{
isFarx = true;
x -= x_decay;
}
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

else if ((w + lengthYou >= y && w - 10 <= y ) && isTrue2) //controls how the ball bounces of if it hits the  player bar
{
isFarx = false;
x += x_decay;
}

//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

else
{
if (isFarx)
{
if(x > 0)
{
coloryellow = true;
x -= x_decay;
}
else
{
isFarx = false;
coloryellow = false;
x += x_decay;
count2 = count2 + countGain2;
}
}
else
x += x_decay;
}

if(y > 290)
{
isFary = true;
y -= y_decay;
}
else
{
if(isFary)
{
if(y > 0)
{
y -= y_decay;
}
else
{
isFary = false;
{
y += y_decay;
}
}
}
else
{
y += y_decay;
}
}
repaint();
    }
}
   
   //*****************************************************************
   //  Represents the listener for keyboard activity.
   //*****************************************************************
private class DirectionListener implements KeyListener
{
//--------------------------------------------------------------
//  Responds to the user pressing arrow keys by adjusting the
//  image and image location accordingly.
//--------------------------------------------------------------
public void keyPressed (KeyEvent event)
{
switch (event.getKeyCode())
{
case KeyEvent.VK_UP:
if(w <= 0)
{

}
else
{
            w -= 20;
}
            break;
            case KeyEvent.VK_DOWN:
if(w >= 260)
{

}
else
{
            w += 20;
}
            break;
            case KeyEvent.VK_LEFT:
               break;
            case KeyEvent.VK_RIGHT:
               break;
         }

         repaint();
      }

      //--------------------------------------------------------------
      //  Provide empty definitions for unused event methods.
      //--------------------------------------------------------------
      public void keyTyped (KeyEvent event) {}
      public void keyReleased (KeyEvent event) {}
   }

}

code to implement it
Code: [Select]
//********************************************************************
//Moving Circle      Author: Gabriel B.
//
//Plays a 2d game of ping pong.
//********************************************************************

import javax.swing.JFrame;

public class MovingCircleGame
{
   //-----------------------------------------------------------------
   //  Creates and displays the application frame.
   //-----------------------------------------------------------------
   public static void main (String[] args)
   {
      JFrame frame = new JFrame ("Direction");
      frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add (new MovingCirclePanel());
      frame.pack();
      frame.setVisible(true);
   }
}
warning:
i don't know how to get it to go up or down immediately when you hold the keys down, so i recommend tapping on the keys instead of holding them  to move the player paddle.
The laziest elements player this side of one thousand posts.

davidy22

  • Guest
Re: Java https://elementscommunity.org/forum/index.php?topic=29000.msg372995#msg372995
« Reply #7 on: July 29, 2011, 04:48:10 am »
The following text comes from the scribble pad in my text editor, where I wrote down my thoughts as I read your code.

Quote
HOLY****POWERUPS.

Isn't the ball in pong square? Ah well, modern technolgy does make a round ball feasible.

Comments! You were taught well, I can never be bothered to comment my own code. I wish that gremlin on my shoulder would do my comments for me.

You could pare out an if...else clause at the coloryellow bit. Assign an RGB value to the thing instead, RGB being specified by three floating point variables in Color(R,G,B)
Proccess heavy vs data heavy. bleh.

Wait, nevermind. That colour change is for powerups? I want psychedelic pink.

Maybe change the required points to win to a variable? add a settings menu too.

FUUUUUUUUU. MAXIMUM LINE LENGTH OF 79 CHARACTERS.
That's alot of indents.

For your keypress problem, try a frame-by frame system of rendering and checking. Have a loop that executes indefinitely, which checks to see if the player has a button held down in each iteration. The AI also acts on a frame-by-frame basis, moving a little bit in each frame. I would suggest 30fps, with a move rate of 3 pixels, which would result in about 3 seconds for the paddle to traverse from one side of the screen to the other. Put everything that moves inside the loop, and have it update everything sequentially. It will result in some rapid keypresses not being registered, but holding down on keys will guarantee continuous movement.

Offline Sevs

  • Legendary Member
  • ******
  • Posts: 2007
  • Country: us
  • Reputation Power: 26
  • Sevs is a proud Wyrm taking wing for the first time.Sevs is a proud Wyrm taking wing for the first time.Sevs is a proud Wyrm taking wing for the first time.Sevs is a proud Wyrm taking wing for the first time.Sevs is a proud Wyrm taking wing for the first time.
  • My favorite element is Oxygen
  • Awards: Slice of Elements 3rd Birthday CakeWeekly Tournament WinnerWeekly Tournament Winner
Re: Java https://elementscommunity.org/forum/index.php?topic=29000.msg372996#msg372996
« Reply #8 on: July 29, 2011, 05:16:30 am »
There are keyboard events for button down and button up, meaning you can have events trigger when it is pressed or not. As for sharing code, I don't think I have any games simple enough to share in 2 classes. Also most of my games involves pictures which cant really be sent over the forums. At least that i know
"Elements is the greatest game ever made" - Abraham Lincoln

davidy22

  • Guest
Re: Java https://elementscommunity.org/forum/index.php?topic=29000.msg372997#msg372997
« Reply #9 on: July 29, 2011, 05:29:07 am »
There are keyboard events for button down and button up, meaning you can have events trigger when it is pressed or not. As for sharing code, I don't think I have any games simple enough to share in 2 classes. Also most of my games involves pictures which cant really be sent over the forums. At least that i know
You can put them all in a .zip file and attach them to your post. Max size 5mb.

Button up? That's way better than my idea. Didn't come to mind, these fancy new libraries you people have.

Java 7 SE has been released. It has shiny new features and a few bugfixes.

Offline YawnChainHow

  • Full Member
  • ***
  • Posts: 463
  • Reputation Power: 9
  • YawnChainHow is a Spark waiting for a buff.
  • Tees no longer available for purchase
  • Awards: Slice of Elements 4th Birthday CakeSlice of Elements 3rd Birthday CakeSlice of Elements 2nd Birthday Cake
Re: Java https://elementscommunity.org/forum/index.php?topic=29000.msg373017#msg373017
« Reply #10 on: July 29, 2011, 07:06:08 am »
Pastebin (http://pastebin.com/ (http://pastebin.com/)) proves to be really useful when you need to fling large walls of text around online.

Because I am essentially illiterate in programming languages, no comments on the programs from me. But I do hear that double > float.

davidy22

  • Guest
Re: Java https://elementscommunity.org/forum/index.php?topic=29000.msg373040#msg373040
« Reply #11 on: July 29, 2011, 08:56:32 am »
Pastebin (http://pastebin.com/ (http://pastebin.com/)) proves to be really useful when you need to fling large walls of text around online.

Because I am essentially illiterate in programming languages, no comments on the programs from me. But I do hear that double > float.
Not necessarily. Double precision integers take up twice as much space as normal floating point integers. The language will sometimes not have a discrepancy, and have only one option for a floating point variable. Python, my favourite programming language, uses duck typing- you don't declare the data type of a variable. Instead, the interpreter makes the assumption that the string you just entered is a string, the integer you just entered is an integer and the decimal you entered is a floating point integer. It does result in python programs running slightly slower than others, but the ease of use is awesome.

 

anything
blarg: