Система голосования Panorama позволяет создавать пользовательские голосования Да/Нет, которые отображаются в интерфейсе CS2. Игроки могут голосовать с помощью встроенного игрового интерфейса, что делает процесс естественным и знакомым.
Ключевые возможности:
Интеграция с нативным UI CS2
Настраиваемые сообщения голосования и текст успеха/провала
Выборочное таргетирование игроков с использованием битовой маски
Обратные вызовы событий голосования (начало, голос, конец)
Пользовательская логика успеха/провала с подробной статистикой голосования
Автоматическая обработка тайм-аута
Игроки голосуют клавишами F1 и F2 (консольные команды vote option1 и vote option2). Игра принимает их голоса, только пока ConVar sv_allow_votes равен 1, это его значение по умолчанию.
Событие End приходит до вызова обратного вызова результата, поэтому по нему нельзя узнать, прошло ли голосование. Действуйте по итогу в обратном вызове результата.
PanoramaSendYesNoVoteToAll - Создает голосование для всех игроков
PanoramaSendYesNoVote - Создает голосование для определенных игроков (используя битовую маску получателей)
Обе возвращают true, если голосование началось. Они возвращают false, если уже идёт другое голосование, нет получателей, не передан обратный вызов результата или сущность карты vote_controller ещё не найдена (s2sdk ищет её на round_start, поэтому запускайте голосования, когда раунд уже идёт, например из команды).
using Plugify;
using s2sdk;
using static s2sdk.s2sdk;
public class VoteExample : Plugin
{
// Not exported by s2sdk: player slot shown as "Server" and the vote options
private const int VOTE_CALLER_SERVER = 99;
private const int VOTE_OPTION1 = 0; // Yes
// Call this once a round is running (for example from a command)
public void StartRestartVote()
{
// Create a simple vote for all players
bool started = PanoramaSendYesNoVoteToAll(
duration: 30.0,
caller: VOTE_CALLER_SERVER,
voteTitle: "#SFUI_vote_restart_game",
detailStr: "",
votePassTitle: "#SFUI_vote_passed_restart_game",
detailPassStr: "",
failReason: VoteCreateFailed.Generic,
result: OnVoteResult,
handler: OnVoteHandler
);
if (!started)
{
PrintToServer("Could not start the vote\n");
}
}
// Called to determine if vote passes
private Bool8 OnVoteResult(int numVotes, int yesVotes, int noVotes,
int numClients, int[] clientInfoSlot, int[] clientInfoItem)
{
PrintToServer($"Vote finished: {yesVotes} Yes, {noVotes} No, " +
$"{numVotes}/{numClients} voted\n");
// Simple majority of the votes cast
bool passed = yesVotes > noVotes;
if (passed)
{
ServerCommand("mp_restartgame 1");
}
return passed;
}
// Called for vote events
private void OnVoteHandler(VoteAction action, int clientSlot, int choice)
{
switch (action)
{
case VoteAction.Start:
PrintToServer("Vote started!\n");
break;
case VoteAction.Vote:
string vote = choice == VOTE_OPTION1 ? "Yes" : "No";
PrintToServer($"Player {clientSlot} voted: {vote}\n");
break;
case VoteAction.End:
VoteEndReason reason = (VoteEndReason)choice;
PrintToServer($"Vote ended: {reason}\n");
// The result callback runs after this event
break;
}
}
}
#include <plg/plugin.hpp>
#include <format>
#include <s2sdk/s2sdk.hpp>
using namespace s2sdk;
// Not exported by s2sdk: player slot shown as "Server" and the vote options
constexpr int32_t VOTE_CALLER_SERVER = 99;
constexpr int32_t VOTE_OPTION1 = 0; // Yes
// Call this once a round is running (for example from a command)
void StartRestartVote() {
bool started = PanoramaSendYesNoVoteToAll(
30.0,
VOTE_CALLER_SERVER,
"#SFUI_vote_restart_game",
"",
"#SFUI_vote_passed_restart_game",
"",
VoteCreateFailed::Generic,
// Result callback - determines pass/fail
[](int32_t numVotes, int32_t yesVotes, int32_t noVotes, int32_t numClients,
const plg::vector<int32_t>& clientInfoSlot,
const plg::vector<int32_t>& clientInfoItem) -> bool {
PrintToServer(std::format("Vote: {} Yes, {} No, {}/{} voted\n",
yesVotes, noVotes, numVotes, numClients));
bool passed = yesVotes > noVotes; // Simple majority
if (passed) {
ServerCommand("mp_restartgame 1");
}
return passed;
},
// Handler callback - vote events
[](VoteAction action, int32_t clientSlot, int32_t choice) {
switch (action) {
case VoteAction::Start:
PrintToServer("Vote started!\n");
break;
case VoteAction::Vote: {
const char* vote = choice == VOTE_OPTION1 ? "Yes" : "No";
PrintToServer(std::format("Player {} voted: {}\n",
clientSlot, vote));
break;
}
case VoteAction::End:
PrintToServer(std::format("Vote ended: {}\n", choice));
break;
}
}
);
if (!started) {
PrintToServer("Could not start the vote\n");
}
}
from plugify.plugin import Plugin
from plugify.pps import s2sdk as s2
# Not exported by s2sdk: player slot shown as "Server" and the vote options
VOTE_CALLER_SERVER = 99
VOTE_OPTION1 = 0 # Yes
def on_vote_result(num_votes, yes_votes, no_votes, num_clients,
client_info_slot, client_info_item):
s2.PrintToServer(f"Vote: {yes_votes} Yes, {no_votes} No, "
f"{num_votes}/{num_clients} voted\n")
passed = yes_votes > no_votes # Simple majority
if passed:
s2.ServerCommand("mp_restartgame 1")
return passed
def on_vote_handler(action, client_slot, choice):
if action == s2.VoteAction.Start:
s2.PrintToServer("Vote started!\n")
elif action == s2.VoteAction.Vote:
vote = "Yes" if choice == VOTE_OPTION1 else "No"
s2.PrintToServer(f"Player {client_slot} voted: {vote}\n")
elif action == s2.VoteAction.End:
reason = s2.VoteEndReason(choice)
s2.PrintToServer(f"Vote ended: {reason.name}\n")
class VoteExample(Plugin):
# Call this once a round is running (for example from a command)
def start_restart_vote(self):
started = s2.PanoramaSendYesNoVoteToAll(
30.0, # duration
VOTE_CALLER_SERVER, # caller
"#SFUI_vote_restart_game", # voteTitle
"", # detailStr
"#SFUI_vote_passed_restart_game", # votePassTitle
"", # detailPassStr
s2.VoteCreateFailed.Generic, # failReason
on_vote_result, # result
on_vote_handler # handler
)
if not started:
s2.PrintToServer("Could not start the vote\n")
package main
import (
"fmt"
"github.com/fr0nch/go-plugify-s2sdk/v2"
)
// Not exported by s2sdk: player slot shown as "Server" and the vote options
const VOTE_CALLER_SERVER int32 = 99
const VOTE_OPTION1 int32 = 0 // Yes
func onVoteResult(numVotes, yesVotes, noVotes, numClients int32,
clientInfoSlot, clientInfoItem []int32) bool {
s2sdk.PrintToServer(fmt.Sprintf("Vote: %d Yes, %d No, %d/%d voted\n",
yesVotes, noVotes, numVotes, numClients))
passed := yesVotes > noVotes // Simple majority
if passed {
s2sdk.ServerCommand("mp_restartgame 1")
}
return passed
}
func onVoteHandler(action s2sdk.VoteAction, clientSlot, choice int32) {
switch action {
case s2sdk.VoteAction_Start:
s2sdk.PrintToServer("Vote started!\n")
case s2sdk.VoteAction_Vote:
vote := "No"
if choice == VOTE_OPTION1 {
vote = "Yes"
}
s2sdk.PrintToServer(fmt.Sprintf("Player %d voted: %s\n", clientSlot, vote))
case s2sdk.VoteAction_End:
s2sdk.PrintToServer(fmt.Sprintf("Vote ended: %d\n", choice))
}
}
// Call this once a round is running (for example from a command)
func startRestartVote() {
started := s2sdk.PanoramaSendYesNoVoteToAll(
30.0,
VOTE_CALLER_SERVER,
"#SFUI_vote_restart_game",
"",
"#SFUI_vote_passed_restart_game",
"",
s2sdk.VoteCreateFailed_Generic,
onVoteResult,
onVoteHandler,
)
if !started {
s2sdk.PrintToServer("Could not start the vote\n")
}
}
import { Plugin } from 'plugify';
import * as s2 from ':s2sdk';
// Not exported by s2sdk: player slot shown as "Server" and the vote options
const VOTE_CALLER_SERVER = 99;
const VOTE_OPTION1 = 0; // Yes
export class VoteExample extends Plugin {
// Call this once a round is running (for example from a command)
startRestartVote() {
const started = s2.PanoramaSendYesNoVoteToAll(
30.0,
VOTE_CALLER_SERVER,
"#SFUI_vote_restart_game",
"",
"#SFUI_vote_passed_restart_game",
"",
s2.VoteCreateFailed.Generic,
// Result callback
(numVotes, yesVotes, noVotes, numClients, clientInfoSlot, clientInfoItem) => {
s2.PrintToServer(`Vote: ${yesVotes} Yes, ${noVotes} No, ${numVotes}/${numClients} voted\n`);
const passed = yesVotes > noVotes;
if (passed) {
s2.ServerCommand("mp_restartgame 1");
}
return passed;
},
// Handler callback
(action, clientSlot, choice) => {
if (action === s2.VoteAction.Start) {
s2.PrintToServer("Vote started!\n");
} else if (action === s2.VoteAction.Vote) {
const vote = choice === VOTE_OPTION1 ? "Yes" : "No";
s2.PrintToServer(`Player ${clientSlot} voted: ${vote}\n`);
} else if (action === s2.VoteAction.End) {
s2.PrintToServer(`Vote ended: ${choice}\n`);
}
}
);
if (!started) {
s2.PrintToServer("Could not start the vote\n");
}
}
}
local plugify = require 'plugify'
local Plugin = plugify.Plugin
local s2 = require 's2sdk'
-- Not exported by s2sdk: player slot shown as "Server" and the vote options
local VOTE_CALLER_SERVER = 99
local VOTE_OPTION1 = 0 -- Yes
local VoteExample = {}
setmetatable(VoteExample, { __index = Plugin })
local function on_vote_result(num_votes, yes_votes, no_votes, num_clients,
client_info_slot, client_info_item)
s2.PrintToServer(string.format("Vote: %d Yes, %d No, %d/%d voted\n",
yes_votes, no_votes, num_votes, num_clients))
local passed = yes_votes > no_votes
if passed then
s2.ServerCommand("mp_restartgame 1")
end
return passed
end
local function on_vote_handler(action, client_slot, choice)
if action == s2.VoteAction.Start then
s2.PrintToServer("Vote started!\n")
elseif action == s2.VoteAction.Vote then
local vote = choice == VOTE_OPTION1 and "Yes" or "No"
s2.PrintToServer(string.format("Player %d voted: %s\n", client_slot, vote))
elseif action == s2.VoteAction.End then
s2.PrintToServer(string.format("Vote ended: %d\n", choice))
end
end
-- Call this once a round is running (for example from a command)
function VoteExample:start_restart_vote()
local started = s2.PanoramaSendYesNoVoteToAll(
30.0,
VOTE_CALLER_SERVER,
"#SFUI_vote_restart_game",
"",
"#SFUI_vote_passed_restart_game",
"",
s2.VoteCreateFailed.Generic,
on_vote_result,
on_vote_handler
)
if not started then
s2.PrintToServer("Could not start the vote\n")
end
end
local M = {}
M.VoteExample = VoteExample
return M
Значения выбора голосования, используемые в обратных вызовах. s2sdk передаёт их как обычные целые числа и не экспортирует это перечисление, поэтому объявите нужные константы в своём плагине:
Чтобы создать голосование для определенных игроков, используйте PanoramaSendYesNoVote с битовой маской получателей (параметр filter). Каждый бит в uint64 представляет слот игрока:
Бит 0 (значение 1) = Слот игрока 0
Бит 1 (значение 2) = Слот игрока 1
Бит 2 (значение 4) = Слот игрока 2
Бит N (значение 2^N) = Слот игрока N
Построение битовой маски: Установите бит N в 1, чтобы включить слот игрока N в голосование. Значение получателей - это сумма всех включенных битовых значений игроков.
Окно голосования показывает строки перевода самой игры из resource/csgo_<язык>.txt. Если в тексте строки есть {s:s1}, игра подставляет туда detailStr (или detailPassStr). Строки без {s:s1} показывают свой фиксированный текст, и строка деталей не видна. Строки для произвольного вопроса в игре нет, поэтому выбирайте ту, что подходит к вашему голосованию:
voteTitle
Текст
votePassTitle
Текст
#SFUI_vote_restart_game
Restart the match?
#SFUI_vote_passed_restart_game
Restarting the match...
#SFUI_vote_changelevel
Change current level to {s:s1}?
#SFUI_vote_passed_changelevel
Changing level to {s:s1}...
#SFUI_vote_nextlevel
Set the next level to {s:s1}?
#SFUI_vote_passed_nextlevel
Next level set to {s:s1}...
#SFUI_vote_kick_player_other
Kick player: {s:s1}?
#SFUI_vote_passed_kick_player
Kicking player: {s:s1}...
#SFUI_vote_scramble_teams
Scramble the teams?
#SFUI_vote_passed_scramble_teams
Teams will be scrambled.
#SFUI_vote_swap_teams
Swap the teams?
#SFUI_vote_passed_swap_teams
Teams will be swapped.
#SFUI_vote_passed
Vote Passed!
Тексты в таблице приведены по английской локализации, у игрока они показываются на его языке.
Требование строк перевода: Используйте только строки перевода, начинающиеся с #SFUI_vote или #Panorama_vote. Другие строки могут некорректно отображаться в UI голосования.
Проверяйте активные голосования - Всегда используйте PanoramaIsVoteInProgress() перед началом нового голосования
Реализуйте пользовательскую логику прохождения - Используйте обратный вызов result для определения, что означает "прохождение" для вашего голосования
Отслеживайте прогресс голосования - Используйте событие VoteAction.Vote обратного вызова handler для мониторинга голосов в реальном времени
Отключения обрабатываются - Отключившиеся игроки удаляются из пула голосования автоматически
Используйте подходящую длительность - 20-30 секунд типично для большинства голосований
Проверяйте получателей - Убедитесь, что в битовой маске получателей есть хотя бы один игрок
Используйте строки перевода - Придерживайтесь строк #SFUI_vote или #Panorama_vote для правильной локализации
Удаляйте цели голосования - Не позволяйте игрокам, против которых голосуют, участвовать
Разделяйте логику - Используйте result для логики прохождения/провала и действий по итогу, handler для событий прогресса
Логируйте данные голосования - Используйте массивы clientInfoSlot и clientInfoItem для детального отслеживания голосов
С системой голосования Panorama вы можете создавать увлекательный демократичный игровой опыт, используя нативный UI CS2 для бесшовного взаимодействия с игроками!