New dev team/java learning thread.

Organized and clear discussion only. Be sure to read sub-forum descriptions.
Forum rules
- All off-topic posts will be removed without notice.
- Poorly written topics/posts will be edited without warning
- Unnecessary topics will be deleted or locked without warning.
- Posts may be moved without warning.
User avatar
Iv121
Vice Admiral
Vice Admiral
Posts:2414
Joined:Fri Dec 07, 2012 3:40 pm
Affiliation:UTN
Location:-> HERE <-
Re: New dev team/java learning thread.

Post by Iv121 » Sun Jan 26, 2014 1:58 pm

No I was complaining about how the code tags work here purely, the alignment is just a suggestion to make comments more readable.
They're watching ... Image

"I am forbidden tag" -CvN

CMA
Captain
Captain
Posts:1083
Joined:Fri Jan 10, 2014 3:16 pm
Affiliation:Byzantine Falangists

Re: New dev team/java learning thread.

Post by CMA » Tue Jan 28, 2014 7:59 pm

Alright, sorry for being away, but it looks like I won't be able to get on for this week much. Also, everyone play vanilla minecraft if you can, I realized that we're trying to make a mod for a game most(?) of us rarely play.
"Being a christian democrat is like being a christian satanist" - Adam Berces

User avatar
Keon
Developer
Posts:662
Joined:Thu Dec 06, 2012 7:09 pm
Affiliation:Inactive
IGN:ducky215

Re: New dev team/java learning thread.

Post by Keon » Tue Jan 28, 2014 8:52 pm

I do a lot of minecraft invention stuff with command blocks, and I suppose I'm one of the few that plays. I haven't played survival in so long. I can't do it anymore. FTB and creative ruined me.

I'd also look at FTB and such, see how they do it and what they do right and wrong.
- I can be reached as ducky215 on minecraft forums -

CMA
Captain
Captain
Posts:1083
Joined:Fri Jan 10, 2014 3:16 pm
Affiliation:Byzantine Falangists

Re: New dev team/java learning thread.

Post by CMA » Tue Jan 28, 2014 11:57 pm

I don't even know what a command block does, is it like scripting, sort of? I'll look at FTB, if I have time.
"Being a christian democrat is like being a christian satanist" - Adam Berces

User avatar
Iv121
Vice Admiral
Vice Admiral
Posts:2414
Joined:Fri Dec 07, 2012 3:40 pm
Affiliation:UTN
Location:-> HERE <-

Re: New dev team/java learning thread.

Post by Iv121 » Wed Jan 29, 2014 1:33 am

Almost, a command block is like a redstone-triggered admin that runs almost any command apart from stuff like kicks or bans or whitelists and so on. It is mostly used by map makers to create complex scenarios.
They're watching ... Image

"I am forbidden tag" -CvN

User avatar
Keon
Developer
Posts:662
Joined:Thu Dec 06, 2012 7:09 pm
Affiliation:Inactive
IGN:ducky215

Re: New dev team/java learning thread.

Post by Keon » Wed Jan 29, 2014 9:14 am



They let you make stuff like this for adventure maps:



Yeah, it's a sphere. Whatcha gonna do about it?
- I can be reached as ducky215 on minecraft forums -

craftqq
Cadet
Cadet
Posts:25
Joined:Sun Jan 12, 2014 3:38 am
IGN:craftqq

Re: New dev team/java learning thread.

Post by craftqq » Wed Jan 29, 2014 11:04 am

Iv121 wrote:The program contains errors of different sorts and does not meet the requirements of the program:

