init
This commit is contained in:
12
.editorconfig
Normal file
12
.editorconfig
Normal file
@@ -0,0 +1,12 @@
|
||||
# EditorConfig is awesome: https://EditorConfig.org
|
||||
|
||||
# top-most EditorConfig file
|
||||
root = true
|
||||
|
||||
[*]
|
||||
indent_style = space
|
||||
indent_size = 4
|
||||
end_of_line = crlf
|
||||
charset = utf-8
|
||||
trim_trailing_whitespace = false
|
||||
insert_final_newline = false
|
||||
18
.eslintrc.cjs
Normal file
18
.eslintrc.cjs
Normal file
@@ -0,0 +1,18 @@
|
||||
module.exports = {
|
||||
root: true,
|
||||
env: { browser: true, es2020: true },
|
||||
extends: [
|
||||
'eslint:recommended',
|
||||
'plugin:@typescript-eslint/recommended',
|
||||
'plugin:react-hooks/recommended',
|
||||
],
|
||||
ignorePatterns: ['dist', '.eslintrc.cjs'],
|
||||
parser: '@typescript-eslint/parser',
|
||||
plugins: ['react-refresh'],
|
||||
rules: {
|
||||
'react-refresh/only-export-components': [
|
||||
'warn',
|
||||
{ allowConstantExport: true },
|
||||
],
|
||||
},
|
||||
}
|
||||
24
.gitignore
vendored
Normal file
24
.gitignore
vendored
Normal file
@@ -0,0 +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?
|
||||
21
LICENSE
Normal file
21
LICENSE
Normal file
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2024 Phaser Studio Inc
|
||||
|
||||
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:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
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.
|
||||
244
README.md
Normal file
244
README.md
Normal file
@@ -0,0 +1,244 @@
|
||||
# Phaser React TypeScript Template
|
||||
|
||||
This is a Phaser 3 project template that uses the React framework and Vite for bundling. It includes a bridge for React to Phaser game communication, hot-reloading for quick development workflow and scripts to generate production-ready builds.
|
||||
|
||||
**[This Template is also available as a JavaScript version.](https://github.com/phaserjs/template-react)**
|
||||
|
||||
### Versions
|
||||
|
||||
This template has been updated for:
|
||||
|
||||
- [Phaser 3.88.2](https://github.com/phaserjs/phaser)
|
||||
- [React 18.2.0](https://github.com/facebook/react)
|
||||
- [Vite 5.3.1](https://github.com/vitejs/vite)
|
||||
- [TypeScript 5.2.2](https://github.com/microsoft/TypeScript)
|
||||
|
||||

|
||||
|
||||
## 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:
|
||||
|
||||
- `index.html` - A basic HTML page to contain the game.
|
||||
- `src` - Contains the React client source code.
|
||||
- `src/main.tsx` - The main **React** entry point. This bootstraps the React application.
|
||||
- `src/vite-env.d.ts` - Global TypeScript declarations, provide types information.
|
||||
- `src/App.tsx` - The main React component.
|
||||
- `src/game/PhaserGame.tsx` - The React component that initializes the Phaser Game and serve like a bridge between React and Phaser.
|
||||
- `src/game/EventBus.ts` - A simple event bus to communicate between React and Phaser.
|
||||
- `src/game` - Contains the game source code.
|
||||
- `src/game/main.tsx` - The main **game** entry point. This contains the game configuration and start the game.
|
||||
- `src/game/scenes/` - The Phaser Scenes are in this folder.
|
||||
- `public/style.css` - Some simple CSS rules to help with page layout.
|
||||
- `public/assets` - Contains the static assets used by the game.
|
||||
|
||||
## React Bridge
|
||||
|
||||
The `PhaserGame.tsx` component is the bridge between React and Phaser. It initializes the Phaser game and passes events between the two.
|
||||
|
||||
To communicate between React and Phaser, you can use the **EventBus.js** file. This is a simple event bus that allows you to emit and listen for events from both React and Phaser.
|
||||
|
||||
```js
|
||||
// In React
|
||||
import { EventBus } from './EventBus';
|
||||
|
||||
// Emit an event
|
||||
EventBus.emit('event-name', data);
|
||||
|
||||
// In Phaser
|
||||
// Listen for an event
|
||||
EventBus.on('event-name', (data) => {
|
||||
// Do something with the data
|
||||
});
|
||||
```
|
||||
|
||||
In addition to this, the `PhaserGame` component exposes the Phaser game instance along with the most recently active Phaser Scene using React forwardRef.
|
||||
|
||||
Once exposed, you can access them like any regular react reference.
|
||||
|
||||
## Phaser Scene Handling
|
||||
|
||||
In Phaser, the Scene is the lifeblood of your game. It is where you sprites, game logic and all of the Phaser systems live. You can also have multiple scenes running at the same time. This template provides a way to obtain the current active scene from React.
|
||||
|
||||
You can get the current Phaser Scene from the component event `"current-active-scene"`. In order to do this, you need to emit the event `"current-scene-ready"` from the Phaser Scene class. This event should be emitted when the scene is ready to be used. You can see this done in all of the Scenes in our template.
|
||||
|
||||
**Important**: When you add a new Scene to your game, make sure you expose to React by emitting the `"current-scene-ready"` event via the `EventBus`, like this:
|
||||
|
||||
|
||||
```ts
|
||||
class MyScene extends Phaser.Scene
|
||||
{
|
||||
constructor ()
|
||||
{
|
||||
super('MyScene');
|
||||
}
|
||||
|
||||
create ()
|
||||
{
|
||||
// Your Game Objects and logic here
|
||||
|
||||
// At the end of create method:
|
||||
EventBus.emit('current-scene-ready', this);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
You don't have to emit this event if you don't need to access the specific scene from React. Also, you don't have to emit it at the end of `create`, you can emit it at any point. For example, should your Scene be waiting for a network request or API call to complete, it could emit the event once that data is ready.
|
||||
|
||||
### React Component Example
|
||||
|
||||
Here's an example of how to access Phaser data for use in a React Component:
|
||||
|
||||
```ts
|
||||
import { useRef } from 'react';
|
||||
import { IRefPhaserGame } from "./game/PhaserGame";
|
||||
|
||||
// In a parent component
|
||||
const ReactComponent = () => {
|
||||
|
||||
const phaserRef = useRef<IRefPhaserGame>(); // you can access to this ref from phaserRef.current
|
||||
|
||||
const onCurrentActiveScene = (scene: Phaser.Scene) => {
|
||||
|
||||
// This is invoked
|
||||
|
||||
}
|
||||
|
||||
return (
|
||||
...
|
||||
<PhaserGame ref={phaserRef} currentActiveScene={onCurrentActiveScene} />
|
||||
...
|
||||
);
|
||||
|
||||
}
|
||||
```
|
||||
|
||||
In the code above, you can get a reference to the current Phaser Game instance and the current Scene by creating a reference with `useRef()` and assign to PhaserGame component.
|
||||
|
||||
From this state reference, the game instance is available via `phaserRef.current.game` and the most recently active Scene via `phaserRef.current.scene`.
|
||||
|
||||
The `onCurrentActiveScene` callback will also be invoked whenever the the Phaser Scene changes, as long as you emit the event via the EventBus, as outlined above.
|
||||
|
||||
## 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 © 2011 - 2024 Phaser Studio Inc.
|
||||
|
||||
All rights reserved.
|
||||
16
index.html
Normal file
16
index.html
Normal file
@@ -0,0 +1,16 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<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 React Template</title>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
36
log.js
Normal file
36
log.js
Normal file
@@ -0,0 +1,36 @@
|
||||
const fs = require('fs');
|
||||
const https = require('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();
|
||||
3325
package-lock.json
generated
Normal file
3325
package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
47
package.json
Normal file
47
package.json
Normal file
@@ -0,0 +1,47 @@
|
||||
{
|
||||
"name": "template-react-ts",
|
||||
"description": "A Phaser 3 TypeScript project template that demonstrates React communication and uses Vite for bundling.",
|
||||
"version": "1.0.3",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/phaserjs/template-react-ts.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-react-ts/issues"
|
||||
},
|
||||
"homepage": "https://github.com/phaserjs/template-react-ts#readme",
|
||||
"keywords": [
|
||||
"phaser",
|
||||
"phaser3",
|
||||
"react",
|
||||
"vite",
|
||||
"typescript"
|
||||
],
|
||||
"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"
|
||||
},
|
||||
"dependencies": {
|
||||
"phaser": "^3.88.2",
|
||||
"react": "^18.2.0",
|
||||
"react-dom": "^18.2.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/react": "^18.3.3",
|
||||
"@types/react-dom": "^18.3.0",
|
||||
"@typescript-eslint/eslint-plugin": "^7.13.1",
|
||||
"@typescript-eslint/parser": "^7.13.1",
|
||||
"@vitejs/plugin-react": "^4.3.1",
|
||||
"eslint": "^8.57.0",
|
||||
"eslint-plugin-react-hooks": "^4.6.2",
|
||||
"eslint-plugin-react-refresh": "^0.4.7",
|
||||
"terser": "^5.28.1",
|
||||
"typescript": "^5.2.2",
|
||||
"vite": "^5.3.1"
|
||||
}
|
||||
}
|
||||
2133
pnpm-lock.yaml
generated
Normal file
2133
pnpm-lock.yaml
generated
Normal file
File diff suppressed because it is too large
Load Diff
BIN
public/assets/bg.png
Normal file
BIN
public/assets/bg.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 296 KiB |
1
public/assets/cursor/default.svg
Normal file
1
public/assets/cursor/default.svg
Normal file
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="128" height="128" viewBox="0 0 24 24"><path fill="currentColor" d="m16.574 19.2l-3.938-3.938l-1.203 1.202c-1.23 1.232-1.846 1.847-2.508 1.702s-.963-.963-1.565-2.596l-2.007-5.45C4.152 6.861 3.55 5.232 4.39 4.392s2.47-.24 5.73.962l5.45 2.006c1.633.602 2.45.903 2.596 1.565s-.47 1.277-1.702 2.508l-1.202 1.203l3.938 3.938c.408.408.612.612.706.84c.125.303.125.643 0 .947c-.094.227-.298.431-.706.839s-.612.612-.84.706a1.24 1.24 0 0 1-.947 0c-.227-.094-.43-.298-.839-.706"/></svg>
|
||||
|
After Width: | Height: | Size: 521 B |
BIN
public/assets/fonts/unifont-16.0.01.otf
Normal file
BIN
public/assets/fonts/unifont-16.0.01.otf
Normal file
Binary file not shown.
BIN
public/assets/logo.png
Normal file
BIN
public/assets/logo.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 24 KiB |
BIN
public/assets/star.png
Normal file
BIN
public/assets/star.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 7.1 KiB |
BIN
public/favicon.png
Normal file
BIN
public/favicon.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 354 B |
74
public/style.css
Normal file
74
public/style.css
Normal file
@@ -0,0 +1,74 @@
|
||||
body {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
color: rgba(255, 255, 255, 0.87);
|
||||
background-color: #000000;
|
||||
font-family: Arial, Helvetica, sans-serif;
|
||||
}
|
||||
|
||||
#app {
|
||||
width: 100%;
|
||||
height: 100vh;
|
||||
overflow: hidden;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.spritePosition {
|
||||
margin: 10px 0 0 10px;
|
||||
font-size: 0.8em;
|
||||
}
|
||||
|
||||
.button {
|
||||
width: 140px;
|
||||
margin: 10px;
|
||||
padding: 10px;
|
||||
background-color: #000000;
|
||||
color: rgba(255, 255, 255, 0.87);
|
||||
border: 1px solid rgba(255, 255, 255, 0.87);
|
||||
cursor: pointer;
|
||||
transition: all 0.3s;
|
||||
|
||||
&:hover {
|
||||
border: 1px solid #0ec3c9;
|
||||
color: #0ec3c9;
|
||||
}
|
||||
|
||||
&:active {
|
||||
background-color: #0ec3c9;
|
||||
}
|
||||
|
||||
/* Disabled styles */
|
||||
&:disabled {
|
||||
cursor: not-allowed;
|
||||
border: 1px solid rgba(255, 255, 255, 0.3);
|
||||
color: rgba(255, 255, 255, 0.3);
|
||||
}
|
||||
}
|
||||
|
||||
/* 全局字体 */
|
||||
@font-face {
|
||||
font-family: 'MainFont';
|
||||
src: url('/assets/fonts/unifont-16.0.01.otf') format('opentype');
|
||||
font-weight: normal;
|
||||
font-style: normal;
|
||||
}
|
||||
|
||||
.full-loading {
|
||||
position: fixed;
|
||||
z-index: 999999;
|
||||
top: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
background: #cecece;
|
||||
color: #eaeaea;
|
||||
text-align: center;
|
||||
font-size: 64px;
|
||||
line-height: 100vh;
|
||||
}
|
||||
|
||||
#game-container {
|
||||
/* cursor: none; */
|
||||
}
|
||||
BIN
screenshot.png
Normal file
BIN
screenshot.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 589 KiB |
104
src/App.tsx
Normal file
104
src/App.tsx
Normal file
@@ -0,0 +1,104 @@
|
||||
import { useRef, useState } from 'react';
|
||||
import { IRefPhaserGame, PhaserGame } from './game/PhaserGame';
|
||||
import { MainMenu } from './game/scenes/MainMenu';
|
||||
|
||||
function App()
|
||||
{
|
||||
// The sprite can only be moved in the MainMenu Scene
|
||||
const [canMoveSprite, setCanMoveSprite] = useState(true);
|
||||
|
||||
// References to the PhaserGame component (game and scene are exposed)
|
||||
const phaserRef = useRef<IRefPhaserGame | null>(null);
|
||||
const [spritePosition, setSpritePosition] = useState({ x: 0, y: 0 });
|
||||
|
||||
const changeScene = () => {
|
||||
|
||||
if(phaserRef.current)
|
||||
{
|
||||
const scene = phaserRef.current.scene as MainMenu;
|
||||
|
||||
if (scene)
|
||||
{
|
||||
scene.changeScene();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const moveSprite = () => {
|
||||
|
||||
if(phaserRef.current)
|
||||
{
|
||||
|
||||
const scene = phaserRef.current.scene as MainMenu;
|
||||
|
||||
if (scene && scene.scene.key === 'MainMenu')
|
||||
{
|
||||
// Get the update logo position
|
||||
scene.moveLogo(({ x, y }) => {
|
||||
|
||||
setSpritePosition({ x, y });
|
||||
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
const addSprite = () => {
|
||||
|
||||
if (phaserRef.current)
|
||||
{
|
||||
const scene = phaserRef.current.scene;
|
||||
|
||||
if (scene)
|
||||
{
|
||||
// Add more stars
|
||||
const x = Phaser.Math.Between(64, scene.scale.width - 64);
|
||||
const y = Phaser.Math.Between(64, scene.scale.height - 64);
|
||||
|
||||
// `add.sprite` is a Phaser GameObjectFactory method and it returns a Sprite Game Object instance
|
||||
const star = scene.add.sprite(x, y, 'star');
|
||||
|
||||
// ... which you can then act upon. Here we create a Phaser Tween to fade the star sprite in and out.
|
||||
// You could, of course, do this from within the Phaser Scene code, but this is just an example
|
||||
// showing that Phaser objects and systems can be acted upon from outside of Phaser itself.
|
||||
scene.add.tween({
|
||||
targets: star,
|
||||
duration: 500 + Math.random() * 1000,
|
||||
alpha: 0,
|
||||
yoyo: true,
|
||||
repeat: -1
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Event emitted from the PhaserGame component
|
||||
const currentScene = (scene: Phaser.Scene) => {
|
||||
|
||||
setCanMoveSprite(scene.scene.key !== 'MainMenu');
|
||||
|
||||
}
|
||||
|
||||
return (
|
||||
<div id="app">
|
||||
<PhaserGame ref={phaserRef} currentActiveScene={currentScene} />
|
||||
<div>
|
||||
<div>
|
||||
<button className="button" onClick={changeScene}>Change Scene</button>
|
||||
</div>
|
||||
<div>
|
||||
<button disabled={canMoveSprite} className="button" onClick={moveSprite}>Toggle Movement</button>
|
||||
</div>
|
||||
<div className="spritePosition">Sprite Position:
|
||||
<pre>{`{\n x: ${spritePosition.x}\n y: ${spritePosition.y}\n}`}</pre>
|
||||
</div>
|
||||
<div>
|
||||
<button className="button" onClick={addSprite}>Add New Sprite</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default App
|
||||
5
src/game/EventBus.ts
Normal file
5
src/game/EventBus.ts
Normal file
@@ -0,0 +1,5 @@
|
||||
import { Events } from 'phaser';
|
||||
|
||||
// Used to emit events between React components and Phaser scenes
|
||||
// https://newdocs.phaser.io/docs/3.70.0/Phaser.Events.EventEmitter
|
||||
export const EventBus = new Events.EventEmitter();
|
||||
102
src/game/PhaserGame.tsx
Normal file
102
src/game/PhaserGame.tsx
Normal file
@@ -0,0 +1,102 @@
|
||||
import { forwardRef, useEffect, useLayoutEffect, useRef, useState } from 'react';
|
||||
import StartGame from './main';
|
||||
import { EventBus } from './EventBus';
|
||||
|
||||
export interface IRefPhaserGame
|
||||
{
|
||||
game: Phaser.Game | null;
|
||||
scene: Phaser.Scene | null;
|
||||
}
|
||||
|
||||
interface IProps
|
||||
{
|
||||
currentActiveScene?: (scene_instance: Phaser.Scene) => void
|
||||
}
|
||||
|
||||
export const PhaserGame = forwardRef<IRefPhaserGame, IProps>(function PhaserGame({ currentActiveScene }, ref)
|
||||
{
|
||||
|
||||
const [isFontLoaded, setIsFontLoaded] = useState(false);
|
||||
const game = useRef<Phaser.Game | null>(null!);
|
||||
|
||||
useLayoutEffect(() =>
|
||||
{
|
||||
if (game.current === null)
|
||||
{
|
||||
|
||||
game.current = StartGame("game-container");
|
||||
|
||||
if (typeof ref === 'function')
|
||||
{
|
||||
ref({ game: game.current, scene: null });
|
||||
} else if (ref)
|
||||
{
|
||||
ref.current = { game: game.current, scene: null };
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
return () =>
|
||||
{
|
||||
if (game.current)
|
||||
{
|
||||
game.current.destroy(true);
|
||||
if (game.current !== null)
|
||||
{
|
||||
game.current = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}, [ref, isFontLoaded]);
|
||||
|
||||
useEffect(() =>
|
||||
{
|
||||
EventBus.on('current-scene-ready', (scene_instance: Phaser.Scene) =>
|
||||
{
|
||||
if (currentActiveScene && typeof currentActiveScene === 'function')
|
||||
{
|
||||
|
||||
currentActiveScene(scene_instance);
|
||||
|
||||
}
|
||||
|
||||
if (typeof ref === 'function')
|
||||
{
|
||||
ref({ game: game.current, scene: scene_instance });
|
||||
} else if (ref)
|
||||
{
|
||||
ref.current = { game: game.current, scene: scene_instance };
|
||||
}
|
||||
});
|
||||
return () =>
|
||||
{
|
||||
EventBus.removeListener('current-scene-ready');
|
||||
}
|
||||
}, [currentActiveScene, ref, isFontLoaded]);
|
||||
|
||||
useEffect(() => {
|
||||
// 定义要检测的字体名称
|
||||
const fontName = 'MainFont';
|
||||
|
||||
// 检测字体是否已加载
|
||||
const checkFont = async () => {
|
||||
try {
|
||||
await document.fonts.load(`1em ${fontName}`);
|
||||
setIsFontLoaded(true);
|
||||
} catch (error) {
|
||||
console.error('字体加载失败:', error);
|
||||
setIsFontLoaded(true); // 可选:即使失败也继续渲染
|
||||
}
|
||||
};
|
||||
|
||||
checkFont();
|
||||
}, []);
|
||||
|
||||
if (!isFontLoaded) {
|
||||
return <div className="full-loading">Loading font...</div>; // 显示加载状态
|
||||
}
|
||||
return (
|
||||
<div id="game-container"></div>
|
||||
);
|
||||
|
||||
});
|
||||
32
src/game/main.ts
Normal file
32
src/game/main.ts
Normal file
@@ -0,0 +1,32 @@
|
||||
import { Boot } from './scenes/Boot';
|
||||
import { GameOver } from './scenes/GameOver';
|
||||
import { Game as MainGame } from './scenes/Game';
|
||||
import { MainMenu } from './scenes/MainMenu';
|
||||
import { AUTO, Game } from 'phaser';
|
||||
import { Preloader } from './scenes/Preloader';
|
||||
import { Demo } from './scenes/Demo';
|
||||
|
||||
// Find out more information about the Game Config at:
|
||||
// https://newdocs.phaser.io/docs/3.70.0/Phaser.Types.Core.GameConfig
|
||||
const config: Phaser.Types.Core.GameConfig = {
|
||||
type: AUTO,
|
||||
width: 1920,
|
||||
height: 1080,
|
||||
parent: 'game-container',
|
||||
backgroundColor: '#028af8',
|
||||
scene: [
|
||||
Boot,
|
||||
Preloader,
|
||||
MainMenu,
|
||||
MainGame,
|
||||
GameOver,
|
||||
Demo
|
||||
]
|
||||
};
|
||||
|
||||
const StartGame = (parent: string) => {
|
||||
|
||||
return new Game({ ...config, parent });
|
||||
}
|
||||
|
||||
export default StartGame;
|
||||
39
src/game/scenes/Boot.ts
Normal file
39
src/game/scenes/Boot.ts
Normal file
@@ -0,0 +1,39 @@
|
||||
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');
|
||||
// this.input.setDefaultCursor('none');
|
||||
|
||||
// // 创建自定义指针精灵
|
||||
// this.cursor = this.add.sprite(0, 0, 'cursor.default')
|
||||
// .setOrigin(0.5, 0.5) // 将原点设为图片中心,确保对准点击点
|
||||
// .setScrollFactor(0) // 固定指针不随镜头滚动
|
||||
// .setDepth(9999);
|
||||
}
|
||||
|
||||
|
||||
update() {
|
||||
// const camera = this.cameras.main;
|
||||
// const pointer = this.input.activePointer;
|
||||
|
||||
// // 将屏幕坐标转换为世界坐标(考虑镜头偏移和缩放)
|
||||
// this.cursor.x = pointer.x / camera.zoom + camera.scrollX;
|
||||
// this.cursor.y = pointer.y / camera.zoom + camera.scrollY;
|
||||
}
|
||||
}
|
||||
36
src/game/scenes/Demo.ts
Normal file
36
src/game/scenes/Demo.ts
Normal file
@@ -0,0 +1,36 @@
|
||||
import { GameObjects, Scene } from 'phaser';
|
||||
|
||||
import UI from '../../utils/ui';
|
||||
|
||||
export class Demo extends Scene
|
||||
{
|
||||
uiUtils: UI;
|
||||
background: GameObjects.Image;
|
||||
logo: GameObjects.Image | GameObjects.Text;
|
||||
title: GameObjects.Text;
|
||||
logoTween: Phaser.Tweens.Tween | null;
|
||||
startButton: GameObjects.Text;
|
||||
|
||||
constructor ()
|
||||
{
|
||||
super('Demo');
|
||||
this.uiUtils = new UI(this);
|
||||
}
|
||||
|
||||
create ()
|
||||
{
|
||||
this.uiUtils.createText('demo v0.0', [0, 0])
|
||||
|
||||
}
|
||||
|
||||
changeScene ()
|
||||
{
|
||||
if (this.logoTween)
|
||||
{
|
||||
this.logoTween.stop();
|
||||
this.logoTween = null;
|
||||
}
|
||||
|
||||
this.scene.start('Game');
|
||||
}
|
||||
}
|
||||
36
src/game/scenes/Game.ts
Normal file
36
src/game/scenes/Game.ts
Normal file
@@ -0,0 +1,36 @@
|
||||
import { EventBus } from '../EventBus';
|
||||
import { Scene } from 'phaser';
|
||||
|
||||
export class Game extends Scene
|
||||
{
|
||||
camera: Phaser.Cameras.Scene2D.Camera;
|
||||
background: Phaser.GameObjects.Image;
|
||||
gameText: Phaser.GameObjects.Text;
|
||||
|
||||
constructor ()
|
||||
{
|
||||
super('Game');
|
||||
}
|
||||
|
||||
create ()
|
||||
{
|
||||
this.camera = this.cameras.main;
|
||||
this.camera.setBackgroundColor(0x00ff00);
|
||||
|
||||
this.background = this.add.image(512, 384, 'background');
|
||||
this.background.setAlpha(0.5);
|
||||
|
||||
this.gameText = 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).setDepth(100);
|
||||
|
||||
EventBus.emit('current-scene-ready', this);
|
||||
}
|
||||
|
||||
changeScene ()
|
||||
{
|
||||
this.scene.start('GameOver');
|
||||
}
|
||||
}
|
||||
36
src/game/scenes/GameOver.ts
Normal file
36
src/game/scenes/GameOver.ts
Normal file
@@ -0,0 +1,36 @@
|
||||
import { EventBus } from '../EventBus';
|
||||
import { Scene } from 'phaser';
|
||||
|
||||
export class GameOver extends Scene
|
||||
{
|
||||
camera: Phaser.Cameras.Scene2D.Camera;
|
||||
background: Phaser.GameObjects.Image;
|
||||
gameOverText : Phaser.GameObjects.Text;
|
||||
|
||||
constructor ()
|
||||
{
|
||||
super('GameOver');
|
||||
}
|
||||
|
||||
create ()
|
||||
{
|
||||
this.camera = this.cameras.main
|
||||
this.camera.setBackgroundColor(0xff0000);
|
||||
|
||||
this.background = this.add.image(512, 384, 'background');
|
||||
this.background.setAlpha(0.5);
|
||||
|
||||
this.gameOverText = this.add.text(512, 384, 'Game Over', {
|
||||
fontFamily: 'Arial Black', fontSize: 64, color: '#ffffff',
|
||||
stroke: '#000000', strokeThickness: 8,
|
||||
align: 'center'
|
||||
}).setOrigin(0.5).setDepth(100);
|
||||
|
||||
EventBus.emit('current-scene-ready', this);
|
||||
}
|
||||
|
||||
changeScene ()
|
||||
{
|
||||
this.scene.start('MainMenu');
|
||||
}
|
||||
}
|
||||
85
src/game/scenes/MainMenu.ts
Normal file
85
src/game/scenes/MainMenu.ts
Normal file
@@ -0,0 +1,85 @@
|
||||
import { GameObjects, Scene } from 'phaser';
|
||||
|
||||
import UI from '../../utils/ui';
|
||||
|
||||
export class MainMenu extends Scene
|
||||
{
|
||||
uiUtils: UI;
|
||||
background: GameObjects.Image;
|
||||
logo: GameObjects.Image | GameObjects.Text;
|
||||
title: GameObjects.Text;
|
||||
logoTween: Phaser.Tweens.Tween | null;
|
||||
startButton: GameObjects.Text;
|
||||
cursor: GameObjects.Image;
|
||||
|
||||
constructor ()
|
||||
{
|
||||
super('MainMenu');
|
||||
this.uiUtils = new UI(this);
|
||||
}
|
||||
|
||||
create ()
|
||||
{
|
||||
|
||||
this.logo = this.uiUtils.createText('代号:江湖', ['center', 320], {
|
||||
fontSize: 64,
|
||||
color: '#028af8',
|
||||
backgroundColor: "#FFF",
|
||||
padding: {x: 16, y: 8}
|
||||
});
|
||||
|
||||
this.startButton = this.uiUtils.createTextButton('开始', ['center', 520], () => {
|
||||
this.scene.start('Demo');
|
||||
});
|
||||
}
|
||||
|
||||
changeScene ()
|
||||
{
|
||||
if (this.logoTween)
|
||||
{
|
||||
this.logoTween.stop();
|
||||
this.logoTween = null;
|
||||
}
|
||||
|
||||
this.scene.start('Game');
|
||||
}
|
||||
|
||||
moveLogo (vueCallback: ({ x, y }: { x: number, y: number }) => void)
|
||||
{
|
||||
if (this.logoTween)
|
||||
{
|
||||
if (this.logoTween.isPlaying())
|
||||
{
|
||||
this.logoTween.pause();
|
||||
}
|
||||
else
|
||||
{
|
||||
this.logoTween.play();
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
this.logoTween = this.tweens.add({
|
||||
targets: this.logo,
|
||||
x: { value: 750, duration: 3000, ease: 'Back.easeInOut' },
|
||||
y: { value: 80, duration: 1500, ease: 'Sine.easeOut' },
|
||||
yoyo: true,
|
||||
repeat: -1,
|
||||
onUpdate: () => {
|
||||
if (vueCallback)
|
||||
{
|
||||
vueCallback({
|
||||
x: Math.floor(this.logo.x),
|
||||
y: Math.floor(this.logo.y)
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
preload() {
|
||||
// 加载OTF字体
|
||||
// this.load.add('MainFont', 'assets/fonts/unifont-16.0.01.otf');
|
||||
}
|
||||
}
|
||||
47
src/game/scenes/Preloader.ts
Normal file
47
src/game/scenes/Preloader.ts
Normal file
@@ -0,0 +1,47 @@
|
||||
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(1920, 1080, '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: number) => {
|
||||
|
||||
// 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');
|
||||
this.load.image('star', 'star.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');
|
||||
}
|
||||
}
|
||||
131
src/game/sprites/baseSprite.ts
Normal file
131
src/game/sprites/baseSprite.ts
Normal file
@@ -0,0 +1,131 @@
|
||||
/**
|
||||
* 基础角色类型
|
||||
*/
|
||||
export default class baseSprite extends Phaser.GameObjects.Sprite {
|
||||
id: string; // id
|
||||
spriteName: string; // 名字
|
||||
agility: number; // 敏捷(影响闪避/攻速)
|
||||
strength: number; // 力量(影响物理伤害)
|
||||
constitution: number; // 体质(影响生命/防御)
|
||||
luck: number; // 运气(影响稀有掉落/暴击)
|
||||
intelligence: number; // 智力(影响魔法/技能)
|
||||
stamina: number; // 耐力(影响持久作战能力)
|
||||
|
||||
// 战斗属性
|
||||
attackRate: number; // 攻击力
|
||||
criticalRate: number; // 暴击率 (Crit%)
|
||||
counterRate: number; // 反击率 (Counter%)
|
||||
comboRate: number; // 连击率 (Combo%)
|
||||
hitRate: number; // 命中率 (Hit%)
|
||||
parryRate: number; // 弹反率 (Parry%)
|
||||
|
||||
// 基础属性
|
||||
health: number; // 血量 (HP)
|
||||
mana: number; // 蓝量 (MP)
|
||||
|
||||
|
||||
constructor(scene: Phaser.Scene, x: number, y: number, texture: string | Phaser.Textures.Texture) {
|
||||
super(scene, x, y, texture);
|
||||
|
||||
// 将角色添加到场景中
|
||||
scene.add.existing(this);
|
||||
}
|
||||
|
||||
init() {
|
||||
const baseProperty:basePropertyType = this.getBaseProperty();
|
||||
const property = this.getProperty(baseProperty);
|
||||
this.agility = baseProperty.agility;
|
||||
this.constitution = baseProperty.constitution;
|
||||
this.intelligence = baseProperty.intelligence;
|
||||
this.luck = baseProperty.luck;
|
||||
this.stamina = baseProperty.stamina;
|
||||
this.strength = baseProperty.strength;
|
||||
this.attackRate = property.attackRate;
|
||||
this.criticalRate = property.criticalRate;
|
||||
this.counterRate = property.counterRate;
|
||||
this.comboRate = property.comboRate;
|
||||
this.hitRate = property.hitRate;
|
||||
this.parryRate = property.parryRate;
|
||||
this.health = property.health;
|
||||
this.mana = property.mana;
|
||||
}
|
||||
|
||||
getBaseProperty() {
|
||||
return {
|
||||
agility: 0,
|
||||
strength: 0,
|
||||
constitution: 0,
|
||||
luck: 0,
|
||||
intelligence: 0,
|
||||
stamina: 0,
|
||||
}
|
||||
// throw new Error("需要实现这个方法!");
|
||||
}
|
||||
|
||||
getProperty(baseProperty:basePropertyType) {
|
||||
return {
|
||||
...baseProperty,
|
||||
// 战斗属性
|
||||
attackRate: this.getAttack(baseProperty), // 攻击力
|
||||
criticalRate: this.getCritical(baseProperty), // 暴击率 (Crit%)
|
||||
counterRate: this.getCounter(baseProperty), // 反击率 (Counter%)
|
||||
comboRate: this.getCombo(baseProperty), // 连击率 (Combo%)
|
||||
hitRate: this.getHit(baseProperty), // 命中率 (Hit%)
|
||||
parryRate: this.getParry(baseProperty), // 弹反率 (Parry%)
|
||||
// 基础属性
|
||||
health: this.getHealth(baseProperty), // 血量 (HP)
|
||||
mana: this.getMana(baseProperty), // 蓝量 (MP)
|
||||
}
|
||||
}
|
||||
|
||||
getAttack(baseProperty: basePropertyType) {
|
||||
const attack = baseProperty.strength * 2 + baseProperty.agility * 0.5;
|
||||
return Math.max(attack, 10); // 攻击力最低10
|
||||
}
|
||||
|
||||
getCritical(baseProperty: basePropertyType) {
|
||||
const crit = baseProperty.luck * 0.1;
|
||||
return Math.max(crit, 10); // 暴击率最低10%
|
||||
}
|
||||
|
||||
getCounter(baseProperty: basePropertyType) {
|
||||
const counter = baseProperty.agility * 0.05 + baseProperty.luck * 0.02;
|
||||
return Math.max(counter, 10); // 反击率最低10%
|
||||
}
|
||||
|
||||
getCombo(baseProperty: basePropertyType) {
|
||||
const combo = (baseProperty.agility + baseProperty.luck) * 0.08;
|
||||
return Math.max(combo, 10); // 连击率最低10%
|
||||
}
|
||||
|
||||
getParry(baseProperty: basePropertyType) {
|
||||
const parry = baseProperty.agility * 0.1 + baseProperty.strength * 0.05;
|
||||
return Math.max(parry, 10); // 弹反率最低10%
|
||||
}
|
||||
|
||||
getHealth(baseProperty: basePropertyType) {
|
||||
const health = baseProperty.constitution * 10 + baseProperty.stamina * 5;
|
||||
return Math.max(health, 100); // 生命值最低100
|
||||
}
|
||||
|
||||
getMana(baseProperty: basePropertyType) {
|
||||
const mana = baseProperty.intelligence * 8 + baseProperty.constitution * 2;
|
||||
return Math.max(mana, 100); // 法力值最低100
|
||||
}
|
||||
|
||||
// 保持原有命中率计算(95%基础+敏捷修正)
|
||||
getHit(baseProperty: basePropertyType) {
|
||||
const hit = 95 + baseProperty.agility * 0.2;
|
||||
return Math.min(Math.max(hit, 5), 100); // 命中率在5%-100%之间
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
export type basePropertyType = {
|
||||
agility: number; // 敏捷(影响闪避/攻速)
|
||||
strength: number; // 力量(影响物理伤害)
|
||||
constitution: number; // 体质(影响生命/防御)
|
||||
luck: number; // 运气(影响稀有掉落/暴击)
|
||||
intelligence: number; // 智力(影响魔法/技能)
|
||||
stamina: number; // 耐力(影响持久作战能力)
|
||||
}
|
||||
0
src/game/sprites/player.ts
Normal file
0
src/game/sprites/player.ts
Normal file
9
src/main.tsx
Normal file
9
src/main.tsx
Normal file
@@ -0,0 +1,9 @@
|
||||
import React from 'react';
|
||||
import ReactDOM from 'react-dom/client';
|
||||
import App from './App.tsx';
|
||||
|
||||
ReactDOM.createRoot(document.getElementById('root')!).render(
|
||||
<React.StrictMode>
|
||||
<App />
|
||||
</React.StrictMode>,
|
||||
)
|
||||
14
src/utils/role.ts
Normal file
14
src/utils/role.ts
Normal file
@@ -0,0 +1,14 @@
|
||||
/**
|
||||
*
|
||||
* @param Agility 速度
|
||||
* @param Strength 力量
|
||||
* @param Constitution 体力
|
||||
* @param Luck 运气
|
||||
* @param Intelligence 智力
|
||||
* @param Stamina 精力
|
||||
* @returns
|
||||
*/
|
||||
export function getScorScore(Agility:number, Strength:number, Constitution:number, Luck:number, Intelligence:number, Stamina:number) {
|
||||
// return Agility * 0.8 + Strength * 1 + Constitution * 1.3 + Luck * 0.3 + Intelligence * 0.8 + Stamina *1.2
|
||||
return (Agility + Strength + Intelligence + Stamina) ^ Strength * (1 - Luck * 0.01)
|
||||
}
|
||||
100
src/utils/ui.ts
Normal file
100
src/utils/ui.ts
Normal file
@@ -0,0 +1,100 @@
|
||||
/**
|
||||
* UI utils
|
||||
*/
|
||||
|
||||
export default class UI {
|
||||
scene: Phaser.Scene;
|
||||
|
||||
// 默认字体配置
|
||||
private defaultFontConfig: Phaser.Types.GameObjects.Text.TextStyle = {
|
||||
fontFamily: 'MainFont', // 你的自定义字体名称
|
||||
fontSize: 32,
|
||||
color: '#FFFFFF',
|
||||
stroke: '#000000',
|
||||
strokeThickness: 4,
|
||||
align: 'center'
|
||||
};
|
||||
|
||||
// private defaultImageConfig: Phaser.Types.GameObjects.Image.TextStyle = {
|
||||
// fontFamily: 'MainFont', // 你的自定义字体名称
|
||||
// fontSize: 32,
|
||||
// color: '#FFFFFF',
|
||||
// stroke: '#000000',
|
||||
// strokeThickness: 4,
|
||||
// align: 'center'
|
||||
// };
|
||||
|
||||
constructor(scene: Phaser.Scene) {
|
||||
this.scene = scene;
|
||||
}
|
||||
|
||||
createText(
|
||||
text: string,
|
||||
position: [number|'center', number|'center'] = [0, 0],
|
||||
style: Phaser.Types.GameObjects.Text.TextStyle = this.defaultFontConfig
|
||||
): Phaser.GameObjects.Text {
|
||||
// 合并默认样式和自定义样式
|
||||
const mergedStyle = { ...this.defaultFontConfig, ...style };
|
||||
return this?.scene?.add?.text(
|
||||
position[0] !== 'center' ? position[0]: this.scene.renderer.width/2,
|
||||
position[1] !== 'center' ? position[1]: this.scene.renderer.height/2,
|
||||
text,
|
||||
mergedStyle
|
||||
)
|
||||
.setDepth(100)
|
||||
.setOrigin(
|
||||
position[1] !== 'center'||position[0] !== 'center'?
|
||||
0.5:
|
||||
0
|
||||
);
|
||||
}
|
||||
|
||||
createImage(
|
||||
src: string,
|
||||
position: [number, number] = [0, 0],
|
||||
): Phaser.GameObjects.Image {
|
||||
return this.scene?.add?.image(
|
||||
position[0],
|
||||
position[1],
|
||||
src,
|
||||
)
|
||||
.setDepth(100)
|
||||
.setOrigin(0.5);
|
||||
}
|
||||
|
||||
createTextButton(
|
||||
text: string,
|
||||
position: [number|'center', number|'center'] = [0, 0],
|
||||
onClick: () => void = () => {},
|
||||
style: Phaser.Types.GameObjects.Text.TextStyle = this.defaultFontConfig
|
||||
): Phaser.GameObjects.Text {
|
||||
// 合并默认样式和自定义样式
|
||||
const mergedStyle = { ...this.defaultFontConfig, ...style };
|
||||
const result = this?.scene?.add?.text(
|
||||
position[0] !== 'center' ? position[0]: this.scene.renderer.width/2,
|
||||
position[1] !== 'center' ? position[1]: this.scene.renderer.height/2,
|
||||
text,
|
||||
mergedStyle
|
||||
)
|
||||
.setDepth(100)
|
||||
.setOrigin(0.5)
|
||||
.setInteractive()
|
||||
.on('pointerdown', onClick)
|
||||
.on('pointerover', () => {
|
||||
result.setStyle({ fill: '#ffff00' }); // 悬停变黄
|
||||
result.setScale(1.1); // 放大10%
|
||||
})
|
||||
.on('pointerout', () => {
|
||||
result.setStyle({ fill: '#ffffff' }); // 恢复白色
|
||||
result.setScale(1); // 恢复原尺寸
|
||||
});
|
||||
return result
|
||||
}
|
||||
|
||||
// createProgress(
|
||||
// value,
|
||||
// max,
|
||||
// min,
|
||||
// ):
|
||||
// create
|
||||
}
|
||||
1
src/vite-env.d.ts
vendored
Normal file
1
src/vite-env.d.ts
vendored
Normal file
@@ -0,0 +1 @@
|
||||
/// <reference types="vite/client" />
|
||||
26
tsconfig.json
Normal file
26
tsconfig.json
Normal file
@@ -0,0 +1,26 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2020",
|
||||
"useDefineForClassFields": true,
|
||||
"lib": ["ES2020", "DOM", "DOM.Iterable"],
|
||||
"module": "ESNext",
|
||||
"skipLibCheck": true,
|
||||
|
||||
/* Bundler mode */
|
||||
"moduleResolution": "bundler",
|
||||
"allowImportingTsExtensions": true,
|
||||
"resolveJsonModule": true,
|
||||
"isolatedModules": true,
|
||||
"noEmit": true,
|
||||
"jsx": "react-jsx",
|
||||
|
||||
/* Linting */
|
||||
"strict": true,
|
||||
"strictPropertyInitialization": false,
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"noFallthroughCasesInSwitch": true
|
||||
},
|
||||
"include": ["src"],
|
||||
"references": [{ "path": "./tsconfig.node.json" }]
|
||||
}
|
||||
11
tsconfig.node.json
Normal file
11
tsconfig.node.json
Normal file
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"composite": true,
|
||||
"skipLibCheck": true,
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "bundler",
|
||||
"allowSyntheticDefaultImports": true,
|
||||
"strict": true
|
||||
},
|
||||
"include": ["vite.config.ts"]
|
||||
}
|
||||
13
vite/config.dev.mjs
Normal file
13
vite/config.dev.mjs
Normal file
@@ -0,0 +1,13 @@
|
||||
import { defineConfig } from 'vite'
|
||||
import react from '@vitejs/plugin-react'
|
||||
|
||||
// https://vitejs.dev/config/
|
||||
export default defineConfig({
|
||||
base: './',
|
||||
plugins: [
|
||||
react(),
|
||||
],
|
||||
server: {
|
||||
port: 8080
|
||||
}
|
||||
})
|
||||
46
vite/config.prod.mjs
Normal file
46
vite/config.prod.mjs
Normal file
@@ -0,0 +1,46 @@
|
||||
import { defineConfig } from 'vite';
|
||||
import react from '@vitejs/plugin-react';
|
||||
|
||||
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: './',
|
||||
plugins: [
|
||||
react(),
|
||||
phasermsg()
|
||||
],
|
||||
logLevel: 'warning',
|
||||
build: {
|
||||
rollupOptions: {
|
||||
output: {
|
||||
manualChunks: {
|
||||
phaser: ['phaser']
|
||||
}
|
||||
}
|
||||
},
|
||||
minify: 'terser',
|
||||
terserOptions: {
|
||||
compress: {
|
||||
passes: 2
|
||||
},
|
||||
mangle: true,
|
||||
format: {
|
||||
comments: false
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
Reference in New Issue
Block a user