feat: init again with phaser vite webbundler

This commit is contained in:
tiennm99 committed 2025-04-27 11:03:20 +07:00
1 parent 21fc37bc51
commit 1731863ec0
28 files changed
+1701 -248270

No files matched your search

+23
View File
@@ -1 +1,24 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
.
node_modules
dist
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
+17 -197
View File
@@ -1,201 +1,21 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
MIT License
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
Copyright (c) 2025 Phaser Studio Inc
1. Definitions.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+153 -1
View File
@@ -1 +1,153 @@
# Night Ninja: Twilight Voyage
# Phaser Vite Template
This is a Phaser 3 project template that uses Vite for bundling. It supports hot-reloading for quick development workflow and includes scripts to generate production-ready builds.
**[This Template is also available as a TypeScript version.](https://github.com/phaserjs/template-vite-ts)**
### Versions
This template has been updated for:
- [Phaser 3.88.2](https://github.com/phaserjs/phaser)
- [Vite 5.3.1](https://github.com/vitejs/vite)
![screenshot](screenshot.png)
## Requirements
[Node.js](https://nodejs.org) is required to install dependencies and run scripts via `npm`.
## Available Commands
| Command | Description |
|---------|-------------|
| `npm install` | Install project dependencies |
| `npm run dev` | Launch a development web server |
| `npm run build` | Create a production build in the `dist` folder |
| `npm run dev-nolog` | Launch a development web server without sending anonymous data (see "About log.js" below) |
| `npm run build-nolog` | Create a production build in the `dist` folder without sending anonymous data (see "About log.js" below) |
## Writing Code
After cloning the repo, run `npm install` from your project directory. Then, you can start the local development server by running `npm run dev`.
The local development server runs on `http://localhost:8080` by default. Please see the Vite documentation if you wish to change this, or add SSL support.
Once the server is running you can edit any of the files in the `src` folder. Vite will automatically recompile your code and then reload the browser.
## Template Project Structure
We have provided a default project structure to get you started. This is as follows:
| Path | Description |
|------------------------------|------------------------------------------------------------|
| `index.html` | A basic HTML page to contain the game. |
| `public/assets` | Game sprites, audio, etc. Served directly at runtime. |
| `public/style.css` | Global layout styles. |
| `src/main.js` | Application bootstrap. |
| `src/game` | Folder containing the game code. |
| `src/game/main.js` | Game entry point: configures and starts the game. |
| `src/game/scenes` | Folder with all Phaser game scenes. |
## Handling Assets
Vite supports loading assets via JavaScript module `import` statements.
This template provides support for both embedding assets and also loading them from a static folder. To embed an asset, you can import it at the top of the JavaScript file you are using it in:
```js
import logoImg from './assets/logo.png'
```
To load static files such as audio files, videos, etc place them into the `public/assets` folder. Then you can use this path in the Loader calls within Phaser:
```js
preload ()
{
// This is an example of an imported bundled image.
// Remember to import it at the top of this file
this.load.image('logo', logoImg);
// This is an example of loading a static image
// from the public/assets folder:
this.load.image('background', 'assets/bg.png');
}
```
When you issue the `npm run build` command, all static assets are automatically copied to the `dist/assets` folder.
## Deploying to Production
After you run the `npm run build` command, your code will be built into a single bundle and saved to the `dist` folder, along with any other assets your project imported, or stored in the public assets folder.
In order to deploy your game, you will need to upload *all* of the contents of the `dist` folder to a public facing web server.
## Customizing the Template
### Vite
If you want to customize your build, such as adding plugin (i.e. for loading CSS or fonts), you can modify the `vite/config.*.mjs` file for cross-project changes, or you can modify and/or create new configuration files and target them in specific npm tasks inside of `package.json`. Please see the [Vite documentation](https://vitejs.dev/) for more information.
## About log.js
If you inspect our node scripts you will see there is a file called `log.js`. This file makes a single silent API call to a domain called `gryzor.co`. This domain is owned by Phaser Studio Inc. The domain name is a homage to one of our favorite retro games.
We send the following 3 pieces of data to this API: The name of the template being used (vue, react, etc). If the build was 'dev' or 'prod' and finally the version of Phaser being used.
At no point is any personal data collected or sent. We don't know about your project files, device, browser or anything else. Feel free to inspect the `log.js` file to confirm this.
Why do we do this? Because being open source means we have no visible metrics about which of our templates are being used. We work hard to maintain a large and diverse set of templates for Phaser developers and this is our small anonymous way to determine if that work is actually paying off, or not. In short, it helps us ensure we're building the tools for you.
However, if you don't want to send any data, you can use these commands instead:
Dev:
```bash
npm run dev-nolog
```
Build:
```bash
npm run build-nolog
```
Or, to disable the log entirely, simply delete the file `log.js` and remove the call to it in the `scripts` section of `package.json`:
Before:
```json
"scripts": {
"dev": "node log.js dev & dev-template-script",
"build": "node log.js build & build-template-script"
},
```
After:
```json
"scripts": {
"dev": "dev-template-script",
"build": "build-template-script"
},
```
Either of these will stop `log.js` from running. If you do decide to do this, please could you at least join our Discord and tell us which template you're using! Or send us a quick email. Either will be super-helpful, thank you.
## Join the Phaser Community!
We love to see what developers like you create with Phaser! It really motivates us to keep improving. So please join our community and show-off your work 😄
**Visit:** The [Phaser website](https://phaser.io) and follow on [Phaser Twitter](https://twitter.com/phaser_)<br />
**Play:** Some of the amazing games [#madewithphaser](https://twitter.com/search?q=%23madewithphaser&src=typed_query&f=live)<br />
**Learn:** [API Docs](https://newdocs.phaser.io), [Support Forum](https://phaser.discourse.group/) and [StackOverflow](https://stackoverflow.com/questions/tagged/phaser-framework)<br />
**Discord:** Join us on [Discord](https://discord.gg/phaser)<br />
**Code:** 2000+ [Examples](https://labs.phaser.io)<br />
**Read:** The [Phaser World](https://phaser.io/community/newsletter) Newsletter<br />
Created by [Phaser Studio](mailto:support@phaser.io). Powered by coffee, anime, pixels and love.
The Phaser logo and characters are &copy; 2011 - 2025 Phaser Studio Inc.
All rights reserved.
BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.6 KiB

BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 8.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.5 KiB

+11 -45
View File
@@ -1,51 +1,17 @@
<!DOCTYPE html>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>nntv</title>
<style>
/* Reset CSS: Please avoid making changes here unless you know what you're doing :) */
*,
*::before,
*::after {
margin: 0;
padding: 0;
box-sizing: border-box;
}
html, body {
width: 100%;
height: 100%;
}
body {
line-height: 1;
font-family: Arial, sans-serif;
background-color: #040218;
}
ol, ul {
list-style: none;
}
img, video {
max-width: 100%;
height: auto;
display: block;
}
a {
text-decoration: none;
color: inherit;
}
</style>
<meta charset="UTF-8" />
<link rel="icon" type="image/png" href="/favicon.png" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="/style.css">
<title>Phaser - Template</title>
</head>
<body>
<div id="game-container"></div>
<script src="./phaser.js"></script>
<script type="module" src="./src/main.js"></script>
<div id="app">
<div id="game-container"></div>
</div>
<script type="module" src="src/main.js"></script>
</body>
</html>
+36
View File
@@ -0,0 +1,36 @@
import * as fs from 'fs';
import * as https from 'https';
const main = async () => {
const args = process.argv.slice(2);
const packageData = JSON.parse(fs.readFileSync('./package.json', 'utf8'));
const event = args[0] || 'unknown';
const phaserVersion = packageData.dependencies.phaser;
const options = {
hostname: 'gryzor.co',
port: 443,
path: `/v/${event}/${phaserVersion}/${packageData.name}`,
method: 'GET'
};
try {
const req = https.request(options, (res) => {
res.on('data', () => {});
res.on('end', () => {
process.exit(0);
});
});
req.on('error', (error) => {
process.exit(1);
});
req.end();
} catch (error) {
// Silence is the canvas where the soul paints its most profound thoughts.
process.exit(1);
}
}
main();
+1159
View File
File diff suppressed because it is too large. Load diff
+30
View File
@@ -0,0 +1,30 @@
{
"name": "template-vite",
"description": "A Phaser 3 template using Vite.",
"version": "1.4.0",
"type": "module",
"repository": {
"type": "git",
"url": "git+https://github.com/phaserjs/template-vite.git"
},
"author": "Phaser Studio <support@phaser.io> (https://phaser.io/)",
"license": "MIT",
"licenseUrl": "http://www.opensource.org/licenses/mit-license.php",
"bugs": {
"url": "https://github.com/phaserjs/template-vite/issues"
},
"homepage": "https://github.com/phaserjs/template-vite#readme",
"scripts": {
"dev": "node log.js dev & vite --config vite/config.dev.mjs",
"build": "node log.js build & vite build --config vite/config.prod.mjs",
"dev-nolog": "vite --config vite/config.dev.mjs",
"build-nolog": "vite build --config vite/config.prod.mjs"
},
"devDependencies": {
"terser": "^5.39.0",
"vite": "^6.3.1"
},
"dependencies": {
"phaser": "^3.88.2"
}
}
-247825
View File
File diff suppressed because it is too large. Load diff
-13
View File
@@ -1,13 +0,0 @@
[game]
title = "nntv"
width = 800
height = 600
pixel_art = false
[user]
id = "d071bee3-5337-46ed-970a-9622a6fc0d72"
[editor]
editor_version = "1.0.0"
phaser_version = "3.88.0"
creation_at = 1739969384981
Binary file not shown.

After

Width:  |  Height:  |  Size: 295 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 354 B

+15
View File
@@ -0,0 +1,15 @@
body {
margin: 0;
padding: 0;
color: rgba(255, 255, 255, 0.87);
background-color: #000000;
}
#app {
width: 100%;
height: 100vh;
overflow: hidden;
display: flex;
justify-content: center;
align-items: center;
}
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 363 KiB

+35
View File
@@ -0,0 +1,35 @@
import { Boot } from './scenes/Boot';
import { Game as MainGame } from './scenes/Game';
import { GameOver } from './scenes/GameOver';
import { MainMenu } from './scenes/MainMenu';
import { Preloader } from './scenes/Preloader';
import { AUTO, Game } from 'phaser';
// Find out more information about the Game Config at:
// https://docs.phaser.io/api-documentation/typedef/types-core#gameconfig
const config = {
type: AUTO,
width: 1024,
height: 768,
parent: 'game-container',
backgroundColor: '#028af8',
scale: {
mode: Phaser.Scale.FIT,
autoCenter: Phaser.Scale.CENTER_BOTH
},
scene: [
Boot,
Preloader,
MainMenu,
MainGame,
GameOver
]
};
const StartGame = (parent) => {
return new Game({ ...config, parent });
}
export default StartGame;
+22
View File
@@ -0,0 +1,22 @@
import { Scene } from 'phaser';
export class Boot extends Scene
{
constructor ()
{
super('Boot');
}
preload ()
{
// The Boot Scene is typically used to load in any assets you require for your Preloader, such as a game logo or background.
// The smaller the file size of the assets, the better, as the Boot Scene itself has no preloader.
this.load.image('background', 'assets/bg.png');
}
create ()
{
this.scene.start('Preloader');
}
}
+28
View File
@@ -0,0 +1,28 @@
import { Scene } from 'phaser';
export class Game extends Scene
{
constructor ()
{
super('Game');
}
create ()
{
this.cameras.main.setBackgroundColor(0x00ff00);
this.add.image(512, 384, 'background').setAlpha(0.5);
this.add.text(512, 384, 'Make something fun!\nand share it with us:\nsupport@phaser.io', {
fontFamily: 'Arial Black', fontSize: 38, color: '#ffffff',
stroke: '#000000', strokeThickness: 8,
align: 'center'
}).setOrigin(0.5);
this.input.once('pointerdown', () => {
this.scene.start('GameOver');
});
}
}
+28
View File
@@ -0,0 +1,28 @@
import { Scene } from 'phaser';
export class GameOver extends Scene
{
constructor ()
{
super('GameOver');
}
create ()
{
this.cameras.main.setBackgroundColor(0xff0000);
this.add.image(512, 384, 'background').setAlpha(0.5);
this.add.text(512, 384, 'Game Over', {
fontFamily: 'Arial Black', fontSize: 64, color: '#ffffff',
stroke: '#000000', strokeThickness: 8,
align: 'center'
}).setOrigin(0.5);
this.input.once('pointerdown', () => {
this.scene.start('MainMenu');
});
}
}
+28
View File
@@ -0,0 +1,28 @@
import { Scene } from 'phaser';
export class MainMenu extends Scene
{
constructor ()
{
super('MainMenu');
}
create ()
{
this.add.image(512, 384, 'background');
this.add.image(512, 300, 'logo');
this.add.text(512, 460, 'Main Menu', {
fontFamily: 'Arial Black', fontSize: 38, color: '#ffffff',
stroke: '#000000', strokeThickness: 8,
align: 'center'
}).setOrigin(0.5);
this.input.once('pointerdown', () => {
this.scene.start('Game');
});
}
}
+46
View File
@@ -0,0 +1,46 @@
import { Scene } from 'phaser';
export class Preloader extends Scene
{
constructor ()
{
super('Preloader');
}
init ()
{
// We loaded this image in our Boot Scene, so we can display it here
this.add.image(512, 384, 'background');
// A simple progress bar. This is the outline of the bar.
this.add.rectangle(512, 384, 468, 32).setStrokeStyle(1, 0xffffff);
// This is the progress bar itself. It will increase in size from the left based on the % of progress.
const bar = this.add.rectangle(512-230, 384, 4, 28, 0xffffff);
// Use the 'progress' event emitted by the LoaderPlugin to update the loading bar
this.load.on('progress', (progress) => {
// Update the progress bar (our bar is 464px wide, so 100% = 464px)
bar.width = 4 + (460 * progress);
});
}
preload ()
{
// Load the assets for the game - Replace with your own assets
this.load.setPath('assets');
this.load.image('logo', 'logo.png');
}
create ()
{
// When all the assets have loaded, it's often worth creating global objects here that the rest of the game can use.
// For example, you can define global animations here, so we can use them in other scenes.
// Move to the MainMenu. You could also swap this for a Scene Transition, such as a camera fade.
this.scene.start('MainMenu');
}
}
+6 -23
View File
@@ -1,24 +1,7 @@
import { Menu } from './scenes/Menu.js';
import { Game } from './scenes/Game.js';
import StartGame from './game/main';
const config = {
type: Phaser.AUTO,
title: 'nntv',
description: 'Night Ninja: Twilight Voyage',
parent: 'game-container',
width: 800,
height: 600,
pixelArt: false,
scene: [Menu, Game],
scale: {
mode: Phaser.Scale.FIT,
autoCenter: Phaser.Scale.CENTER_BOTH
},
physics: {
default: 'arcade',
arcade: {
gravity: { y: 0 }
}
}
}
new Phaser.Game(config);
document.addEventListener('DOMContentLoaded', () => {
StartGame('game-container');
});
-115
View File
@@ -1,115 +0,0 @@
export class Game extends Phaser.Scene {
constructor() {
super('Game');
this.player = null;
this.cursors = null;
this.wasd = null;
this.buttons = {};
}
create() {
// Set white background
this.cameras.main.setBackgroundColor('#ffffff');
// Create player
this.player = this.add.circle(400, 300, 20, 0x000000);
// Enable physics on player
this.physics.add.existing(this.player);
// Set up keyboard controls
this.cursors = this.input.keyboard.createCursorKeys();
this.wasd = this.input.keyboard.addKeys({
up: Phaser.Input.Keyboard.KeyCodes.W,
down: Phaser.Input.Keyboard.KeyCodes.S,
left: Phaser.Input.Keyboard.KeyCodes.A,
right: Phaser.Input.Keyboard.KeyCodes.D
});
// Create on-screen buttons
this.createButtons();
}
createButtons() {
const buttonSize = 50;
const buttonColor = 0xaa00ff;
// Create up button (triangle pointing up)
this.buttons.up = this.add.triangle(
700, 425 - buttonSize / 2,
-buttonSize / 2, buttonSize / 2,
buttonSize / 2, buttonSize / 2,
0, -buttonSize / 2
).setInteractive().setFillStyle(buttonColor);
this.buttons.up.on('pointerdown', () => this.movePlayer('up'));
// Create down button (triangle pointing down)
this.buttons.down = this.add.triangle(
700, 575 - buttonSize / 2,
-buttonSize / 2, -buttonSize / 2,
buttonSize / 2, -buttonSize / 2,
0, buttonSize / 2
).setInteractive().setFillStyle(buttonColor);
this.buttons.down.on('pointerdown', () => this.movePlayer('down'));
// Create left button (triangle pointing left)
this.buttons.left = this.add.triangle(
650 - buttonSize / 2, 500,
buttonSize / 2, -buttonSize / 2,
buttonSize / 2, buttonSize / 2,
-buttonSize / 2, 0
).setInteractive().setFillStyle(buttonColor);
this.buttons.left.on('pointerdown', () => this.movePlayer('left'));
// Create right button (triangle pointing right)
this.buttons.right = this.add.triangle(
750 + buttonSize / 2, 500,
-buttonSize / 2, -buttonSize / 2,
-buttonSize / 2, buttonSize / 2,
buttonSize / 2, 0
).setInteractive().setFillStyle(buttonColor);
this.buttons.right.on('pointerdown', () => this.movePlayer('right'));
}
movePlayer(direction) {
const speed = 200;
const playerBody = this.player.body;
switch (direction) {
case 'up':
playerBody.setVelocityY(-speed);
break;
case 'down':
playerBody.setVelocityY(speed);
break;
case 'left':
playerBody.setVelocityX(-speed);
break;
case 'right':
playerBody.setVelocityX(speed);
break;
}
}
update() {
const speed = 200;
const playerBody = this.player.body;
// Reset velocity
playerBody.setVelocity(0);
// Handle horizontal movement
if (this.cursors.left.isDown || this.wasd.left.isDown) {
playerBody.setVelocityX(-speed);
} else if (this.cursors.right.isDown || this.wasd.right.isDown) {
playerBody.setVelocityX(speed);
}
// Handle vertical movement
if (this.cursors.up.isDown || this.wasd.up.isDown) {
playerBody.setVelocityY(-speed);
} else if (this.cursors.down.isDown || this.wasd.down.isDown) {
playerBody.setVelocityY(speed);
}
}
}
-51
View File
@@ -1,51 +0,0 @@
export class Menu extends Phaser.Scene {
constructor() {
super('Menu');
}
create() {
this.addButtons();
}
addButtons() {
const CONTINUE_BUTTON_X = 400; // Center horizontally
const CONTINUE_BUTTON_Y = 250;
const NEW_GAME_BUTTON_X = 400; // Center horizontally
const NEW_GAME_BUTTON_Y = CONTINUE_BUTTON_Y + 80;
const SETTINGS_BUTTON_X = 400; // Center horizontally
const SETTINGS_BUTTON_Y = NEW_GAME_BUTTON_Y + 80;
const HELP_BUTTON_X = 400; // Center horizontally
const HELP_BUTTON_Y = SETTINGS_BUTTON_Y + 80;
this.createButton('Tiếp tục', CONTINUE_BUTTON_X, CONTINUE_BUTTON_Y, () => this.startGame());
this.createButton('Chơi mới', NEW_GAME_BUTTON_X, NEW_GAME_BUTTON_Y, () => this.newGame());
this.createButton('Cài đặt', SETTINGS_BUTTON_X, SETTINGS_BUTTON_Y, () => this.openSettings());
this.createButton('Trợ giúp', HELP_BUTTON_X, HELP_BUTTON_Y, () => this.openHelp());
}
createButton(text, x, y, callback) {
const button = this.add.rectangle(x, y, 200, 50, 0xffffff).setInteractive()
.on('pointerdown', callback)
.on('pointerover', () => button.fillColor = 0xff3333)
.on('pointerout', () => button.fillColor = 0xffffff);
const textObject = this.add.text(x, y, text, { fontSize: '24px', fill: '#000' }).setOrigin(0.5);
return button;
}
startGame() {
console.log('Tiếp tục trò chơi');
}
newGame() {
this.scene.start('Game');
}
openSettings() {
console.log('Mở cài đặt');
}
openHelp() {
console.log('Mở trợ giúp');
}
}
+17
View File
@@ -0,0 +1,17 @@
import { defineConfig } from 'vite';
export default defineConfig({
base: './',
build: {
rollupOptions: {
output: {
manualChunks: {
phaser: ['phaser']
}
}
},
},
server: {
port: 8080
}
});
+47
View File
@@ -0,0 +1,47 @@
import { defineConfig } from 'vite';
const phasermsg = () => {
return {
name: 'phasermsg',
buildStart() {
process.stdout.write(`Building for production...\n`);
},
buildEnd() {
const line = "---------------------------------------------------------";
const msg = `❤️❤️❤️ Tell us about your game! - games@phaser.io ❤️❤️❤️`;
process.stdout.write(`${line}\n${msg}\n${line}\n`);
process.stdout.write(`✨ Done ✨\n`);
}
}
}
export default defineConfig({
base: './',
logLevel: 'warn',
build: {
rollupOptions: {
output: {
manualChunks: {
phaser: ['phaser']
}
}
},
minify: 'terser',
terserOptions: {
compress: {
passes: 2
},
mangle: true,
format: {
comments: false
}
}
},
server: {
port: 8080
},
plugins: [
phasermsg()
]
});