JAVA GAME PROGRAMMING FOR BEGINNERS: WHERE TO START

 - 
Writing simple games is a fun way khổng lồ learn a new programming language. Put that principle to lớn work khổng lồ get started with Java.

Bạn đang xem: Java game programming for beginners: where to start


*

My article about learning different programming languages lists five things you need to lớn understand when starting a new language. An important part of learning a language, of course, is knowing what you intend to vị with it.


I"ve found that simple games are both fun lớn write & useful in exploring a language"s abilities. In this article, I demonstrate how to lớn create a simple guessing trò chơi in Java.

Install Java

To bởi vì this exercise, you must have Java installed. If you don"t have it, kiểm tra out these link to install Java on Linux, macOS, or Windows.

After installing it, run this Java command in a terminal to confirm the version you installed:

$ java -version

Guess the number

This "guess the number" program exercises several concepts in programming languages: how to assign values khổng lồ variables, how to write statements, and how to lớn perform conditional evaluation và loops. It"s a great practical experiment for learning a new programming language.

Here"s my Java implementation:


package com.example.guess;import java.util.Random;import java.util.Scanner; class Main private static final Random r = new Random(); private static final int NUMBER = r.nextInt(100) + 1; private static int guess = 0; public static void main(String<> args) Scanner player = new Scanner(System.in); System.out.println("number is " + String.valueOf(NUMBER)); //DEBUG while ( guess != NUMBER ) // prompt player for guess System.out.println("Guess a number between 1 và 100"); guess = player.nextInt(); if ( guess > NUMBER ) System.out.println("Too high"); else if ( guess NUMBER ) System.out.println("Too low"); else System.out.println("That"s right!"); System.exit(0);
That"s about đôi mươi lines of code, excluding whitespace & trailing braces. Structurally, however, there"s a lot going on, which I"ll break down here.

Package declaration

The first line, package com.example.guess, is not strictly necessary in a simple one-file application lượt thích this, but it"s a good habit lớn get into. Java is a big language, & new Java is written every day, so every Java project needs to have a unique identifier khổng lồ help programmers tell one library from another.

When writing Java code, you should declare a package it belongs to. The format for this is usually a reverse tên miền name, such as com.digitalseminar.com.vn.guess or org.slf4j.Logger. As usual for Java, this line is terminated by a semicolon.

Import statements

The next lines of the code are import statements, which tell the Java compiler what libraries to load when building the executable application. The libraries I use here are distributed along with OpenJDK, so you don"t need to download them yourself. Because they"re not strictly a part of the bộ vi xử lý core language, you bởi vì need to danh mục them for the compiler.

The Random library provides access to pseudo-random number generation, & the Scanner library lets you read user input đầu vào in a terminal.

Java class

The next part creates a Java class. Java is an object-oriented programming language, so its quintessential construct is a class. There are some very specific code ideas suggested by a class, & if you"re new to lớn programming, you"ll pick up on them with practice. For now, think of a class as a box into which you place variables and code instructions, almost as if you were building a machine. The parts you place into the class are quality to that class, và because they"re contained in a box, they can"t be seen by other classes. More importantly, since there is only one class in this sample game, a class is self-sufficient: It contains everything it needs lớn perform its particular task. In this case, its task is the whole game, but in larger applications, classes often work together in a sort of daisy-chain khổng lồ produce complex jobs.

In Java, each file generally contains one class. The class in this tệp tin is called Main khổng lồ signify that it"s the entry-point for this application. In a single-file application such as this, the significance of a main class is difficult khổng lồ appreciate, but in a larger Java project with dozens of classes & source files, marking one Main is helpful. Và anyway, it"s easy to lớn package up an application for distribution with a main class defined.

Java fields

In Java, as in C & C++, you must declare variables before using them. You can define "fields" at the vị trí cao nhất of a Java class. The word "field" is just a fancy term for a variable, but it specifically refers to lớn a variable assigned to lớn a class rather than one embedded somewhere in a function.

This trò chơi creates three fields: Two khổng lồ generate a pseudo-random number, & one lớn establish an initial (and always incorrect) guess. The long string of keywords (private static final) leading up khổng lồ each field may look confusing (especially when starting out with Java), but using a good IDE lượt thích Netbeans or Eclipse can help you navigate the best choice.

Xem thêm: Công Nghệ Skyway Là Gì ? Skyway Lừa Đảo Không ? Có Nên Đầu Tư Vào Skyway ?

