The Word Game. Post #1
Post # 0 - https://steemit.com/hive-171319/@alexmove/the-word-game-start-post-0
Move on. Now there are tables in the database with the comment rating and points for comments, and the rating of posts and points for the length of the post (respectively, for its presence, if the participant did not write the post, then he is not assigned points. But in our case, not just a point is assigned , but depending on the length of the post).
What do we need next? Put it all together. The task is to get a single number of points.
To be @alexmove - 10 points
Moreover, it is necessary to calculate the total number of points, and the number of points in each day. To calculate the total score, you need to create a new table in the database. Something like authors, with id, name and points tables.
And calculate all the points (points) there.
...
Googling, it seems that recalculating all tables at the same time is not the best idea. And it is still better to process each table step by step and add new points to the value. Those. at the time of sorting and displaying what I already have, connect also reading the total number of points and adding new points. And recording, overwriting again into the table.
Created the authors table. Columns id, name, points.
Now I will make a conclusion of all positions.
Points!
As soon as the game starts, then each of the 85 players is awarded 1 points (point). Points are added for comments (taking into account the rating) and for posts (taking into account the rating of the length of posts).
Added for every day.
Working script for ADDING POINTS TO THE TOTAL BASE (TOTAL SCORE):
Пост #0 - https://steemit.com/hive-171319/@alexmove/the-word-game-start-post-0
Идем дальше. Теперь есть таблицы в базе данных с рейтингом комментарий и баллами за комментарии, и рейтингом постов и баллами за длину поста (соответственно и за его наличие, если участник не написал пост, то ему и баллы не присваивается. Но в нашем случае присваивается не просто балл, а в зависимости от длины поста).
Что же нам нужно дальше? Соединить это все вместе. Задача получить единое количество баллов.
Чтобы было @alexmove - 10 points
Причем необходимо просчитывать общее количество баллов, и количество баллов в каждом дне. Чтобы подсчитывать общее количество баллов, необходимо завести новую таблицу в базе данных. Нечто вроде authors, с таблицами id, name и points.
И просчитывать туда все поинты (баллы).
...
Погуглил, похоже что пересчитать все таблицы одновременно не самая лучшая затея. И лучше все же по этапно обработать каждую таблицу и прибавить к значению новые баллы. Т.е. в момент сортировки и вывода, что уже у меня есть, подключить также считывание общего количество баллов и добавление новых баллов. И запись, перезапись вновь в таблицу.
Создал таблицу authors. Столбцы id, name, points.
Сейчас сделаю вывод всех позиций.
Баллы!
Как только игра стартует, то каждому из 85 игроков начисляется 1 points (балл). Баллы прибавляются за комментарии (с учетом рейтинга) и за посты (с учетом рейтинга длины постов).
Добавляются за каждый день.
Рабочий скрипт ДОБАВЛЕНИЯ БАЛЛОВ В ОБЩУЮ БАЗУ (ОБЩИЙ БАЛ):
all-c.js
const mysql = require("mysql2");
const connection = mysql.createConnection({
host: "localhost",
user: "root",
database: "thewordgame",
password: "xxxx"
});
let mytable = 'c1610';
const sql = `SELECT * FROM ${mytable} ORDER BY points DESC` ;
connection.query(sql, function(err, results) {
if(err) console.log(err);
const users = results;
console.log(users);
for(let i=0; i < users.length; i++){
let formula = (users.length - i)/10;
const connection = mysql.createConnection({
host: "localhost",
user: "root",
database: "thewordgame",
password: "xxxx"
});
const sql = `UPDATE ${mytable} SET points=${formula} WHERE id=${users[i].id}`;
//console.log (`UPDATE ${mytable} SET point=${formula} WHERE author=${users[i].id}`);
//console.log (users[i].id);
connection.query(sql,function(err, results) {
if(err) console.log(err);
//console.log(results);
}); //'${formula}'
sql3 = `UPDATE authors SET points=points+'${formula}' WHERE name='${users[i].author}' LIMIT 1000`;
console.log (sql3);
connection.query(sql3,function(err, results) {
if(err) console.log(err);
});
let author = users[i].author;
const sql4 = `INSERT INTO authors(name, points) VALUES('${author}', 1)`;
connection.query(sql4,function(err, results) {
if(err) console.log(err); });
connection.end();
console.log('|',i+1,'|',users[i].author,'|',users[i].length,'|',formula,'|');
}
});
connection.end();
Чтобы сменить таблицу для обработки, нужно заменить поле
let mytable = 'c1610';
таблица безусловно должна быть до этого готова, и она добавляется скриптом для комментариев и постов
Сперва добавить.
Затем all-c.js или all-p.js (отличие очень маленькие).
Добавления происходят с помощью иного скрипта.
addcom.js
const fs = require("fs");
const steem = require('steem');
let input, hive, fullbody, x1;
var author,author2;
var permlinkR;
var err;
let stat, stat2;
let array = fs.readFileSync('spisok.txt').toString().split("\n");
let test_a = array[0].split(' ');
console.log(test_a[2]);
len1 = test_a.length;
for (x1 = 0; x1 < len1; x1++) {
steem.api.getDiscussionsByComments({
"start_author": test_a[x1],
"limit": 100
}, function (err, result) {
console.log(err, result);
if (err === null) {
stat = 0;
console.log('asdasdasdas');
var i, len = result.length;
for (i = 0; i < len; i++) {
var discussion = result[i];
var d = new Date(); // Today!
d.setDate(d.getDate() - 4); // Yesterday!
d = d.toJSON().split("T")[0];
permlinkR = discussion.permlink;
author = discussion.author;
author2 = author;
input = discussion.created;
hive = discussion.category;
// console.log(stat);
if ((input.indexOf(d) !== -1) && (hive === 'hive-171319')) {
stat=stat+1;
stat2 = stat;
fullbody = fullbody + ' ' + discussion.body;
}}
const mysql = require("mysql2");
const connection = mysql.createConnection({
host: "localhost",
user: "root",
database: "thewordgame",
password: "xxx"
});
connection.on('error', function() {});
const sql = `INSERT INTO с1310(author, count) VALUES('${author}', '${stat}')`;
connection.query(sql, function(err, results) {
if(err) console.log(err);
console.log(results);
});
connection.end();
console.log('60 строка');
console.log(stat,author);
} else {
console.log('внимание поломка поломка поломка поломка');
}}
);
}
addpost.js
const fs = require("fs");
const steem = require('steem');
let body3R = '';
let accounts = fs.readFileSync('spisok.txt').toString().split(" ");
console.log(accounts);
accounts.forEach(function (element,i,array){
steem.api.getDiscussionsByAuthorBeforeDate(element,null, new Date().toISOString().split('.')[0],20 , function(err, result) {
// console.log(result);
var i, len = result.length;
for (i = 0; i < len; i++)
{
var raw = result[i];
console.log('Автор');
console.log(raw.author);
console.log('Заголовок');
console.log(raw.author);
console.log('Сообщество');
console.log(raw.category);
console.log('Длина поста');
console.log(raw.body_length);
console.log('Количество ожидаемого вознаграждения');
console.log(raw.pending_payout_value);
console.log('Количество комментариев');
console.log(raw.replies.length);
console.log('Количество upvote');
let upvote = raw.active_votes.length-1;
console.log(raw.active_votes.length-1);
console.log('Дата создания');
console.log(raw.created);
let input = raw.created;
var d = new Date(); // Today!
d.setDate(d.getDate() - 1); // Yesterday!
d = d.toJSON().split("T")[0];
let title = raw.title;
title = title.replace(/[^a-zа-яё0-9\s]/gi, ' ');
if ((input.indexOf(d) !== -1)&& (raw.category === 'hive-171319'))
{
body3R = `| `+raw.author + `| <a href="`+raw.url+`">` + title + `</a>| `+ upvote + `| ` + `????` + `| ` + raw.children+`| ` + raw.body_length+ ' | \n';
console.log(body3R);
const mysql = require("mysql2");
const connection = mysql.createConnection({
host: "localhost",
user: "root",
database: "thewordgame",
password: "xxxx"
});
connection.on('error', function() {});
const sql = `INSERT INTO p1610(author, created, length, url, comments, upvotes ) VALUES('${raw.author}', '${raw.created}', '${raw.body_length}', '${raw.url}', '${raw.children}', '${upvote}')`;
connection.query(sql, function(err, results) {
if(err) console.log(err);
console.log(results);
});
connection.end();
console.log(raw.created);
fs.appendFileSync("rank.txt",body3R);
}
}
});
});
- Сперва создать таблицу
let date_know;
const mysql = require("mysql2");
const connection = mysql.createConnection({
host: "localhost",
user: "root",
database: "thewordgame",
password: "xxxx"
});
let sql = `create table if not exists p1610(
id int primary key auto_increment,
author varchar(255) not null,
created varchar(255) not null,
length int not null,
url varchar(255) not null,
comments int not null,
upvotes int not null,
points int not null
)`;
sql = `create table if not exists all(
id int primary key auto_increment,
c1510 varchar(255) not null,
c1510 int not null
)`;
connection.query(sql, function(err, results) {
if(err) console.log(err);
else console.log("Таблица создана");
});
connection.end();
итак:
Создать таблицу table-c.js и table-p.js (поменять название таблицы)
Затем добавить сами данные. Addpost.js и addcom.js (поменять название таблицы)
Отсортировать, добавить одновременно к общему баллу в общую таблицу all-c.js и all-p.js (поменять название таблицы)
Создать пост в стимите.
Пример:
https://steemit.com/hive-171319/@alexmove/steem-bru-rank-post-17-10-2021-with-sort-real-rank
Спасибо за внимание!
Продолжение следует!