-
Notifications
You must be signed in to change notification settings - Fork 2
Context API Player RU
dev2alert edited this page Feb 2, 2022
·
7 revisions
Главная ▸ Context API ▸ Игрок
В контексте игрока доступны все функции обратного вызова, которые касаются игрока SA-MP.
Команды, обработчики событий клавиатуры и обработчики событий ответов с диалогов не будут выполняться, когда контекст заморожен.
Пример:
// index.ts
import {Player} from "@sa-mp/core";
import {ModePlayer} from "./mode.pctx";
Player.Factory.create(ModePlayer);
Пример:
// index.ts
import {GameMode, Player} from "@sa-mp/core";
import {Mode} from "./mode.gctx";
import {ModePlayer} from "./mode.pctx";
const gamemodeFactory = GameMode.Factory.create(Mode);
Player.Factory.create(ModePlayer, {gamemodeFactory});
Привязывание необходимо для того, чтобы была возможность импортировать контекст игрового режима в контексте игрока.
Параметры передаются вторым аргументом при создании фабрики.
Имя | Тип | Описание |
---|---|---|
gamemodeFactory | GameMode.Factory | Привязывание фабрики игрового режима. |
extensions | (typeof Player.Extension)[] | Список расширений фабрики. |
commands | boolean | Использовать ли команды. |
keys | boolean | Использовать ли обработчики событий клавиатуры. |
dialogs | boolean | Использовать ли обработчики событий ответов с диалогов. |
Пример:
// mode.pctx.ts
import {Player} from "@sa-mp/core";
import {Context, Import, ImportService} from "@sa-mp/decorators";
import {Mode} from "./mode.gctx";
import {ModePlayerService} from "./mode.psv";
@Context({
services: [ModePlayerService]
})
export class ModePlayer extends Player.Context {
@Import()
public readonly mode: Mode;
@ImportService()
public readonly modeService: ModePlayerService;
public onConnect(): void {
this.send(`Hello, ${this}!`);
this.send(`7 - 5 = ${this.mode.minus(7, 5)};`);
this.send(`3 + 4 = ${this.modeService.sum(3, 4)};`);
}
}
Пример:
// mode.psv.ts
import {Player} from "@sa-mp/core";
import {Service} from "@sa-mp/decorators";
@Service()
export class ModePlayerService extends Player.Service {
public sum(a: number, b: number): number {
return a + b;
}
}
Пример:
// mode.pctx.ts
import {CommandList, Player} from "@sa-mp/core";
import {Alt, Command, Context, Param, ParamInt, ParamNumber, ParamString} from "@sa-mp/decorators";
@Context()
export class ModePlayer extends Player.Context {
@Command("spawn", "Spawn.")
@Alt("s", "sn")
public spawnPlayer(): void {
this.spawn();
}
@Command("pos", "Set position.")
@Alt("p")
public setPosition(@ParamNumber("x") x: number, @Param("y") y: number, @Param("z") z: number): void {
this.pos = {x, y, z};
}
@Command("weather", "Set weather.")
public setWeather(@ParamInt("weather") weather: number): void {
this.weather = weather;
}
@Command("send", "Send message.")
public sendMessage(@ParamString("message") message: string): void {
this.sendToAll(message);
}
public onCommandInvalid(): boolean {
this.send("[Error]{FFFFFF} Command invalid.", 0xe04010AA);
return true;
}
public onCommandNotFound(name: string): boolean {
this.send(`[Error]{FFFFFF} Command {dbce12}${name}{FFFFFF} not found.`, 0xe04010AA);
return true;
}
public onCommandParamsMismatch(cmdList: CommandList): boolean {
if(cmdList.desc) {
this.send(cmdList.desc, 0xdbdbdbAA);
this.send();
}
for(const cmd of cmdList)
this.send(`{b3afaf}/${cmd.name} {dbce12}${cmd.params.map(({name, type}) => `<${name}: ${Player.command.paramTypeNames[type]}>`).join(" ")}`);
return true;
}
}
Пример:
// mode.pctx.ts
import {Keys, Player} from "@sa-mp/core";
import {Context, Key} from "@sa-mp/decorators";
@Context()
export class ModePlayer extends Player.Context {
@Key(Keys.YES)
public handleYes(): void {
this.send("[Y]", 0xfcba03AA);
}
@Key(Keys.NO)
public handleNo(): void {
this.send("[N]", 0xfcba03AA);
}
}
Пример:
// mode.pctx.ts
import {Dialog, DialogResponse, DialogStyles, Player} from "@sa-mp/core";
import {Context, DialogRes} from "@sa-mp/decorators";
@Context()
export class ModePlayer extends Player.Context {
public static readonly genderDialog = new Dialog({
style: DialogStyles.MSGBOX,
caption: "Gender",
info: " ",
buttons: ["Male", "Female"]
});
public static readonly ageDialog = new Dialog({
style: DialogStyles.INPUT,
caption: "Age",
info: " ",
buttons: ["Ok"]
});
public static readonly passwordDialog = new Dialog({
style: DialogStyles.PASSWORD,
caption: "Password",
info: " ",
buttons: ["Ok"]
});
public static readonly infoDialog = new Dialog({
style: DialogStyles.MSGBOX,
caption: "Info",
info: " ",
buttons: ["Ok"]
});
public gender: boolean;
public age: number;
public password: string;
public onConnect(): void {
this.dialog(ModePlayer.genderDialog);
}
@DialogRes(ModePlayer.genderDialog)
public handleGender({response}: DialogResponse): void {
this.gender = response;
this.dialog(ModePlayer.ageDialog);
}
@DialogRes(ModePlayer.ageDialog)
public handleAge({inputText}: DialogResponse): void {
this.age = Number(inputText);
this.dialog(ModePlayer.passwordDialog);
}
@DialogRes(ModePlayer.passwordDialog)
public handlePassword({inputText}: DialogResponse): void {
this.password = inputText;
let info: string = `Gender: ${this.gender ? "Male" : "Female"}.\n`;
info += `Age: ${this.age}.\n`;
info += `Password: ${this.password}.`;
ModePlayer.infoDialog.info = info;
this.dialog(ModePlayer.infoDialog);
}
}
- Getting started [RU]
- Configuration [RU]
- Command line interface (CLI) [RU]
- Examples [RU]
- Player commands [RU]
- Keyboard [RU]
- Dialogs [RU]
- Groups [RU]
- Context API [RU]
- AMX API [RU]