11 |
12 |
13 |
14 |
15 |
--------------------------------------------------------------------------------
/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/.mvn/wrapper/maven-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hoangsonww/Space-Invader-Game-JavaFX/d7e2ac3b28ca7aeb1de02e7a77005fcdf10a68a9/.mvn/wrapper/maven-wrapper.jar
--------------------------------------------------------------------------------
/.mvn/wrapper/maven-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.8.5/apache-maven-3.8.5-bin.zip
2 | wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Creative Commons Legal Code
2 |
3 | CC0 1.0 Universal
4 |
5 | CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE
6 | LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN
7 | ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS
8 | INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES
9 | REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS
10 | PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM
11 | THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED
12 | HEREUNDER.
13 |
14 | Statement of Purpose
15 |
16 | The laws of most jurisdictions throughout the world automatically confer
17 | exclusive Copyright and Related Rights (defined below) upon the creator
18 | and subsequent owner(s) (each and all, an "owner") of an original work of
19 | authorship and/or a database (each, a "Work").
20 |
21 | Certain owners wish to permanently relinquish those rights to a Work for
22 | the purpose of contributing to a commons of creative, cultural and
23 | scientific works ("Commons") that the public can reliably and without fear
24 | of later claims of infringement build upon, modify, incorporate in other
25 | works, reuse and redistribute as freely as possible in any form whatsoever
26 | and for any purposes, including without limitation commercial purposes.
27 | These owners may contribute to the Commons to promote the ideal of a free
28 | culture and the further production of creative, cultural and scientific
29 | works, or to gain reputation or greater distribution for their Work in
30 | part through the use and efforts of others.
31 |
32 | For these and/or other purposes and motivations, and without any
33 | expectation of additional consideration or compensation, the person
34 | associating CC0 with a Work (the "Affirmer"), to the extent that he or she
35 | is an owner of Copyright and Related Rights in the Work, voluntarily
36 | elects to apply CC0 to the Work and publicly distribute the Work under its
37 | terms, with knowledge of his or her Copyright and Related Rights in the
38 | Work and the meaning and intended legal effect of CC0 on those rights.
39 |
40 | 1. Copyright and Related Rights. A Work made available under CC0 may be
41 | protected by copyright and related or neighboring rights ("Copyright and
42 | Related Rights"). Copyright and Related Rights include, but are not
43 | limited to, the following:
44 |
45 | i. the right to reproduce, adapt, distribute, perform, display,
46 | communicate, and translate a Work;
47 | ii. moral rights retained by the original author(s) and/or performer(s);
48 | iii. publicity and privacy rights pertaining to a person's image or
49 | likeness depicted in a Work;
50 | iv. rights protecting against unfair competition in regards to a Work,
51 | subject to the limitations in paragraph 4(a), below;
52 | v. rights protecting the extraction, dissemination, use and reuse of data
53 | in a Work;
54 | vi. database rights (such as those arising under Directive 96/9/EC of the
55 | European Parliament and of the Council of 11 March 1996 on the legal
56 | protection of databases, and under any national implementation
57 | thereof, including any amended or successor version of such
58 | directive); and
59 | vii. other similar, equivalent or corresponding rights throughout the
60 | world based on applicable law or treaty, and any national
61 | implementations thereof.
62 |
63 | 2. Waiver. To the greatest extent permitted by, but not in contravention
64 | of, applicable law, Affirmer hereby overtly, fully, permanently,
65 | irrevocably and unconditionally waives, abandons, and surrenders all of
66 | Affirmer's Copyright and Related Rights and associated claims and causes
67 | of action, whether now known or unknown (including existing as well as
68 | future claims and causes of action), in the Work (i) in all territories
69 | worldwide, (ii) for the maximum duration provided by applicable law or
70 | treaty (including future time extensions), (iii) in any current or future
71 | medium and for any number of copies, and (iv) for any purpose whatsoever,
72 | including without limitation commercial, advertising or promotional
73 | purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each
74 | member of the public at large and to the detriment of Affirmer's heirs and
75 | successors, fully intending that such Waiver shall not be subject to
76 | revocation, rescission, cancellation, termination, or any other legal or
77 | equitable action to disrupt the quiet enjoyment of the Work by the public
78 | as contemplated by Affirmer's express Statement of Purpose.
79 |
80 | 3. Public License Fallback. Should any part of the Waiver for any reason
81 | be judged legally invalid or ineffective under applicable law, then the
82 | Waiver shall be preserved to the maximum extent permitted taking into
83 | account Affirmer's express Statement of Purpose. In addition, to the
84 | extent the Waiver is so judged Affirmer hereby grants to each affected
85 | person a royalty-free, non transferable, non sublicensable, non exclusive,
86 | irrevocable and unconditional license to exercise Affirmer's Copyright and
87 | Related Rights in the Work (i) in all territories worldwide, (ii) for the
88 | maximum duration provided by applicable law or treaty (including future
89 | time extensions), (iii) in any current or future medium and for any number
90 | of copies, and (iv) for any purpose whatsoever, including without
91 | limitation commercial, advertising or promotional purposes (the
92 | "License"). The License shall be deemed effective as of the date CC0 was
93 | applied by Affirmer to the Work. Should any part of the License for any
94 | reason be judged legally invalid or ineffective under applicable law, such
95 | partial invalidity or ineffectiveness shall not invalidate the remainder
96 | of the License, and in such case Affirmer hereby affirms that he or she
97 | will not (i) exercise any of his or her remaining Copyright and Related
98 | Rights in the Work or (ii) assert any associated claims and causes of
99 | action with respect to the Work, in either case contrary to Affirmer's
100 | express Statement of Purpose.
101 |
102 | 4. Limitations and Disclaimers.
103 |
104 | a. No trademark or patent rights held by Affirmer are waived, abandoned,
105 | surrendered, licensed or otherwise affected by this document.
106 | b. Affirmer offers the Work as-is and makes no representations or
107 | warranties of any kind concerning the Work, express, implied,
108 | statutory or otherwise, including without limitation warranties of
109 | title, merchantability, fitness for a particular purpose, non
110 | infringement, or the absence of latent or other defects, accuracy, or
111 | the present or absence of errors, whether or not discoverable, all to
112 | the greatest extent permissible under applicable law.
113 | c. Affirmer disclaims responsibility for clearing rights of other persons
114 | that may apply to the Work or any use thereof, including without
115 | limitation any person's Copyright and Related Rights in the Work.
116 | Further, Affirmer disclaims responsibility for obtaining any necessary
117 | consents, permissions or other rights required for any use of the
118 | Work.
119 | d. Affirmer understands and acknowledges that Creative Commons is not a
120 | party to this document and has no duty or obligation with respect to
121 | this CC0 or use of the Work.
122 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Space Shooter Game in JavaFX
2 |
3 | ## Table of Contents
4 |
5 | - [Overview](#overview)
6 | - [User Interface](#user-interface)
7 | - [Demo GIF](#demo-gif)
8 | - [Start Screen](#start-screen)
9 | - [Gameplay](#gameplay)
10 | - [Instructions](#instructions)
11 | - [Losing Screen](#losing-screen)
12 | - [Features](#features)
13 | - [Prerequisites](#prerequisites)
14 | - [Setup and Installation](#setup-and-installation)
15 | - [Necessary Configuration](#necessary-configuration)
16 | - [How to Play](#how-to-play)
17 | - [Contributing](#contributing)
18 | - [License](#license)
19 | - [Author](#author)
20 |
21 | ## Overview
22 |
23 | Space Shooter is a simple, lightweight but engaging JavaFX-based game where players navigate a spaceship, avoiding enemies and obstacles while trying to achieve the highest score possible. The game incorporates features such as enemy spawn logic, collision detection, power-ups, and a scoring system, showcasing the capabilities of JavaFX in creating interactive 2D games.
24 |
25 | ## User Interface
26 |
27 | ### Demo GIF
28 |
29 |
30 |
31 |
32 |
33 | > Our apologies for the low quality of the GIF. The actual game has a much smoother and visually appealing experience. Please try it out yourself! 😊
34 |
35 | ### Start Screen
36 |
37 |
38 |
39 |
40 |
41 | ### Gameplay
42 |
43 |
44 |
45 |
46 |
47 | ### Instructions
48 |
49 |
50 |
51 |
52 |
53 | ### Losing Screen
54 |
55 |
56 |
57 |
58 |
59 | ## Features
60 |
61 | - Control a spaceship using keyboard inputs (A, W, S, D, or arrow keys) to move and SPACE to shoot.
62 | - Enemies and boss enemies spawn at intervals, increasing the game's difficulty.
63 | - Collect power-ups to boost your abilities.
64 | - Score tracking and display, with the game increasing in difficulty as your score rises.
65 | - Lives system where players lose a life if an enemy reaches the bottom of the screen or collides with the player's spaceship.
66 | - Reset mechanism to start over once all lives are lost.
67 | - Sound effects for shooting, enemy hits, and power-up collection.
68 | - JavaDoc documentation for the game's classes and methods.
69 |
70 | ## Prerequisites
71 |
72 | - JDK 11 or higher.
73 | - JavaFX SDK (version compatible with your JDK).
74 | - Maven (for building and running the project).
75 |
76 | ## Setup and Installation
77 |
78 | 1. **JavaFX SDK**: Download the JavaFX SDK from [OpenJFX](https://openjfx.io/) and extract it to a known directory.
79 | 2. **Maven Configuration**: Ensure Maven is installed on your system and correctly configured. Alternatively, you can use an IDE like IntelliJ IDEA or Eclipse that supports Maven projects.
80 | 3. **Clone the Repository**:
81 | ```bash
82 | git clone https://github.com/hoangsonww/Space-Invader-Game-JavaFX.git
83 | cd Space-Invader-Game
84 | ```
85 |
86 | 4. **Update `pom.xml`**: Modify the `javafx-sdk.path` property in the `pom.xml` file to point to the JavaFX SDK's location on your system. This is necessary for Maven to build the project correctly.
87 | 5. **Build the Project**:
88 | ```bash
89 | mvn clean install
90 | ```
91 |
92 | 6. **Run the Application**:
93 | ```bash
94 | mvn javafx:run
95 | ```
96 |
97 | If you're using an IDE like IntelliJ IDEA, you can run the `SpaceShooter.java` file directly to start the game.
98 |
99 | ## Necessary Configuration
100 |
101 | Ensure JavaFX is correctly set up in your development environment:
102 | - **IntelliJ IDEA**:
103 | 1. Go to `File` > `Project Structure` > `Libraries`, add the JavaFX SDK as a library by navigating to its `lib` folder.
104 | 2. Modify your run configuration to include VM options for the JavaFX modules you use, e.g., `--module-path "path/to/javafx-sdk/lib" --add-modules javafx.controls,javafx.fxml,javafx.media`.
105 |
106 | - **Eclipse**:
107 | 1. Add the JavaFX SDK as an external JAR to your project's build path.
108 | 2. Adjust the run configurations to include the necessary VM arguments, as shown above for IntelliJ.
109 |
110 | ## How to Play
111 |
112 | - Use the A, W, S, D keys or arrow keys to move the spaceship.
113 | - Press SPACE to shoot at enemies.
114 | - Avoid letting enemies reach the bottom of the screen or colliding with them.
115 | - Collect power-ups to enhance your capabilities and increase your score.
116 | - The game ends when all lives are lost, but you can start over by resetting the game.
117 |
118 | ## Contributing
119 |
120 | Contributions to the Space Shooter game are welcome! Please fork the repository, make your changes, and submit a pull request with your improvements.
121 |
122 | ## License
123 |
124 | This project is licensed under the Creative Commons License. See the [LICENSE](LICENSE) file for more information.
125 |
126 | ## Author
127 |
128 | - [Son Nguyen](https://github.com/hoangsonww)
129 |
130 | ---
131 |
132 | Created with ❤️ by [Son Nguyen](https://github.com/hoangsonww) in 2024.
133 |
--------------------------------------------------------------------------------
/img/demo.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hoangsonww/Space-Invader-Game-JavaFX/d7e2ac3b28ca7aeb1de02e7a77005fcdf10a68a9/img/demo.gif
--------------------------------------------------------------------------------
/img/gameplay.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hoangsonww/Space-Invader-Game-JavaFX/d7e2ac3b28ca7aeb1de02e7a77005fcdf10a68a9/img/gameplay.png
--------------------------------------------------------------------------------
/img/instructions.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hoangsonww/Space-Invader-Game-JavaFX/d7e2ac3b28ca7aeb1de02e7a77005fcdf10a68a9/img/instructions.png
--------------------------------------------------------------------------------
/img/losing.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hoangsonww/Space-Invader-Game-JavaFX/d7e2ac3b28ca7aeb1de02e7a77005fcdf10a68a9/img/losing.png
--------------------------------------------------------------------------------
/img/start.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hoangsonww/Space-Invader-Game-JavaFX/d7e2ac3b28ca7aeb1de02e7a77005fcdf10a68a9/img/start.png
--------------------------------------------------------------------------------
/img/test.txt:
--------------------------------------------------------------------------------
1 |
2 | This is a test file!
3 |
--------------------------------------------------------------------------------
/mvnw:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 | # ----------------------------------------------------------------------------
3 | # Licensed to the Apache Software Foundation (ASF) under one
4 | # or more contributor license agreements. See the NOTICE file
5 | # distributed with this work for additional information
6 | # regarding copyright ownership. The ASF licenses this file
7 | # to you under the Apache License, Version 2.0 (the
8 | # "License"); you may not use this file except in compliance
9 | # with the License. You may obtain a copy of the License at
10 | #
11 | # https://www.apache.org/licenses/LICENSE-2.0
12 | #
13 | # Unless required by applicable law or agreed to in writing,
14 | # software distributed under the License is distributed on an
15 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16 | # KIND, either express or implied. See the License for the
17 | # specific language governing permissions and limitations
18 | # under the License.
19 | # ----------------------------------------------------------------------------
20 |
21 | # ----------------------------------------------------------------------------
22 | # Maven Start Up Batch script
23 | #
24 | # Required ENV vars:
25 | # ------------------
26 | # JAVA_HOME - location of a JDK home dir
27 | #
28 | # Optional ENV vars
29 | # -----------------
30 | # M2_HOME - location of maven2's installed home dir
31 | # MAVEN_OPTS - parameters passed to the Java VM when running Maven
32 | # e.g. to debug Maven itself, use
33 | # set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
34 | # MAVEN_SKIP_RC - flag to disable loading of mavenrc files
35 | # ----------------------------------------------------------------------------
36 |
37 | if [ -z "$MAVEN_SKIP_RC" ] ; then
38 |
39 | if [ -f /usr/local/etc/mavenrc ] ; then
40 | . /usr/local/etc/mavenrc
41 | fi
42 |
43 | if [ -f /etc/mavenrc ] ; then
44 | . /etc/mavenrc
45 | fi
46 |
47 | if [ -f "$HOME/.mavenrc" ] ; then
48 | . "$HOME/.mavenrc"
49 | fi
50 |
51 | fi
52 |
53 | # OS specific support. $var _must_ be set to either true or false.
54 | cygwin=false;
55 | darwin=false;
56 | mingw=false
57 | case "`uname`" in
58 | CYGWIN*) cygwin=true ;;
59 | MINGW*) mingw=true;;
60 | Darwin*) darwin=true
61 | # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home
62 | # See https://developer.apple.com/library/mac/qa/qa1170/_index.html
63 | if [ -z "$JAVA_HOME" ]; then
64 | if [ -x "/usr/libexec/java_home" ]; then
65 | export JAVA_HOME="`/usr/libexec/java_home`"
66 | else
67 | export JAVA_HOME="/Library/Java/Home"
68 | fi
69 | fi
70 | ;;
71 | esac
72 |
73 | if [ -z "$JAVA_HOME" ] ; then
74 | if [ -r /etc/gentoo-release ] ; then
75 | JAVA_HOME=`java-config --jre-home`
76 | fi
77 | fi
78 |
79 | if [ -z "$M2_HOME" ] ; then
80 | ## resolve links - $0 may be a link to maven's home
81 | PRG="$0"
82 |
83 | # need this for relative symlinks
84 | while [ -h "$PRG" ] ; do
85 | ls=`ls -ld "$PRG"`
86 | link=`expr "$ls" : '.*-> \(.*\)$'`
87 | if expr "$link" : '/.*' > /dev/null; then
88 | PRG="$link"
89 | else
90 | PRG="`dirname "$PRG"`/$link"
91 | fi
92 | done
93 |
94 | saveddir=`pwd`
95 |
96 | M2_HOME=`dirname "$PRG"`/..
97 |
98 | # make it fully qualified
99 | M2_HOME=`cd "$M2_HOME" && pwd`
100 |
101 | cd "$saveddir"
102 | # echo Using m2 at $M2_HOME
103 | fi
104 |
105 | # For Cygwin, ensure paths are in UNIX format before anything is touched
106 | if $cygwin ; then
107 | [ -n "$M2_HOME" ] &&
108 | M2_HOME=`cygpath --unix "$M2_HOME"`
109 | [ -n "$JAVA_HOME" ] &&
110 | JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
111 | [ -n "$CLASSPATH" ] &&
112 | CLASSPATH=`cygpath --path --unix "$CLASSPATH"`
113 | fi
114 |
115 | # For Mingw, ensure paths are in UNIX format before anything is touched
116 | if $mingw ; then
117 | [ -n "$M2_HOME" ] &&
118 | M2_HOME="`(cd "$M2_HOME"; pwd)`"
119 | [ -n "$JAVA_HOME" ] &&
120 | JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`"
121 | fi
122 |
123 | if [ -z "$JAVA_HOME" ]; then
124 | javaExecutable="`which javac`"
125 | if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then
126 | # readlink(1) is not available as standard on Solaris 10.
127 | readLink=`which readlink`
128 | if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then
129 | if $darwin ; then
130 | javaHome="`dirname \"$javaExecutable\"`"
131 | javaExecutable="`cd \"$javaHome\" && pwd -P`/javac"
132 | else
133 | javaExecutable="`readlink -f \"$javaExecutable\"`"
134 | fi
135 | javaHome="`dirname \"$javaExecutable\"`"
136 | javaHome=`expr "$javaHome" : '\(.*\)/bin'`
137 | JAVA_HOME="$javaHome"
138 | export JAVA_HOME
139 | fi
140 | fi
141 | fi
142 |
143 | if [ -z "$JAVACMD" ] ; then
144 | if [ -n "$JAVA_HOME" ] ; then
145 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
146 | # IBM's JDK on AIX uses strange locations for the executables
147 | JAVACMD="$JAVA_HOME/jre/sh/java"
148 | else
149 | JAVACMD="$JAVA_HOME/bin/java"
150 | fi
151 | else
152 | JAVACMD="`\\unset -f command; \\command -v java`"
153 | fi
154 | fi
155 |
156 | if [ ! -x "$JAVACMD" ] ; then
157 | echo "Error: JAVA_HOME is not defined correctly." >&2
158 | echo " We cannot execute $JAVACMD" >&2
159 | exit 1
160 | fi
161 |
162 | if [ -z "$JAVA_HOME" ] ; then
163 | echo "Warning: JAVA_HOME environment variable is not set."
164 | fi
165 |
166 | CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher
167 |
168 | # traverses directory structure from process work directory to filesystem root
169 | # first directory with .mvn subdirectory is considered project base directory
170 | find_maven_basedir() {
171 |
172 | if [ -z "$1" ]
173 | then
174 | echo "Path not specified to find_maven_basedir"
175 | return 1
176 | fi
177 |
178 | basedir="$1"
179 | wdir="$1"
180 | while [ "$wdir" != '/' ] ; do
181 | if [ -d "$wdir"/.mvn ] ; then
182 | basedir=$wdir
183 | break
184 | fi
185 | # workaround for JBEAP-8937 (on Solaris 10/Sparc)
186 | if [ -d "${wdir}" ]; then
187 | wdir=`cd "$wdir/.."; pwd`
188 | fi
189 | # end of workaround
190 | done
191 | echo "${basedir}"
192 | }
193 |
194 | # concatenates all lines of a file
195 | concat_lines() {
196 | if [ -f "$1" ]; then
197 | echo "$(tr -s '\n' ' ' < "$1")"
198 | fi
199 | }
200 |
201 | BASE_DIR=`find_maven_basedir "$(pwd)"`
202 | if [ -z "$BASE_DIR" ]; then
203 | exit 1;
204 | fi
205 |
206 | ##########################################################################################
207 | # Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
208 | # This allows using the maven wrapper in projects that prohibit checking in binary data.
209 | ##########################################################################################
210 | if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then
211 | if [ "$MVNW_VERBOSE" = true ]; then
212 | echo "Found .mvn/wrapper/maven-wrapper.jar"
213 | fi
214 | else
215 | if [ "$MVNW_VERBOSE" = true ]; then
216 | echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..."
217 | fi
218 | if [ -n "$MVNW_REPOURL" ]; then
219 | jarUrl="$MVNW_REPOURL/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar"
220 | else
221 | jarUrl="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar"
222 | fi
223 | while IFS="=" read key value; do
224 | case "$key" in (wrapperUrl) jarUrl="$value"; break ;;
225 | esac
226 | done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties"
227 | if [ "$MVNW_VERBOSE" = true ]; then
228 | echo "Downloading from: $jarUrl"
229 | fi
230 | wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar"
231 | if $cygwin; then
232 | wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"`
233 | fi
234 |
235 | if command -v wget > /dev/null; then
236 | if [ "$MVNW_VERBOSE" = true ]; then
237 | echo "Found wget ... using wget"
238 | fi
239 | if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
240 | wget "$jarUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath"
241 | else
242 | wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath"
243 | fi
244 | elif command -v curl > /dev/null; then
245 | if [ "$MVNW_VERBOSE" = true ]; then
246 | echo "Found curl ... using curl"
247 | fi
248 | if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
249 | curl -o "$wrapperJarPath" "$jarUrl" -f
250 | else
251 | curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f
252 | fi
253 |
254 | else
255 | if [ "$MVNW_VERBOSE" = true ]; then
256 | echo "Falling back to using Java to download"
257 | fi
258 | javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java"
259 | # For Cygwin, switch paths to Windows format before running javac
260 | if $cygwin; then
261 | javaClass=`cygpath --path --windows "$javaClass"`
262 | fi
263 | if [ -e "$javaClass" ]; then
264 | if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
265 | if [ "$MVNW_VERBOSE" = true ]; then
266 | echo " - Compiling MavenWrapperDownloader.java ..."
267 | fi
268 | # Compiling the Java class
269 | ("$JAVA_HOME/bin/javac" "$javaClass")
270 | fi
271 | if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
272 | # Running the downloader
273 | if [ "$MVNW_VERBOSE" = true ]; then
274 | echo " - Running MavenWrapperDownloader.java ..."
275 | fi
276 | ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR")
277 | fi
278 | fi
279 | fi
280 | fi
281 | ##########################################################################################
282 | # End of extension
283 | ##########################################################################################
284 |
285 | export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}
286 | if [ "$MVNW_VERBOSE" = true ]; then
287 | echo $MAVEN_PROJECTBASEDIR
288 | fi
289 | MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
290 |
291 | # For Cygwin, switch paths to Windows format before running java
292 | if $cygwin; then
293 | [ -n "$M2_HOME" ] &&
294 | M2_HOME=`cygpath --path --windows "$M2_HOME"`
295 | [ -n "$JAVA_HOME" ] &&
296 | JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"`
297 | [ -n "$CLASSPATH" ] &&
298 | CLASSPATH=`cygpath --path --windows "$CLASSPATH"`
299 | [ -n "$MAVEN_PROJECTBASEDIR" ] &&
300 | MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"`
301 | fi
302 |
303 | # Provide a "standardized" way to retrieve the CLI args that will
304 | # work with both Windows and non-Windows executions.
305 | MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@"
306 | export MAVEN_CMD_LINE_ARGS
307 |
308 | WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
309 |
310 | exec "$JAVACMD" \
311 | $MAVEN_OPTS \
312 | $MAVEN_DEBUG_OPTS \
313 | -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
314 | "-Dmaven.home=${M2_HOME}" \
315 | "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
316 | ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@"
317 |
--------------------------------------------------------------------------------
/mvnw.cmd:
--------------------------------------------------------------------------------
1 | @REM ----------------------------------------------------------------------------
2 | @REM Licensed to the Apache Software Foundation (ASF) under one
3 | @REM or more contributor license agreements. See the NOTICE file
4 | @REM distributed with this work for additional information
5 | @REM regarding copyright ownership. The ASF licenses this file
6 | @REM to you under the Apache License, Version 2.0 (the
7 | @REM "License"); you may not use this file except in compliance
8 | @REM with the License. You may obtain a copy of the License at
9 | @REM
10 | @REM https://www.apache.org/licenses/LICENSE-2.0
11 | @REM
12 | @REM Unless required by applicable law or agreed to in writing,
13 | @REM software distributed under the License is distributed on an
14 | @REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 | @REM KIND, either express or implied. See the License for the
16 | @REM specific language governing permissions and limitations
17 | @REM under the License.
18 | @REM ----------------------------------------------------------------------------
19 |
20 | @REM ----------------------------------------------------------------------------
21 | @REM Maven Start Up Batch script
22 | @REM
23 | @REM Required ENV vars:
24 | @REM JAVA_HOME - location of a JDK home dir
25 | @REM
26 | @REM Optional ENV vars
27 | @REM M2_HOME - location of maven2's installed home dir
28 | @REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
29 | @REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending
30 | @REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
31 | @REM e.g. to debug Maven itself, use
32 | @REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
33 | @REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
34 | @REM ----------------------------------------------------------------------------
35 |
36 | @REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
37 | @echo off
38 | @REM set title of command window
39 | title %0
40 | @REM enable echoing by setting MAVEN_BATCH_ECHO to 'on'
41 | @if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
42 |
43 | @REM set %HOME% to equivalent of $HOME
44 | if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
45 |
46 | @REM Execute a user defined script before this one
47 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
48 | @REM check for pre script, once with legacy .bat ending and once with .cmd ending
49 | if exist "%USERPROFILE%\mavenrc_pre.bat" call "%USERPROFILE%\mavenrc_pre.bat" %*
50 | if exist "%USERPROFILE%\mavenrc_pre.cmd" call "%USERPROFILE%\mavenrc_pre.cmd" %*
51 | :skipRcPre
52 |
53 | @setlocal
54 |
55 | set ERROR_CODE=0
56 |
57 | @REM To isolate internal variables from possible post scripts, we use another setlocal
58 | @setlocal
59 |
60 | @REM ==== START VALIDATION ====
61 | if not "%JAVA_HOME%" == "" goto OkJHome
62 |
63 | echo.
64 | echo Error: JAVA_HOME not found in your environment. >&2
65 | echo Please set the JAVA_HOME variable in your environment to match the >&2
66 | echo location of your Java installation. >&2
67 | echo.
68 | goto error
69 |
70 | :OkJHome
71 | if exist "%JAVA_HOME%\bin\java.exe" goto init
72 |
73 | echo.
74 | echo Error: JAVA_HOME is set to an invalid directory. >&2
75 | echo JAVA_HOME = "%JAVA_HOME%" >&2
76 | echo Please set the JAVA_HOME variable in your environment to match the >&2
77 | echo location of your Java installation. >&2
78 | echo.
79 | goto error
80 |
81 | @REM ==== END VALIDATION ====
82 |
83 | :init
84 |
85 | @REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
86 | @REM Fallback to current working directory if not found.
87 |
88 | set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
89 | IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
90 |
91 | set EXEC_DIR=%CD%
92 | set WDIR=%EXEC_DIR%
93 | :findBaseDir
94 | IF EXIST "%WDIR%"\.mvn goto baseDirFound
95 | cd ..
96 | IF "%WDIR%"=="%CD%" goto baseDirNotFound
97 | set WDIR=%CD%
98 | goto findBaseDir
99 |
100 | :baseDirFound
101 | set MAVEN_PROJECTBASEDIR=%WDIR%
102 | cd "%EXEC_DIR%"
103 | goto endDetectBaseDir
104 |
105 | :baseDirNotFound
106 | set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
107 | cd "%EXEC_DIR%"
108 |
109 | :endDetectBaseDir
110 |
111 | IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
112 |
113 | @setlocal EnableExtensions EnableDelayedExpansion
114 | for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
115 | @endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
116 |
117 | :endReadAdditionalConfig
118 |
119 | SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
120 | set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
121 | set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
122 |
123 | set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar"
124 |
125 | FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO (
126 | IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B
127 | )
128 |
129 | @REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
130 | @REM This allows using the maven wrapper in projects that prohibit checking in binary data.
131 | if exist %WRAPPER_JAR% (
132 | if "%MVNW_VERBOSE%" == "true" (
133 | echo Found %WRAPPER_JAR%
134 | )
135 | ) else (
136 | if not "%MVNW_REPOURL%" == "" (
137 | SET DOWNLOAD_URL="%MVNW_REPOURL%/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar"
138 | )
139 | if "%MVNW_VERBOSE%" == "true" (
140 | echo Couldn't find %WRAPPER_JAR%, downloading it ...
141 | echo Downloading from: %DOWNLOAD_URL%
142 | )
143 |
144 | powershell -Command "&{"^
145 | "$webclient = new-object System.Net.WebClient;"^
146 | "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^
147 | "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^
148 | "}"^
149 | "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^
150 | "}"
151 | if "%MVNW_VERBOSE%" == "true" (
152 | echo Finished downloading %WRAPPER_JAR%
153 | )
154 | )
155 | @REM End of extension
156 |
157 | @REM Provide a "standardized" way to retrieve the CLI args that will
158 | @REM work with both Windows and non-Windows executions.
159 | set MAVEN_CMD_LINE_ARGS=%*
160 |
161 | %MAVEN_JAVA_EXE% ^
162 | %JVM_CONFIG_MAVEN_PROPS% ^
163 | %MAVEN_OPTS% ^
164 | %MAVEN_DEBUG_OPTS% ^
165 | -classpath %WRAPPER_JAR% ^
166 | "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" ^
167 | %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
168 | if ERRORLEVEL 1 goto error
169 | goto end
170 |
171 | :error
172 | set ERROR_CODE=1
173 |
174 | :end
175 | @endlocal & set ERROR_CODE=%ERROR_CODE%
176 |
177 | if not "%MAVEN_SKIP_RC%"=="" goto skipRcPost
178 | @REM check for post script, once with legacy .bat ending and once with .cmd ending
179 | if exist "%USERPROFILE%\mavenrc_post.bat" call "%USERPROFILE%\mavenrc_post.bat"
180 | if exist "%USERPROFILE%\mavenrc_post.cmd" call "%USERPROFILE%\mavenrc_post.cmd"
181 | :skipRcPost
182 |
183 | @REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
184 | if "%MAVEN_BATCH_PAUSE%"=="on" pause
185 |
186 | if "%MAVEN_TERMINATE_CMD%"=="on" exit %ERROR_CODE%
187 |
188 | cmd /C exit /B %ERROR_CODE%
189 |
--------------------------------------------------------------------------------
/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 | 4.0.0
6 |
7 | com.example
8 | SpaceShooterGameJavaFX
9 | 1.0-SNAPSHOT
10 | Space Shooter Game JavaFX
11 |
12 |
13 | UTF-8
14 | 5.9.1
15 |
16 |
17 |
18 |
19 | org.openjfx
20 | javafx-controls
21 | 17.0.2
22 |
23 |
24 | org.openjfx
25 | javafx-fxml
26 | 17.0.2
27 |
28 |
29 |
30 | org.junit.jupiter
31 | junit-jupiter-api
32 | ${junit.version}
33 | test
34 |
35 |
36 | org.junit.jupiter
37 | junit-jupiter-engine
38 | ${junit.version}
39 | test
40 |
41 |
42 |
43 |
44 |
45 |
46 | org.apache.maven.plugins
47 | maven-compiler-plugin
48 | 3.10.1
49 |
50 | 17
51 | 17
52 |
53 |
54 |
55 | org.openjfx
56 | javafx-maven-plugin
57 | 0.0.8
58 |
59 |
60 |
61 | default-cli
62 |
63 |
64 | com.example.spaceshootergamejavafx/com.example.spaceshootergamejavafx.SpaceShooter
65 |
66 | app
67 | app
68 | app
69 | true
70 | true
71 | true
72 |
73 |
74 |
75 |
76 |
77 |
78 |
--------------------------------------------------------------------------------
/src/main/java/com/example/spaceshootergamejavafx/BossEnemy.java:
--------------------------------------------------------------------------------
1 | package com.example.spaceshootergamejavafx;
2 |
3 | import javafx.scene.canvas.GraphicsContext;
4 | import javafx.scene.image.Image;
5 | import javafx.scene.paint.Color;
6 |
7 | import java.util.List;
8 | import java.util.Objects;
9 |
10 | /** BossEnemy class represents a boss enemy in the game. */
11 | public class BossEnemy extends Enemy {
12 |
13 | /** Health of the boss enemy. */
14 | private int health = 5;
15 |
16 | /** Width of the boss enemy hitbox. */
17 | private static final int WIDTH = 50;
18 |
19 | /** Height of the boss enemy hitbox. */
20 | private static final int HEIGHT = 50; // Hitbox height
21 |
22 | /** Number of hits the boss can take before dying. */
23 | private int numHits = 5;
24 |
25 | /** Image for the boss enemy. */
26 | private final Image bossImage;
27 |
28 | /** Horizontal movement speed of the boss enemy. */
29 | private double horizontalSpeed = 1.5;
30 |
31 | /**
32 | * Creates a new BossEnemy object at the specified position.
33 | *
34 | * @param x X-coordinate of the boss enemy.
35 | * @param y Y-coordinate of the boss enemy.
36 | */
37 | public BossEnemy(double x, double y) {
38 | super(x, y);
39 | SPEED = 1.0; // Vertical speed
40 | health = 5;
41 |
42 | // Load the boss image from resources
43 | this.bossImage = new Image(Objects.requireNonNull(getClass().getResourceAsStream("/boss.png")));
44 | }
45 |
46 | /** Updates the boss enemy's position and behavior. */
47 | @Override
48 | public void update() {
49 | // BossEnemy moves vertically down
50 | if (y < 40) {
51 | y += SPEED;
52 | }
53 |
54 | // BossEnemy also moves horizontally back and forth
55 | x += horizontalSpeed;
56 |
57 | // Reverse direction if the boss reaches the edges of the screen
58 | if (x - WIDTH / 2 <= 0 || x + WIDTH / 2 >= SpaceShooter.WIDTH) {
59 | horizontalSpeed = -horizontalSpeed;
60 | }
61 | }
62 |
63 | /** Damages the boss enemy by reducing its health. */
64 | public void takeDamage() {
65 | health--;
66 | if (health <= 0) {
67 | setDead(true);
68 | }
69 | }
70 |
71 | /**
72 | * Shoots bullets at the player.
73 | *
74 | * @param newObjects List of GameObjects to add new objects to.
75 | */
76 | public void shoot(List newObjects) {
77 | if (Math.random() < 0.015) {
78 | newObjects.add(new EnemyBullet(x, y + HEIGHT / 2));
79 | }
80 | }
81 |
82 | /** Checks if the boss enemy is dead. */
83 | public boolean isDead() {
84 | return health <= 0;
85 | }
86 |
87 | /**
88 | * Renders the boss enemy on the screen.
89 | *
90 | * @param gc GraphicsContext object to render the boss enemy.
91 | */
92 | @Override
93 | public void render(GraphicsContext gc) {
94 | if (bossImage != null) {
95 | // Double the visual size of the image
96 | double scaledWidth = WIDTH * 2;
97 | double scaledHeight = HEIGHT * 2;
98 |
99 | // Center the image around the hitbox's center
100 | double drawX = x - scaledWidth / 2;
101 | double drawY = y - scaledHeight / 2;
102 |
103 | gc.drawImage(bossImage, drawX, drawY, scaledWidth, scaledHeight);
104 | } else {
105 | // Fallback: Render a blue rectangle to match the hitbox size
106 | gc.setFill(Color.BLUE);
107 | gc.fillRect(x - WIDTH / 2, y - HEIGHT / 2, WIDTH, HEIGHT);
108 | }
109 | }
110 |
111 | /** Damages the boss enemy by reducing its health. */
112 | public void hit() {
113 | health--;
114 | if (health <= 0) {
115 | setDead(true);
116 | }
117 | }
118 | }
119 |
--------------------------------------------------------------------------------
/src/main/java/com/example/spaceshootergamejavafx/Bullet.java:
--------------------------------------------------------------------------------
1 | package com.example.spaceshootergamejavafx;
2 |
3 | import javafx.scene.canvas.GraphicsContext;
4 | import javafx.scene.paint.Color;
5 |
6 | /** Represents a bullet in the game */
7 | public class Bullet extends GameObject {
8 |
9 | /** Width of the bullet */
10 | public static final int WIDTH = 4;
11 |
12 | /** Height of the bullet */
13 | public static final int HEIGHT = 15;
14 |
15 | /** Speed of the bullet */
16 | private static final double SPEED = 7;
17 |
18 | /** Flag to indicate if the bullet is dead */
19 | private boolean dead = false;
20 |
21 | /**
22 | * Creates a new bullet at the specified position
23 | *
24 | * @param x The x-coordinate of the bullet
25 | * @param y The y-coordinate of the bullet
26 | */
27 | public Bullet(double x, double y) {
28 | super(x, y, WIDTH, HEIGHT);
29 | }
30 |
31 | /** Updates the bullet's position */
32 | @Override
33 | public void update() {
34 | y -= SPEED;
35 | }
36 |
37 | /**
38 | * Renders the bullet on the screen
39 | *
40 | * @param gc The GraphicsContext to render the bullet
41 | */
42 | @Override
43 | public void render(GraphicsContext gc) {
44 | gc.setFill(Color.YELLOW);
45 | gc.fillRect(x - WIDTH / 2, y - HEIGHT / 2, WIDTH, HEIGHT);
46 | }
47 |
48 | /**
49 | * Returns the width of the bullet
50 | *
51 | * @return The width of the bullet
52 | */
53 | @Override
54 | public double getWidth() {
55 | return WIDTH;
56 | }
57 |
58 | /**
59 | * Returns the height of the bullet
60 | *
61 | * @return The height of the bullet
62 | */
63 | @Override
64 | public double getHeight() {
65 | return HEIGHT;
66 | }
67 |
68 | /**
69 | * Sets the dead flag for the bullet
70 | *
71 | * @param dead The dead flag to set
72 | */
73 | public void setDead(boolean dead) {
74 | this.dead = dead;
75 | }
76 |
77 | /**
78 | * Returns whether the bullet is dead
79 | *
80 | * @return True if the bullet is dead, false otherwise
81 | */
82 | @Override
83 | public boolean isDead() {
84 | return dead;
85 | }
86 | }
87 |
--------------------------------------------------------------------------------
/src/main/java/com/example/spaceshootergamejavafx/Enemy.java:
--------------------------------------------------------------------------------
1 | package com.example.spaceshootergamejavafx;
2 |
3 | import javafx.scene.canvas.GraphicsContext;
4 | import javafx.scene.image.Image;
5 | import javafx.scene.paint.Color;
6 |
7 | import java.util.Objects;
8 |
9 | /** Represents an enemy object in the game. */
10 | public class Enemy extends GameObject {
11 |
12 | /** Width of the enemy hitbox. */
13 | protected static final int WIDTH = 30;
14 |
15 | /** Height of the enemy hitbox. */
16 | protected static final int HEIGHT = 30;
17 |
18 | /** Speed of the enemy. */
19 | public static double SPEED = 1;
20 |
21 | /** Image for the enemy. */
22 | private final Image enemyImage;
23 |
24 | /** Flag to indicate if the enemy is dead. */
25 | private boolean dead = false;
26 |
27 | /**
28 | * Creates a new enemy object at the specified position.
29 | *
30 | * @param x X-coordinate of the enemy.
31 | * @param y Y-coordinate of the enemy.
32 | */
33 | public Enemy(double x, double y) {
34 | super(x, y, WIDTH, HEIGHT);
35 | // Load the enemy image from resources
36 | this.enemyImage =
37 | new Image(Objects.requireNonNull(getClass().getResourceAsStream("/enemy.png")));
38 | }
39 |
40 | /** Updates the enemy's position. */
41 | @Override
42 | public void update() {
43 | y += SPEED;
44 | }
45 |
46 | /**
47 | * Renders the enemy on the screen.
48 | *
49 | * @param gc The GraphicsContext to render the enemy.
50 | */
51 | @Override
52 | public void render(GraphicsContext gc) {
53 | if (enemyImage != null) {
54 | // Draw the enemy image, scaled to fit the enemy's dimensions
55 | gc.drawImage(enemyImage, x - WIDTH / 2, y - HEIGHT / 2, WIDTH, HEIGHT);
56 | } else {
57 | // Fallback: Render a red rectangle if the image is not loaded
58 | gc.setFill(Color.RED);
59 | gc.fillRect(x - WIDTH / 2, y - HEIGHT / 2, WIDTH, HEIGHT);
60 | }
61 | }
62 |
63 | /**
64 | * Returns the width of the enemy.
65 | *
66 | * @return The width of the enemy.
67 | */
68 | @Override
69 | public double getWidth() {
70 | return WIDTH;
71 | }
72 |
73 | /**
74 | * Returns the height of the enemy.
75 | *
76 | * @return The height of the enemy.
77 | */
78 | @Override
79 | public double getHeight() {
80 | return HEIGHT;
81 | }
82 |
83 | /**
84 | * Sets the dead flag for the enemy.
85 | *
86 | * @param dead The dead flag to set.
87 | */
88 | public void setDead(boolean dead) {
89 | this.dead = dead;
90 | }
91 |
92 | /**
93 | * Returns whether the enemy is dead.
94 | *
95 | * @return True if the enemy is dead, false otherwise.
96 | */
97 | @Override
98 | public boolean isDead() {
99 | return dead;
100 | }
101 | }
102 |
--------------------------------------------------------------------------------
/src/main/java/com/example/spaceshootergamejavafx/EnemyBullet.java:
--------------------------------------------------------------------------------
1 | package com.example.spaceshootergamejavafx;
2 |
3 | import javafx.scene.canvas.GraphicsContext;
4 | import javafx.scene.paint.Color;
5 |
6 | /** Represents a bullet fired by an enemy */
7 | public class EnemyBullet extends GameObject {
8 |
9 | /** Width of the bullet */
10 | public static final int WIDTH = 4;
11 |
12 | /** Height of the bullet */
13 | public static final int HEIGHT = 20;
14 |
15 | /** Speed of the bullet */
16 | private static final double SPEED = 3;
17 |
18 | /** Flag to indicate if the bullet is dead */
19 | private boolean dead = false;
20 |
21 | /**
22 | * Creates a new enemy bullet at the specified position
23 | *
24 | * @param x The x-coordinate of the bullet
25 | * @param y The y-coordinate of the bullet
26 | */
27 | public EnemyBullet(double x, double y) {
28 | super(x, y, WIDTH, HEIGHT);
29 | }
30 |
31 | /** Updates the bullet's position */
32 | @Override
33 | public void update() {
34 | y += SPEED;
35 | }
36 |
37 | /**
38 | * Renders the bullet on the screen
39 | *
40 | * @param gc The GraphicsContext to render the bullet
41 | */
42 | @Override
43 | public void render(GraphicsContext gc) {
44 | gc.setFill(Color.RED);
45 | gc.fillRect(x - WIDTH / 2, y - HEIGHT / 2, WIDTH, HEIGHT);
46 | }
47 |
48 | /**
49 | * Returns the width of the bullet
50 | *
51 | * @return The width of the bullet
52 | */
53 | @Override
54 | public double getWidth() {
55 | return WIDTH;
56 | }
57 |
58 | /**
59 | * Returns the height of the bullet
60 | *
61 | * @return The height of the bullet
62 | */
63 | @Override
64 | public double getHeight() {
65 | return HEIGHT;
66 | }
67 |
68 | /**
69 | * Sets the dead flag for the bullet
70 | *
71 | * @param dead The dead flag to set
72 | */
73 | public void setDead(boolean dead) {
74 | this.dead = dead;
75 | }
76 |
77 | /**
78 | * Returns whether the bullet is dead
79 | *
80 | * @return True if the bullet is dead, false otherwise
81 | */
82 | @Override
83 | public boolean isDead() {
84 | return dead;
85 | }
86 | }
87 |
--------------------------------------------------------------------------------
/src/main/java/com/example/spaceshootergamejavafx/GameObject.java:
--------------------------------------------------------------------------------
1 | package com.example.spaceshootergamejavafx;
2 |
3 | import javafx.scene.canvas.GraphicsContext;
4 | import javafx.geometry.Bounds;
5 | import javafx.scene.shape.Rectangle;
6 |
7 | /** Represents a game object in the game */
8 | public abstract class GameObject {
9 |
10 | /** X-coordinate of the game object */
11 | protected double x;
12 |
13 | /** Y-coordinate of the game object */
14 | protected double y;
15 |
16 | /** Width of the game object */
17 | protected double width;
18 |
19 | /** Height of the game object */
20 | protected double height;
21 |
22 | /**
23 | * Creates a new game object at the specified position with the given dimensions.
24 | *
25 | * @param x The x-coordinate of the game object
26 | * @param y The y-coordinate of the game object
27 | * @param width The width of the game object
28 | * @param height The height of the game object
29 | */
30 | public GameObject(double x, double y, double width, double height) {
31 | this.x = x;
32 | this.y = y;
33 | this.width = width;
34 | this.height = height;
35 | }
36 |
37 | /** Updates the game object's position and behavior. */
38 | public abstract void update();
39 |
40 | /**
41 | * Renders the game object on the screen.
42 | *
43 | * @param gc The GraphicsContext to render the game object
44 | */
45 | public abstract void render(GraphicsContext gc);
46 |
47 | /**
48 | * Checks if the game object is dead.
49 | *
50 | * @return true if the game object is dead, false otherwise
51 | */
52 | public abstract boolean isDead();
53 |
54 | /**
55 | * Returns the x-coordinate of the game object.
56 | *
57 | * @return The x-coordinate of the game object
58 | */
59 | public double getX() {
60 | return x;
61 | }
62 |
63 | /**
64 | * Returns the y-coordinate of the game object.
65 | *
66 | * @return The y-coordinate of the game object
67 | */
68 | public double getY() {
69 | return y;
70 | }
71 |
72 | /**
73 | * Returns the bounds of the game object.
74 | *
75 | * @return The bounds of the game object
76 | */
77 | public Bounds getBounds() {
78 | return new Rectangle(x - getWidth() / 2, y - getHeight() / 2, getWidth(), getHeight())
79 | .getBoundsInLocal();
80 | }
81 |
82 | /**
83 | * Returns the width of the game object.
84 | *
85 | * @return The width of the game object
86 | */
87 | public abstract double getWidth();
88 |
89 | /**
90 | * Returns the height of the game object.
91 | *
92 | * @return The height of the game object
93 | */
94 | public abstract double getHeight();
95 | }
96 |
--------------------------------------------------------------------------------
/src/main/java/com/example/spaceshootergamejavafx/Player.java:
--------------------------------------------------------------------------------
1 | package com.example.spaceshootergamejavafx;
2 |
3 | import javafx.scene.canvas.GraphicsContext;
4 | import javafx.scene.image.Image;
5 | import javafx.scene.paint.Color;
6 |
7 | import java.util.List;
8 | import java.util.Objects;
9 |
10 | /** Represents the player object in the game */
11 | public class Player extends GameObject {
12 |
13 | /** Width of the player hitbox */
14 | private static final int WIDTH = 40; // Updated to 2x the original size
15 |
16 | /** Height of the player hitbox */
17 | private static final int HEIGHT = 40; // Updated to 2x the original size
18 |
19 | /** Speed of the player */
20 | private static final double SPEED = 5;
21 |
22 | /** Flags to indicate move left direction */
23 | private boolean moveLeft;
24 |
25 | /** Flags to indicate move right direction */
26 | private boolean moveRight;
27 |
28 | /** Flags to indicate move forward direction */
29 | private boolean moveForward;
30 |
31 | /** Flags to indicate move backward direction */
32 | private boolean moveBackward;
33 |
34 | /** Health of the player */
35 | private int health = 20;
36 |
37 | /** Image for the player */
38 | private final Image overlayImage; // Overlay image for the player
39 |
40 | /** Stores the dead flag for the player */
41 | private boolean dead = false;
42 |
43 | /**
44 | * Creates a new player at the specified position
45 | *
46 | * @param x The x-coordinate of the player
47 | * @param y The y-coordinate of the player
48 | */
49 | public Player(double x, double y) {
50 | super(x, y, WIDTH, HEIGHT);
51 | // Load the overlay image from resources
52 | this.overlayImage =
53 | new Image(Objects.requireNonNull(getClass().getResourceAsStream("/player.png")));
54 | }
55 |
56 | /**
57 | * Returns the width of the player hitbox
58 | *
59 | * @return The width of the player hitbox
60 | */
61 | @Override
62 | public double getWidth() {
63 | return WIDTH;
64 | }
65 |
66 | /**
67 | * Returns the height of the player hitbox
68 | *
69 | * @return The height of the player hitbox
70 | */
71 | @Override
72 | public double getHeight() {
73 | return HEIGHT;
74 | }
75 |
76 | /**
77 | * Returns the health of the player
78 | *
79 | * @return The health of the player
80 | */
81 | public int getHealth() {
82 | return health;
83 | }
84 |
85 | /**
86 | * Sets the health of the player
87 | *
88 | * @param health The health of the player
89 | */
90 | public void setHealth(int health) {
91 | this.health = health;
92 | }
93 |
94 | /** Updates the player's position */
95 | @Override
96 | public void update() {
97 | // Move left
98 | if (moveLeft && x - WIDTH / 2 - SPEED >= 0) {
99 | x -= SPEED;
100 | }
101 |
102 | // Move right
103 | if (moveRight && x + WIDTH / 2 + SPEED <= SpaceShooter.WIDTH) {
104 | x += SPEED;
105 | }
106 |
107 | // Move up
108 | if (moveForward && y - HEIGHT / 2 - SPEED >= 0) {
109 | y -= SPEED;
110 | }
111 |
112 | // Move down
113 | if (moveBackward && y + HEIGHT / 2 + SPEED <= SpaceShooter.HEIGHT) {
114 | y += SPEED;
115 | }
116 | }
117 |
118 | /**
119 | * Renders the player on the screen
120 | *
121 | * @param gc The GraphicsContext to render the player
122 | */
123 | @Override
124 | public void render(GraphicsContext gc) {
125 | // Check if the overlay image exists
126 | if (overlayImage != null) {
127 | double imageWidth = overlayImage.getWidth();
128 | double imageHeight = overlayImage.getHeight();
129 |
130 | // Calculate aspect ratio
131 | double aspectRatio = imageWidth / imageHeight;
132 |
133 | // Double the size of the visual image dimensions
134 | double scaledWidth = WIDTH * 2; // Double the width
135 | double scaledHeight = HEIGHT * 2; // Double the height
136 |
137 | // Maintain aspect ratio
138 | if (scaledHeight > scaledWidth / aspectRatio) {
139 | scaledHeight = scaledWidth / aspectRatio;
140 | } else {
141 | scaledWidth = scaledHeight * aspectRatio;
142 | }
143 |
144 | // Center the image within the hitbox
145 | double drawX = x - scaledWidth / 2;
146 | double drawY = y - scaledHeight / 2;
147 |
148 | gc.drawImage(overlayImage, drawX, drawY, scaledWidth, scaledHeight);
149 | } else {
150 | // Fallback: Render a rectangle if the image is not loaded
151 | gc.setFill(Color.BLUE);
152 | gc.fillRect(x - WIDTH / 2, y - HEIGHT / 2, WIDTH, HEIGHT);
153 | }
154 | }
155 |
156 | /**
157 | * Sets the move left flag
158 | *
159 | * @param moveLeft The move left flag to set
160 | */
161 | public void setMoveLeft(boolean moveLeft) {
162 | this.moveLeft = moveLeft;
163 | }
164 |
165 | /**
166 | * Sets the move right flag
167 | *
168 | * @param moveRight The move right flag to set
169 | */
170 | public void setMoveRight(boolean moveRight) {
171 | this.moveRight = moveRight;
172 | }
173 |
174 | /**
175 | * Sets the move forward flag
176 | *
177 | * @param moveForward The move forward flag to set
178 | */
179 | public void setMoveForward(boolean moveForward) {
180 | this.moveForward = moveForward;
181 | }
182 |
183 | /**
184 | * Sets the move backward flag
185 | *
186 | * @param moveBackward The move backward flag to set
187 | */
188 | public void setMoveBackward(boolean moveBackward) {
189 | this.moveBackward = moveBackward;
190 | }
191 |
192 | /**
193 | * Shoots a bullet from the player
194 | *
195 | * @param newObjects The list of new objects to add the bullet to
196 | */
197 | public void shoot(List newObjects) {
198 | Bullet bullet = new Bullet(x, y - HEIGHT / 2 - Bullet.HEIGHT);
199 | newObjects.add(bullet);
200 | }
201 |
202 | /**
203 | * Sets the dead flag for the player
204 | *
205 | * @param dead The dead flag to set
206 | */
207 | public void setDead(boolean dead) {
208 | this.dead = dead;
209 | }
210 |
211 | /**
212 | * Returns whether the player is dead
213 | *
214 | * @return true if the player is dead, false otherwise
215 | */
216 | @Override
217 | public boolean isDead() {
218 | return dead;
219 | }
220 | }
221 |
--------------------------------------------------------------------------------
/src/main/java/com/example/spaceshootergamejavafx/PowerUp.java:
--------------------------------------------------------------------------------
1 | package com.example.spaceshootergamejavafx;
2 |
3 | import javafx.scene.canvas.GraphicsContext;
4 | import javafx.scene.image.Image;
5 | import javafx.scene.paint.Color;
6 |
7 | import java.util.Objects;
8 |
9 | /** Represents a power-up in the game */
10 | public class PowerUp extends GameObject {
11 |
12 | /** Width of the power-up */
13 | public static final int WIDTH = 20; // Hitbox width remains unchanged
14 |
15 | /** Height of the power-up */
16 | public static final int HEIGHT = 20; // Hitbox height remains unchanged
17 |
18 | /** Speed of the power-up */
19 | private static final double SPEED = 2;
20 |
21 | /** Flag to indicate if the power-up is dead */
22 | private boolean isDead = false;
23 |
24 | /** Image for the power-up */
25 | private final Image powerUpImage; // Image for the power-up
26 |
27 | /**
28 | * Creates a new power-up at the specified position
29 | *
30 | * @param x The x-coordinate of the power-up
31 | * @param y The y-coordinate of the power-up
32 | */
33 | public PowerUp(double x, double y) {
34 | super(x, y, WIDTH, HEIGHT);
35 | // Load the power-up image from resources
36 | this.powerUpImage =
37 | new Image(Objects.requireNonNull(getClass().getResourceAsStream("/powerup.png")));
38 | }
39 |
40 | /** Updates the power-up's position */
41 | @Override
42 | public void update() {
43 | y += SPEED;
44 | }
45 |
46 | /**
47 | * Renders the power-up on the screen
48 | *
49 | * @param gc The GraphicsContext to render the power-up
50 | */
51 | @Override
52 | public void render(GraphicsContext gc) {
53 | if (powerUpImage != null) {
54 | // Double the visual size of the image
55 | double scaledWidth = WIDTH * 2;
56 | double scaledHeight = HEIGHT * 2;
57 |
58 | // Center the image around the hitbox's center
59 | double drawX = x - scaledWidth / 2;
60 | double drawY = y - scaledHeight / 2;
61 |
62 | gc.drawImage(powerUpImage, drawX, drawY, scaledWidth, scaledHeight);
63 | } else {
64 | // Fallback: Render a green rectangle to match the hitbox size
65 | gc.setFill(Color.GREEN);
66 | gc.fillRect(x - WIDTH / 2, y - HEIGHT / 2, WIDTH, HEIGHT);
67 | }
68 | }
69 |
70 | /**
71 | * Returns the width of the power-up
72 | *
73 | * @return The width of the power-up
74 | */
75 | @Override
76 | public double getWidth() {
77 | return WIDTH;
78 | }
79 |
80 | /**
81 | * Returns the height of the power-up
82 | *
83 | * @return The height of the power-up
84 | */
85 | @Override
86 | public double getHeight() {
87 | return HEIGHT;
88 | }
89 |
90 | /**
91 | * Returns whether the power-up is dead
92 | *
93 | * @return Whether the power-up is dead
94 | */
95 | @Override
96 | public boolean isDead() {
97 | return this.isDead;
98 | }
99 |
100 | /**
101 | * Sets the dead flag for the power-up
102 | *
103 | * @param isDead The dead flag to set
104 | */
105 | public void setDead(boolean isDead) {
106 | this.isDead = isDead;
107 | }
108 | }
109 |
--------------------------------------------------------------------------------
/src/main/java/com/example/spaceshootergamejavafx/SpaceShooter.java:
--------------------------------------------------------------------------------
1 | package com.example.spaceshootergamejavafx;
2 |
3 | import javafx.animation.AnimationTimer;
4 | import javafx.animation.PauseTransition;
5 | import javafx.application.Application;
6 | import javafx.scene.Scene;
7 | import javafx.scene.canvas.Canvas;
8 | import javafx.scene.canvas.GraphicsContext;
9 | import javafx.scene.control.Button;
10 | import javafx.scene.control.Label;
11 | import javafx.scene.input.KeyCode;
12 | import javafx.scene.layout.Pane;
13 | import javafx.scene.layout.VBox;
14 | import javafx.scene.paint.Color;
15 | import javafx.scene.text.Font;
16 | import javafx.scene.text.FontWeight;
17 | import javafx.scene.text.Text;
18 | import javafx.stage.Stage;
19 | import javafx.util.Duration;
20 | import javafx.scene.control.Alert;
21 | import javafx.scene.control.Alert.AlertType;
22 | import javafx.scene.effect.DropShadow;
23 | import javafx.scene.effect.Glow;
24 | import javafx.scene.text.TextAlignment;
25 | import javafx.scene.image.Image;
26 |
27 | import java.util.ArrayList;
28 | import java.util.Iterator;
29 | import java.util.List;
30 | import java.util.Random;
31 | import java.util.Objects;
32 |
33 | /** Main game class for the Space Shooter game. */
34 | public class SpaceShooter extends Application {
35 |
36 | /** Width of the game window. */
37 | public static final int WIDTH = 350;
38 |
39 | /** Height of the game window. */
40 | public static final int HEIGHT = 800;
41 |
42 | /** Number of lives the player starts with. */
43 | public static int numLives = 3;
44 |
45 | /** Current score of the player. */
46 | private int score = 0;
47 |
48 | /** Flag to indicate if a boss enemy exists. */
49 | private boolean bossExists = false;
50 |
51 | /** Flag to indicate if the game should be reset. */
52 | private boolean reset = false;
53 |
54 | /** Label to display the player's score. */
55 | private final Label scoreLabel = new Label("Score: " + score);
56 |
57 | /** Label to display the player's remaining lives. */
58 | private final Label lifeLabel = new Label("Lives: " + numLives);
59 |
60 | /** List of game objects in the game. */
61 | private final List gameObjects = new ArrayList<>();
62 |
63 | /** List of new game objects to add to the game. */
64 | private final List newObjects = new ArrayList<>();
65 |
66 | /** Player object for the game. */
67 | private Player player = new Player(WIDTH / 2, HEIGHT - 40);
68 |
69 | /** Root pane for the game scene. */
70 | private Pane root = new Pane();
71 |
72 | /** Game scene for the game. */
73 | private Scene scene = new Scene(root, WIDTH, HEIGHT, Color.BLACK);
74 |
75 | /** Flag to indicate if the level up message has been displayed. */
76 | private boolean levelUpMessageDisplayed = false;
77 |
78 | /** Flag to indicate if the level up message has been shown. */
79 | private boolean levelUpShown = false;
80 |
81 | /** Primary stage for the game. */
82 | private Stage primaryStage;
83 |
84 | /** Flag to indicate if the game is running. */
85 | private boolean gameRunning = false;
86 |
87 | /** Main method to launch the game. */
88 | public static void main(String[] args) {
89 | launch(args);
90 | }
91 |
92 | /**
93 | * Starts the game and initializes the game window.
94 | *
95 | * @param primaryStage The primary stage for the game
96 | */
97 | @Override
98 | public void start(Stage primaryStage) {
99 | this.primaryStage = primaryStage;
100 | primaryStage.setScene(scene);
101 | primaryStage.setTitle("Space Shooter");
102 | primaryStage.setResizable(false);
103 |
104 | primaryStage
105 | .getIcons()
106 | .add(new Image(Objects.requireNonNull(getClass().getResourceAsStream("/player.png"))));
107 |
108 | Canvas canvas = new Canvas(WIDTH, HEIGHT);
109 | scoreLabel.setTranslateX(10);
110 | scoreLabel.setTranslateY(10);
111 | scoreLabel.setTextFill(Color.WHITE);
112 | scoreLabel.setFont(Font.font("Verdana", FontWeight.BOLD, 18));
113 |
114 | root.setStyle("-fx-background-color: black;");
115 | root.getChildren().addAll(canvas, scoreLabel, lifeLabel);
116 |
117 | lifeLabel.setTranslateX(10);
118 | lifeLabel.setTranslateY(40);
119 | lifeLabel.setTextFill(Color.WHITE);
120 | lifeLabel.setFont(Font.font("Verdana", FontWeight.BOLD, 18));
121 |
122 | GraphicsContext gc = canvas.getGraphicsContext2D();
123 | gameObjects.add(player);
124 |
125 | Pane menuPane = createMenu();
126 | Scene menuScene = new Scene(menuPane, WIDTH, HEIGHT);
127 |
128 | primaryStage.setScene(menuScene);
129 | primaryStage.setTitle("Space Shooter");
130 | primaryStage.setResizable(false);
131 | initEventHandlers(scene);
132 |
133 | AnimationTimer gameLoop =
134 | new AnimationTimer() {
135 | private long lastEnemySpawned = 0;
136 |
137 | private long lastPowerUpSpawned = 0;
138 |
139 | @Override
140 | public void handle(long now) {
141 | if (!gameRunning) return;
142 |
143 | if (reset) {
144 | this.start();
145 | reset = false;
146 | }
147 |
148 | gc.setFill(Color.BLACK);
149 | gc.clearRect(0, 0, WIDTH, HEIGHT);
150 |
151 | if (now - lastEnemySpawned > 1_000_000_000) {
152 | spawnEnemy();
153 | lastEnemySpawned = now;
154 | }
155 |
156 | if (now - lastPowerUpSpawned > 10_000_000_000L) {
157 | spawnPowerUp();
158 | lastPowerUpSpawned = now;
159 | }
160 |
161 | if (score >= 200 && score % 200 == 0) {
162 | boolean bossExists = false;
163 | for (GameObject obj : gameObjects) {
164 | if (obj instanceof BossEnemy) {
165 | bossExists = true;
166 | break;
167 | }
168 | }
169 | if (!bossExists) {
170 | spawnBossEnemy();
171 | }
172 | }
173 |
174 | checkCollisions();
175 | checkEnemiesReachingBottom();
176 |
177 | gameObjects.addAll(newObjects);
178 | newObjects.clear();
179 |
180 | for (GameObject obj : gameObjects) {
181 | obj.update();
182 | obj.render(gc);
183 | }
184 |
185 | Iterator iterator = gameObjects.iterator();
186 | while (iterator.hasNext()) {
187 | GameObject obj = iterator.next();
188 | if (obj.isDead()) {
189 | iterator.remove();
190 | }
191 | }
192 | }
193 | };
194 |
195 | gameLoop.start();
196 | primaryStage.show();
197 | }
198 |
199 | /** Spawns an enemy at a random x-coordinate at the top of the screen. */
200 | private void spawnEnemy() {
201 | Random random = new Random();
202 | int x = random.nextInt(WIDTH - 50) + 25;
203 |
204 | if (score % 200 == 0 && score > 0 && !bossExists) {
205 | BossEnemy boss = new BossEnemy(x, -50);
206 | gameObjects.add(boss);
207 | showTempMessage("A boss is ahead, watch out!", 75, HEIGHT / 2 - 100, 5);
208 | bossExists = true; // Ensure we don't spawn multiple bosses
209 | } else {
210 | Enemy enemy = new Enemy(x, -40);
211 | gameObjects.add(enemy);
212 | }
213 | }
214 |
215 | /**
216 | * Checks for collisions between game objects and updates the score and game state accordingly.
217 | */
218 | private void checkCollisions() {
219 | List bullets = new ArrayList<>();
220 | List enemies = new ArrayList<>();
221 | List powerUps = new ArrayList<>();
222 |
223 | for (GameObject obj : gameObjects) {
224 | if (obj instanceof Bullet) {
225 | bullets.add((Bullet) obj);
226 | } else if (obj instanceof Enemy) {
227 | enemies.add((Enemy) obj);
228 | } else if (obj instanceof PowerUp) {
229 | powerUps.add((PowerUp) obj);
230 | }
231 | }
232 |
233 | for (Bullet bullet : bullets) {
234 | for (Enemy enemy : enemies) {
235 | if (bullet.getBounds().intersects(enemy.getBounds())) {
236 | bullet.setDead(true);
237 | if (enemy instanceof BossEnemy) {
238 | ((BossEnemy) enemy).takeDamage();
239 | score += 20;
240 | } else {
241 | enemy.setDead(true);
242 | score += 10;
243 | }
244 | scoreLabel.setText("Score: " + score);
245 |
246 | if (score % 100 == 0) {
247 | Enemy.SPEED += 0.4;
248 | }
249 | }
250 | }
251 |
252 | // Check collisions between bullets and power-ups
253 | for (PowerUp powerUp : powerUps) {
254 | if (bullet.getBounds().intersects(powerUp.getBounds())) {
255 | bullet.setDead(true);
256 | powerUp.setDead(true);
257 | score += 50;
258 | scoreLabel.setText("Score: " + score);
259 | }
260 | }
261 | }
262 |
263 | if (score % 100 == 0 && score > 0 && !levelUpShown) {
264 | showTempMessage("Level Up!", 135, HEIGHT / 2, 2);
265 | levelUpShown = true;
266 | } else if (score % 100 != 0) {
267 | levelUpShown = false;
268 | }
269 | }
270 |
271 | /**
272 | * Checks if any enemies have reached the bottom of the screen and updates the game state
273 | * accordingly.
274 | */
275 | private void checkEnemiesReachingBottom() {
276 | List enemies = new ArrayList<>();
277 |
278 | for (GameObject obj : gameObjects) {
279 | if (obj instanceof Enemy) {
280 | enemies.add((Enemy) obj);
281 | }
282 | }
283 |
284 | for (Enemy enemy : enemies) {
285 | if (enemy.getY() + enemy.getHeight() / 2 >= HEIGHT) {
286 | enemy.setDead(true);
287 | enemy.SPEED = enemy.SPEED + 0.4;
288 | numLives--;
289 | score -= 10;
290 | lifeLabel.setText("Lives: " + numLives);
291 | if (numLives < 0) {
292 | resetGame();
293 | }
294 | }
295 | }
296 | }
297 |
298 | /** Shows the losing screen when the player loses all lives. */
299 | private void showLosingScreen() {
300 | Pane losingPane = new Pane();
301 | losingPane.setStyle("-fx-background-color: black;");
302 |
303 | // Game Over Text
304 | Text gameOverText = new Text("GAME OVER");
305 | gameOverText.setFont(Font.font("Verdana", FontWeight.BOLD, 40));
306 | gameOverText.setFill(Color.RED);
307 | gameOverText.setX((WIDTH - gameOverText.getLayoutBounds().getWidth()) / 2);
308 | gameOverText.setY(150);
309 |
310 | // Score Display
311 | if (score < 0) {
312 | score = 0;
313 | }
314 |
315 | Text scoreText = new Text("Your Score: " + score);
316 | scoreText.setFont(Font.font("Verdana", FontWeight.BOLD, 24));
317 | scoreText.setFill(Color.WHITE);
318 | scoreText.setX((WIDTH - scoreText.getLayoutBounds().getWidth()) / 2);
319 | scoreText.setY(250);
320 |
321 | // Try Again Button
322 | Button tryAgainButton = new Button("Try Again");
323 | tryAgainButton.setStyle(
324 | "-fx-background-color: #444; -fx-text-fill: white; -fx-font-size: 18; "
325 | + "-fx-font-weight: bold; -fx-padding: 10 20; -fx-font-family: 'Verdana';");
326 | tryAgainButton.setOnMouseEntered(
327 | event -> {
328 | tryAgainButton.setStyle(
329 | "-fx-background-color: white; -fx-text-fill: black; -fx-font-size: 18; "
330 | + "-fx-font-weight: bold; -fx-padding: 10 20; -fx-font-family: 'Verdana';");
331 | tryAgainButton.setEffect(new Glow(0.5));
332 | });
333 | tryAgainButton.setOnMouseExited(
334 | event -> {
335 | tryAgainButton.setStyle(
336 | "-fx-background-color: #444; -fx-text-fill: white; -fx-font-size: 18; "
337 | + "-fx-font-weight: bold; -fx-padding: 10 20; -fx-font-family: 'Verdana';");
338 | tryAgainButton.setEffect(null);
339 | });
340 | tryAgainButton.setLayoutX(115);
341 | tryAgainButton.setLayoutY(350);
342 | tryAgainButton.setOnAction(event -> restartGame());
343 |
344 | // Exit Button
345 | Button exitButton = new Button("Exit Game");
346 | exitButton.setStyle(
347 | "-fx-background-color: #d9534f; -fx-text-fill: white; -fx-font-size: 18; "
348 | + "-fx-font-weight: bold; -fx-padding: 10 20; -fx-font-family: 'Verdana';");
349 | exitButton.setOnMouseEntered(
350 | event -> {
351 | exitButton.setStyle(
352 | "-fx-background-color: white; -fx-text-fill: red; -fx-font-size: 18; "
353 | + "-fx-font-weight: bold; -fx-padding: 10 20; -fx-font-family: 'Verdana';");
354 | exitButton.setEffect(new Glow(0.5));
355 | });
356 | exitButton.setOnMouseExited(
357 | event -> {
358 | exitButton.setStyle(
359 | "-fx-background-color: #d9534f; -fx-text-fill: white; -fx-font-size: 18; "
360 | + "-fx-font-weight: bold; -fx-padding: 10 20; -fx-font-family: 'Verdana';");
361 | exitButton.setEffect(null);
362 | });
363 | exitButton.setLayoutX(115);
364 | exitButton.setLayoutY(450);
365 | exitButton.setOnAction(event -> System.exit(0));
366 |
367 | losingPane.getChildren().addAll(gameOverText, scoreText, tryAgainButton, exitButton);
368 |
369 | // Create and set the losing screen scene
370 | Scene losingScene = new Scene(losingPane, WIDTH, HEIGHT);
371 | primaryStage.setScene(losingScene);
372 | }
373 |
374 | /** Restarts the game when the player chooses to try again. */
375 | private void restartGame() {
376 | gameObjects.clear();
377 | numLives = 3;
378 | score = 0;
379 | lifeLabel.setText("Lives: " + numLives);
380 | scoreLabel.setText("Score: " + score);
381 | gameObjects.add(player);
382 | reset = true;
383 | gameRunning = true;
384 | primaryStage.setScene(scene);
385 | }
386 |
387 | /** Resets the game when the player loses all lives. */
388 | private void resetGame() {
389 | gameRunning = false;
390 | showLosingScreen();
391 | }
392 |
393 | /**
394 | * Initializes the event handlers for the game scene.
395 | *
396 | * @param scene The game scene to add the event handlers to
397 | */
398 | private void initEventHandlers(Scene scene) {
399 | scene.setOnKeyPressed(
400 | event -> {
401 | switch (event.getCode()) {
402 | case A:
403 | case LEFT:
404 | player.setMoveLeft(true);
405 | break;
406 | case D:
407 | case RIGHT:
408 | player.setMoveRight(true);
409 | break;
410 | case S:
411 | case DOWN:
412 | player.setMoveBackward(true);
413 | break;
414 | case W:
415 | case UP:
416 | player.setMoveForward(true);
417 | break;
418 | case SPACE:
419 | player.shoot(newObjects);
420 | break;
421 | }
422 | });
423 |
424 | scene.setOnKeyReleased(
425 | event -> {
426 | switch (event.getCode()) {
427 | case A:
428 | case LEFT:
429 | player.setMoveLeft(false);
430 | break;
431 | case D:
432 | case RIGHT:
433 | player.setMoveRight(false);
434 | break;
435 | case S:
436 | case DOWN:
437 | player.setMoveBackward(false);
438 | break;
439 | case W:
440 | case UP:
441 | player.setMoveForward(false);
442 | break;
443 | }
444 | });
445 | }
446 |
447 | /** Spawns a power-up at a random x-coordinate at the top of the screen. */
448 | private void spawnPowerUp() {
449 | Random random = new Random();
450 | int x = random.nextInt(WIDTH - PowerUp.WIDTH) + PowerUp.WIDTH / 2;
451 | PowerUp powerUp = new PowerUp(x, -PowerUp.HEIGHT / 2);
452 | gameObjects.add(powerUp);
453 | }
454 |
455 | /** Spawns a boss enemy at the top of the screen. */
456 | private void spawnBossEnemy() {
457 | if (gameObjects.stream().noneMatch(obj -> obj instanceof BossEnemy)) {
458 | BossEnemy bossEnemy = new BossEnemy(WIDTH / 2, -40);
459 | gameObjects.add(bossEnemy);
460 | }
461 | }
462 |
463 | /**
464 | * Creates the main menu for the game.
465 | *
466 | * @return The main menu pane
467 | */
468 | private Pane createMenu() {
469 | Pane menuPane = new Pane();
470 | menuPane.setStyle(
471 | "-fx-background-color: linear-gradient(to bottom, #1e3c72, #2a5298);"); // Gradient
472 | // background
473 |
474 | // Styled title
475 | Text welcomeText = new Text("Welcome to\nSpace Shooter!");
476 | welcomeText.setFont(Font.font("Verdana", FontWeight.EXTRA_BOLD, 36)); // Bold and larger font
477 | welcomeText.setFill(Color.LIGHTCYAN); // Softer text color
478 | welcomeText.setEffect(new DropShadow(10, Color.CYAN)); // Add a shadow effect
479 | welcomeText.setTextAlignment(TextAlignment.CENTER);
480 | welcomeText.setX(WIDTH / 2 - 150);
481 | welcomeText.setY(100);
482 |
483 | // Styled buttons
484 | Button startButton = createStyledButton("START", 200);
485 | startButton.setOnAction(event -> startGame());
486 |
487 | Button instructionsButton = createStyledButton("INSTRUCTIONS", 300);
488 | instructionsButton.setOnAction(event -> showInstructions());
489 |
490 | Button quitButton = createStyledButton("QUIT", 400);
491 | quitButton.setOnAction(event -> System.exit(0));
492 |
493 | // Button layout container
494 | VBox buttonsContainer = new VBox(20);
495 | buttonsContainer.setLayoutX(WIDTH / 2 - 75); // Center the buttons
496 | buttonsContainer.setLayoutY(200);
497 | buttonsContainer.getChildren().addAll(startButton, instructionsButton, quitButton);
498 |
499 | menuPane.getChildren().addAll(welcomeText, buttonsContainer);
500 |
501 | return menuPane;
502 | }
503 |
504 | /**
505 | * Creates a styled button with a gradient background and hover effects.
506 | *
507 | * @param text The text to display on the button
508 | * @param y The y-coordinate of the button
509 | * @return The styled button
510 | */
511 | private Button createStyledButton(String text, double y) {
512 | Button button = new Button(text);
513 | button.setStyle(
514 | "-fx-background-color: linear-gradient(to right, #6a11cb, #2575fc);"
515 | + "-fx-text-fill: white;"
516 | + "-fx-font-size: 18;"
517 | + "-fx-font-weight: bold;"
518 | + "-fx-padding: 10 20;"
519 | + "-fx-border-radius: 20;"
520 | + "-fx-background-radius: 20;"
521 | + "-fx-border-color: #ffffff;"
522 | + "-fx-border-width: 2;"
523 | + "-fx-font-family: 'Verdana';");
524 | button.setOnMouseEntered(
525 | event -> {
526 | button.setStyle(
527 | "-fx-background-color: linear-gradient(to right, #2575fc, #6a11cb);"
528 | + "-fx-text-fill: yellow;"
529 | + "-fx-font-size: 18;"
530 | + "-fx-font-weight: bold;"
531 | + "-fx-padding: 10 20;"
532 | + "-fx-border-radius: 20;"
533 | + "-fx-background-radius: 20;"
534 | + "-fx-border-color: yellow;"
535 | + "-fx-border-width: 2;"
536 | + "-fx-font-family: 'Verdana';");
537 | button.setEffect(new Glow(0.5));
538 | });
539 | button.setOnMouseExited(
540 | event -> {
541 | button.setStyle(
542 | "-fx-background-color: linear-gradient(to right, #6a11cb, #2575fc);"
543 | + "-fx-text-fill: white;"
544 | + "-fx-font-size: 18;"
545 | + "-fx-font-weight: bold;"
546 | + "-fx-padding: 10 20;"
547 | + "-fx-border-radius: 20;"
548 | + "-fx-background-radius: 20;"
549 | + "-fx-border-color: #ffffff;"
550 | + "-fx-border-width: 2;"
551 | + "-fx-font-family: 'Verdana';");
552 | button.setEffect(null);
553 | });
554 | return button;
555 | }
556 |
557 | /** Shows the instructions for the game. */
558 | private void showInstructions() {
559 | Alert instructionsAlert = new Alert(AlertType.INFORMATION);
560 | instructionsAlert.setTitle("Instructions");
561 | instructionsAlert.setHeaderText("Space Shooter Instructions");
562 | instructionsAlert.setContentText(
563 | "Use the A, W, S, and D keys or the arrow keys to move your spaceship.\n"
564 | + "Press SPACE to shoot bullets and destroy the enemies.\n"
565 | + "If an enemy reaches the bottom of the screen, you lose a life.\n"
566 | + "The game resets if you lose all lives.\n"
567 | + "Collect power-ups to increase your score.\n"
568 | + "Defeat the boss enemy to level up and increase the difficulty.\n"
569 | + "Good luck and have fun!");
570 | instructionsAlert.showAndWait();
571 | }
572 |
573 | /**
574 | * Shows a temporary message on the screen for a specified duration.
575 | *
576 | * @param message The message to display
577 | * @param x The x-coordinate of the message
578 | * @param y The y-coordinate of the message
579 | * @param duration The duration to display the message
580 | */
581 | private void showTempMessage(String message, double x, double y, double duration) {
582 | Text tempMessage = new Text(message);
583 | tempMessage.setFont(Font.font("Verdana", FontWeight.BOLD, 18));
584 | tempMessage.setFill(Color.RED);
585 | tempMessage.setX(x);
586 | tempMessage.setY(y);
587 | root.getChildren().add(tempMessage);
588 |
589 | PauseTransition pause = new PauseTransition(Duration.seconds(duration));
590 | pause.setOnFinished(event -> root.getChildren().remove(tempMessage));
591 | pause.play();
592 | }
593 |
594 | /** Starts the game when the player clicks the start button. */
595 | private void startGame() {
596 | gameRunning = true;
597 | primaryStage.setScene(scene);
598 | }
599 | }
600 |
--------------------------------------------------------------------------------
/src/main/java/module-info.java:
--------------------------------------------------------------------------------
1 | module com.example.spaceshootergamejavafx {
2 | requires javafx.controls;
3 | requires javafx.fxml;
4 |
5 |
6 | opens com.example.spaceshootergamejavafx to javafx.fxml;
7 | exports com.example.spaceshootergamejavafx;
8 | }
--------------------------------------------------------------------------------
/src/main/resources/boss.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hoangsonww/Space-Invader-Game-JavaFX/d7e2ac3b28ca7aeb1de02e7a77005fcdf10a68a9/src/main/resources/boss.png
--------------------------------------------------------------------------------
/src/main/resources/com/example/spaceshootergamejavafx/hello-view.fxml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
--------------------------------------------------------------------------------
/src/main/resources/enemy.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hoangsonww/Space-Invader-Game-JavaFX/d7e2ac3b28ca7aeb1de02e7a77005fcdf10a68a9/src/main/resources/enemy.png
--------------------------------------------------------------------------------
/src/main/resources/player.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hoangsonww/Space-Invader-Game-JavaFX/d7e2ac3b28ca7aeb1de02e7a77005fcdf10a68a9/src/main/resources/player.jpg
--------------------------------------------------------------------------------
/src/main/resources/player.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hoangsonww/Space-Invader-Game-JavaFX/d7e2ac3b28ca7aeb1de02e7a77005fcdf10a68a9/src/main/resources/player.png
--------------------------------------------------------------------------------
/src/main/resources/powerup.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hoangsonww/Space-Invader-Game-JavaFX/d7e2ac3b28ca7aeb1de02e7a77005fcdf10a68a9/src/main/resources/powerup.png
--------------------------------------------------------------------------------