1. The random number contains 0's and repeating numbers (yea I forgot to add the 0's to the list but the repeating numbers was clearly specified)
2. The program responds incorrectly to my guesses, I didn’t have a single hit in my guess yet I was shown a hit.
3. The player's invalid input is not handled: You are able to input letters and repeating numbers.
4. The player is unable to press 'escape' and leave the game.
5. Try to use less global variables (Like 'hits' for example).
6. Improper usage of strings, a string is an array in it's own right, no need to create a separate string for each number , instead add the new number directly into the string.
Should be fixed now (apart from the "hit escape to exit the program" - I'll do that once I'm able to use swing since java doesn't really support key presses (current workaround is to write "exit" to exit))
Program
Source: (github doesn't display it properly)
Spoiler:

Code: Select all

package io.github.craftqq.Bullseye;	// the package the class is in

import edu.hws.math.TextIO.TextIO;	// importing the TextIO class since it is needed to get the user input

public class Bullseye
{
	
	public static void main(String[] args)
	{
		String 	number 	= 	"";		// the number the user has to guess
		String 	hits 	= 	"";		/* how many hits the user scored
									*  pattern:
									*  "X" for a Bullseye
									*  "O" for a hit
									*  first "X", than "O"
									*  examples: "XX", "O", "XOO"
									*/ 
		int 	round 	= 	0;		// which round the game is in 	/ How many tries the user needs	; game ends after round 20
		boolean running = 	true;	// true if the program is active/ false if the program ends		
		boolean victory = 	false;	// true if the user won 		/ false if the user lost		
		boolean end 	= 	false;	// true if the game ended 		/ false if the game is running	
		
		System.out.println("");															// 
		System.out.println("▓▓▓▓   ▓   ▓  ▓      ▓       ▓▓▓▓  ▓▓▓▓▓  ▓   ▓  ▓▓▓▓▓  ");	// this
		System.out.println("▓   ▓  ▓   ▓  ▓      ▓      ▓      ▓      ▓   ▓  ▓      ");	// is
		System.out.println("▓▓▓▓   ▓   ▓  ▓      ▓       ▓▓▓   ▓▓▓▓    ▓ ▓   ▓▓▓▓   ");	// the
		System.out.println("▓   ▓  ▓   ▓  ▓      ▓          ▓  ▓        ▓    ▓      ");	// start
		System.out.println("▓▓▓▓    ▓▓▓   ▓▓▓▓▓  ▓▓▓▓▓  ▓▓▓▓   ▓▓▓▓▓    ▓    ▓▓▓▓▓  ");	// screen
		System.out.println("");															// 
		try						
		{							//
			Thread.sleep(200);		// Waits
		}							// for
		catch (Exception e)			// a
		{							// bit
									//
		}
		System.out.println("Write \"exit\" to exit Bullseye");	// tells the user how to exit the program
		try
		{							//
			Thread.sleep(200);		// waits
		}							// for
		catch (Exception e)			// a
		{							// bit
									//
		}
		number  = generateNumber();	// generates a new number
		while(running)				// the main loop; active while the program is running
		{
			while(!end)				// the game loop; active while the game is running
			{
				round++;									// increases the round counter
				System.out.println("");						// prints an empty line to leave some space
				System.out.println("Try #" + round + ":");	// prints out which round the user is in
				System.out.println("");						// prints an empty line
				hits = compareNumber(number, getInput());	// gets the input; compares the input with the generated number
				System.out.println(hits);					// prints how many hits the user scored
				if(hits.compareTo("XXXX") == 0)				// checks if the user won
				{											// 
					end 	= true;							// ends the game if the user won
					victory = true;							// sets victory = true to show that the user won
				}											//
				if(round == 20)								// checks if round 20 ended
				{											// 
					end = true;								// ends the game after round 20
				}
			}
			if(victory)												// checks if the user won
			{														// 
				System.out.println("Congratulations! You won!");	// prints out the victory message
				System.out.println("Rounds needed: " + round);		// prints out the amount of tries the user needed to win the game
			}
			else
			{
				System.out.println("Game over. You lost.");			// prints out the defeat message
			}
			while(end)										// the "end" loop; runs after the game ended
			{
				System.out.println("");						// prints out an empty line
				System.out.println("Try again? (Y/N)");		// asks if the user wants to try again
				String input = TextIO.getlnString();		// gets the user input
				if(input.compareToIgnoreCase("exit") == 0)	// checks if the user wants to exit the program
				{											
					System.out.println("Bye!");				// prints the exit message
					System.exit(0);							// exits the program
				}
				else if((input.compareToIgnoreCase("y") == 0) || (input.compareToIgnoreCase("yes") == 0))	// checks if the user wants to play another game
				{
					end 	= false;	// resets the
					victory = false;	// game and starts
					round 	= 0;		// another one
				}
				else if((input.compareToIgnoreCase("n") == 0) || (input.compareToIgnoreCase("no") == 0))	//checks if the user doesn't want to try again
				{
					end 	= false;	// ends the end loop
					running = false;	// and the program
				}
				else					//runs if the input is invalid
				{
					System.out.println(input + " is not an option!");	// informs the user that the specified input is invalid
				}
			}
		}
		System.out.println("Bye!");		// prints the exit message after the main loop ended
		System.exit(0);					// exits the program
	}
	
	static String generateNumber()			// generates a new number
	{
		String newNumber 	= "";			// the new number
		int digit[] 		= new int[4];	// the individual digits
		for(int i = 0; i < 4; i++)			// runs four times; once for each digit
		{
			boolean assigned = false;		// true if a valid digit has been found / false if not
			while (!(assigned))				// runs while the digit is invalid
			{
				assigned = true;			// sets assigned = true; gets set to false if the digit is invalid
				digit[i] = (int) ((Math.random() * 8) + 1);	// generates a new random digit
				for(int j = 0; j < i; j++)	// runs once for every digit generated before the current digit
				{							
					if(digit[i] == digit[j])// checks if the number is already used by another digit (turning the current digit invalid
					{
						assigned = false;	// sets assigned to false if the digit is invalid
					}
				}
			}
		}
		for(int i = 0; i < 4; i++)			// runs four times
		{
			newNumber = newNumber + String.valueOf(digit[i]);	// constructs the new number out of the individual digits
		}
		return newNumber;					// returns the generated number
	}
	
	static String compareNumber(String number1, String number2)	// compares two numbers
	{
		String result 		= "";								// the result of the comparison / the scored hits
		int countBullseye 	= 0;								// how many Bullseyes got scored
		int countHit 		= 0;								// how many hits got scored
		String part1[] 		= new String[4];					// the individual digits of the first number
		String part2[] 		= new String[4];					// the individual digits of the second number
		for(int i = 0; i < 4; i++)								// runs four times
		{
			part1[i] = number1.substring(i, (i + 1));			// creates the separate digits of the first number
			part2[i] = number2.substring(i, (i + 1));			// creates the separate digits of the second number
		}
		for(int i = 0; i < 4; i++)								// runs four times
		{
			for(int j = 0; j < 4; j++)							// runs another four times
			{
				if(part2[j].compareTo(part1[i]) == 0)			// checks if two digits are equal (one of number one and two each)
				{
					if(i == j)									// checks if the digits are at the same position
					{
						countBullseye++;						// increases the Bullseye count if the digits are equal and at the same position
					}
					else										// runs if the digits are at different positions
					{
						countHit++;								// increases the hit count if two digits are equal but not at the same position
					}
				}
			}
		}
		for(int i = 0; i < countBullseye; i++)					// runs as often as the user scored a Bullseye
		{
			result = result + "X";								// adds an "X" to indicate a Bullseye for every Bullseye
		}
		for(int i = 0; i < countHit; i++)						// runs as often as the user scored hits
		{
			result = result + "O";								// adds an "O" for every hit
		}
		return result;											// returns the result/the amount of hits
	}
	
	static String getInput()		// gets the user input
	{
		String input 	= "";		// the input
		boolean inputOK = false;	// true if the input is valid; false if not
		while(!inputOK)				// runs while the input is invalid
		{
			inputOK = true;			// sets the input = true; gets set to false if the input is invalid
			input = TextIO.getlnString();						// uses the TextIO class to get the input
			if(input.compareToIgnoreCase("exit") == 0)			// checks if the user wants to exit the program
			{
				System.out.println("Bye!");						// prints out the exit message
				System.exit(0);									// exits the program
			}
			try													// 
			{													// checks if the input is a number by
				Integer.parseInt(input);						// trying to parse it into an Int;
			}													// an exception is thrown if this isn't possible
			catch(Exception e)									// catches the exception and
			{													// 
				inputOK = false;								// sets inputOK = false to indicate that the input is invalid
				System.out.println("Please write a number!");	// tells the user to input numbers only
			}
			if(inputOK)											// runs if the input is a number
			{
				if((input.length()) != 4)						// checks if the input has less/more digits than required
				{
					System.out.println("The number must consist of 4 digits!");	// tells the user to write a number with four digits
					inputOK = false;							// sets inputOK = false to indicate that the input is invalid
				}
				else											// runs if the number has exactly four digits
				{
					String inputSubS[] = new String[4];			// the individual digits of the input number
					for(int i = 0; i < 4; i++)					// runs four times
					{
						inputSubS[i] = input.substring(i, (i + 1));			// separates the number into the digits
						for(int j = 0; j < i; j++)				// runs once four every digit created before the current one
						{
							if(inputSubS[i].compareTo(inputSubS[j]) == 0)	// checks if two digits are equal
							{
								inputOK = false;				// sets inputOK = false to indicate that the input is invalid
								break;							// ends the current loop since the other digits don't have to be checked
							}
						}
						if(!inputOK)							// checks if the input is invalid
						{
							System.out.println("The number shouldn't contain 2 or more identical digits!");	// tells the user that the number must consist of unique digits
							break;								// ends the current loop since the other digits don't have to be checked
						}
					}
				}
			}
		}
		return input;											// returns the input if it is valid
	}
}
edit: Eclipse has a different layout. great. I'll try to fix it
edit2:source open it in eclipse; it should work for now. I'll try fixing the spoiler

Code: Select all

╔═══  ║   ║  ══╦══  ║   ║  ╔══╗   ╔═══  ╔═══╗  ╔══╗   ╔═══╗  ╔═══  ══╦══
║     ║   ║    ║    ║   ║  ║  ║   ║     ║      ║  ║   ║   ║  ║       ║  
╠══   ║   ║    ║    ║   ║  ╠══╩╗  ╠══   ║      ╠══╩╗  ╠═══╣  ╠══     ║  
║     ║   ║    ║    ║   ║  ║   ║  ║     ║      ║   ║  ║   ║  ║       ║  
║     ╚═══╝    ║    ╚═══╝  ║   ║  ╚═══  ╚═══╝  ║   ║  ║   ║  ║       ║  

User avatar
fr0stbyte124
Developer
Posts:727
Joined:Fri Dec 07, 2012 3:39 am
Affiliation:Aye-Aye

Re: New dev team/java learning thread.

Post by fr0stbyte124 » Wed Jan 29, 2014 2:34 pm

For future reference, if you include the

Code: Select all

 tag, it will respect your whitespace. (*edit* nvm)  Can we install a code coloring plugin for the forum?  It's kind of tough to read the way it is. 

On topic: I've never been a fan of the command block system.  If you are going to go to all the work to support a scripting language in Minecraft, why would you go and stuff it in the redstone pipeline?  If you need stuff that updates on a per-tick basis you are spamming the block rather than setting up events.  We won't have lambda expressions until JDK 8, but even without that you should be able to register some standard triggers to subscribe scripts to.  This will probably need to be addressed in the mod since we'll be dealing with partially loaded chunks.  Anything that doesn't need to physically interract with the chunk should be moved to an abstract layer to avoid unpredictable conditions.

User avatar
Iv121
Vice Admiral
Vice Admiral
Posts:2414
Joined:Fri Dec 07, 2012 3:40 pm
Affiliation:UTN
Location:-> HERE <-

Re: New dev team/java learning thread.

Post by Iv121 » Wed Jan 29, 2014 3:18 pm

Alright the program technically works but it is inefficient in some points.

1. generateNumber uses 3 loops and an unneeded buffer array merely to assign a number with different letters, redo it using only 2 loops and no additional arrays.
2. In compareNumber and getInput again you use unneeded arrays and strings, and the way you use them might hint you do not wholly understand how they work.

Other than that the program is fine.

I suggest reading the Java book (or any other place you might find better for this) about arrays and also strings specifically. Also as a practice you can add a scoreboard future to the game which stores the high scores even if the program was closed across many games.
They're watching ... Image

"I am forbidden tag" -CvN

User avatar
fr0stbyte124
Developer
Posts:727
Joined:Fri Dec 07, 2012 3:39 am
Affiliation:Aye-Aye

Re: New dev team/java learning thread.

Post by fr0stbyte124 » Wed Jan 29, 2014 5:37 pm

I looked over the code, and I have some recommendations for making it a bit cleaner. The main thing is that you do a lot of nested looping and have some really strange string manipulation going on, which makes the program difficult to follow.

Firstly, I'm going to assume that your desired digit domain is supposed to be [1,9] inclusive and not [1,8] like your random number generator currently produces ( [0,1) * 8 < 8).

I would write generateNumber() to use a permutation pool, like so:

Code: Select all

static String generateNumber()			// generates a new number
{
	ArrayList<Integer> digitPool = new ArrayList<Integer>(Arrays.asList(1,2,3,4,5,6,7,8,9));  //There are many ways to do this.  This was simply the most compact.
	String strSecret = "";
	//int[] secret = new int[4];  //alternate representation of strSecret;

	Random rnd = new Random(); 
	for(int i=0; i<4; i++)
	{
		int slot = rnd.nextInt(digitPool.size());  //pick some number in the range of digitPool indexes
		//secret[i] = digitPool.get(slot);
		strSecret += digitPool.get(slot).toString();
		digitPool.remove(slot);
	}
	return strSecret;
}
I used java.util.Random.nextInt() for the prng instead of Math.random(), because it is cleaner and takes care of any modulo bias (unless your modulo is a power of two, some remainders will appear slightly more frequently than others unless you take steps to avoid it. nextInt() takes care of that for you).
*Edit* the modulo bias only comes into play for integer based random number generators, which is generally what you will see in other languages. Java's just got to be different.

You made compareNumber() way, way more complicated than it needed to be.
I'm not sure why you are chose to use a String to represent the secret number instead of an int[4], but as long as you are, you might as well take advantage of the built-in String functions.

Code: Select all

static String compareNumber(String number1, String number2)  //number1 = secret key, number2 = user guess
{
	int countBullseye 	= 0;
	int countHit 		= 0;		
	for(int i=0; i<4; i++)
	{
		char guess = number2.charAt(i);  //charAt(i) acts like String[i] would if Java was less dumb.  Use this instead of String.substring(i, (i + 1))
		if((number1.charAt(i) == guess)
			countBullseye++;
		else
			if(number1.indexOf(guess) != -1)  //indexOf finds the first instance of a character in a String, or -1 if it is not present
				countHit++;
	}
	String result = "";
	if(countBullseye > 0)
		result += new String(new char[countBullseye]).replace('\0', 'X');  //creates a string of n repeated characters.  I didn't want to import StringUtils just for this.  Java is a stupid language.
	if(countHit > 0)
		result += new String(new char[countHit]).replace('\0', 'O');
	
	return result;
}
Speaking of which, you can test for repeat characters in the input like this:

Code: Select all

boolean inputOK = true;
for(int i = 0; i<3; i++)
{
	char current = input.charAt(i);
	if(input.indexOf(current, i+1) != -1)  //same as indexOf(char), only it begins looking from a specific starting point
	{
		inputOK = false;
		break;
	}
}
Other things: I would recommend using breaks to exit the loop rather than while(!terminationFlag). It will make the program a lot easier to follow, even if you still use the flags for other things.
For the rounds loop, you already have a round counter, so just use a for() loop, and break out of it early if you win. Just remember that if you are counting from 1 to 20, the rounds counter will be 21 when the loop exits.

 ҉ 
Commodore
Commodore
Posts:1574
Joined:Thu Dec 06, 2012 6:50 am
Affiliation:Kzinti Empire
Location:Kzinhome

Re: New dev team/java learning thread.

Post by  ҉  » Wed Jan 29, 2014 5:45 pm

CMA wrote:Also, everyone play vanilla minecraft if you can, I realized that we're trying to make a mod for a game most(?) of us rarely play.
How relevant is that? Understanding the code is important, but game design for FC is going to be a very different thing from game design for Minecraft.

Also, vMC sucks. A lot. So many things have been botched. The new launcher lets you play whatever version you want; I strongly suggest that you drop back to early Beta if you want to see what MC should have been like. 1.3_01 was a good version.
;.'.;'::.;:".":;",,;':",;

(Kzinti script, as best as can be displayed in Human characters, translated roughly as "For the Patriarchy!")

User avatar
Tau
Admin
Posts:750
Joined:Mon Dec 10, 2012 9:58 am
Affiliation:Futureville Mafia
IGN:TehPwnzor7306
Location:Ancapistan

Re: New dev team/java learning thread.

Post by Tau » Wed Jan 29, 2014 5:50 pm

I honestly have no desire to play a game where a desert and a tundra can spawn right fucking next to each other.
Image
Vinyl wrote:"RP" and gaming and homosexuality is what's keeping [the forum] afloat.

User avatar
fr0stbyte124
Developer
Posts:727
Joined:Fri Dec 07, 2012 3:39 am
Affiliation:Aye-Aye

Re: New dev team/java learning thread.

Post by fr0stbyte124 » Wed Jan 29, 2014 5:54 pm

Yeah, realistically everything should have the exact same climate, considering that the world is basically flat and evenly exposed to sunlight.

CMA
Captain
Captain
Posts:1083
Joined:Fri Jan 10, 2014 3:16 pm
Affiliation:Byzantine Falangists

Re: New dev team/java learning thread.

Post by CMA » Wed Jan 29, 2014 7:17 pm

Mistake Not... wrote:if you want to see what MC should have been like. 1.3_01 was a good version.
Do that, then. I didn't know the new launcher did that. The climate thing bothers me as well, but I still think it should retain some of the feel of vMC.
"Being a christian democrat is like being a christian satanist" - Adam Berces

Solar112
Captain
Captain
Posts:1044
Joined:Fri Jan 10, 2014 2:19 pm
IGN:Solar112

Re: New dev team/java learning thread.

Post by Solar112 » Sun Feb 02, 2014 4:02 pm

I am actually resiging from the dev team now.

Post Reply