It"s important to understand them, too. A private field is one that"s available only lớn its own class. If another class tries to lớn access a private field, the field may as well not exist. In a one-class application such as this one, it makes sense lớn use private fields.

A static field belongs to lớn the class itself và not khổng lồ a class instance. This doesn"t make much difference in a small demo app like this because only one instance of the class exists. In a larger application, you may have a reason khổng lồ define or redefine a variable each time a class instance is spawned.

A final field cannot have its value changed. This application demonstrates this perfectly: The random number never changes during the game (a moving target wouldn"t be very fair), while the player"s guess must change or the trò chơi wouldn"t be winnable. For that reason, the random number established at the beginning of the trò chơi is final, but the guess is not.

Pseudo-random numbers

Two fields create the random number that serves as the player"s target. The first creates an instance of the Random class. This is essentially a random seed from which you can draw a pretty unpredictable number. To vị this, danh mục the class you"re invoking followed by a variable name of your choice, which you set to lớn a new instance of the class: Random r = new Random();. Lượt thích other Java statements, this terminates with a semicolon.

To draw a number, you must create another variable using the nextInt() method of Java. The syntax looks a little different, but it"s similar: You các mục the kind of variable you"re creating, you provide a name of your choice, and then you set it khổng lồ the results of some action: int NUMBER = r.nextInt(100) + 1;. You can (and should) look at the documentation for specific methods, like nextInt(), lớn learn how they work, but in this case, the integer drawn from the r random seed is limited up to 100 (that is, a maximum of 99). Adding 1 khổng lồ the result ensures that a number is never 0 and the functional maximum is 100.

Obviously, the decision to disqualify any number outside of the 1 to 100 range is a purely arbitrary design decision, but it"s important to know these constraints before sitting down khổng lồ program. Without them, it"s difficult khổng lồ know what you"re coding toward. If possible, work with a person whose job it is lớn define the application you"re coding. If you have no one to lớn work with, make sure to danh mục your targets first—and only then put on your "coder hat."

Main method

By default, Java looks for a main method (or "function," as they"re called in many other languages) to lớn run in a class. Not all classes need a main method, but this demo phầm mềm only has one method, so it may as well be the main one. Methods, lượt thích fields, can be made public or private and static or non-static, but the main method must be public and static for the Java compiler to recognize and utilize it.

Application logic

For this application khổng lồ work as a game, it must continue khổng lồ run while the player takes guesses at a secret pseudo-random number. Were the application to stop after each guess, the player would only have one guess and would very rarely win. It"s also part of the game"s design that the computer provides hints lớn guide the player"s next guess.

A while loop with embedded if statements achieves this design target. A while loop inherently continues to lớn run until a specific condition is met. (In this case, the guess variable must equal the NUMBER variable.) Each guess can be compared to lớn the target NUMBER to lớn prompt helpful hints.

Syntax

The main method starts by creating a new Scanner instance. This is the same principle as the Random instance used as a pseudo-random seed: You cite the class you want to use as a template, provide a variable name (I use player lớn represent the person entering guesses), & then mix that variable khổng lồ the results of running the class" main method. Again, if you were coding this on your own, you"d look at the class" documentation lớn get the syntax when using it.

This sample code includes a debugging statement that reveals the target NUMBER. That makes the trò chơi moot, but it"s useful to lớn prove to yourself that it"s working correctly. Even this small debugging statement reveals some important Java tips: System.out.println is a print statement, và the valueOf() method converts the integer NUMBER khổng lồ a string lớn print it as part of a sentence rather than an element of math.

The while statement begins next, with the sole condition that the player"s guess is not equal to the target NUMBER. This is an infinite loop that can end only when it"s false that guess does not equal NUMBER.

In this loop, the player is prompted for a number. The Scanner object, called player, takes any valid integer entered by the player và puts its value into the guess field.

The if statement compares guess to NUMBER and responds with System.out.println print statements lớn provide feedback khổng lồ the human player.

Xem thêm: Oxit Là Gì ? Cách Gọi Tên Và Phân Loại Oxit Như Nào ? Oxit Là Gì, Phân Loại Oxit, Cách Gọi Tên Oxit

If guess is neither greater than nor less than NUMBER, then it must be equal lớn it. At this point, the trò chơi prints a congratulatory message and exits. As usual with POSIX application design, this game exits with a 0 status to indicate success.

Run the game

To thử nghiệm your game, save the sample code as Guess.java và use the Java command khổng lồ run it: